diff --git a/_analysis_config/lib/analysis_options.yaml b/_analysis_config/lib/analysis_options.yaml index 7736d8219..c18e50364 100644 --- a/_analysis_config/lib/analysis_options.yaml +++ b/_analysis_config/lib/analysis_options.yaml @@ -2,11 +2,11 @@ # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. -include: package:lints/recommended.yaml +include: package:dart_flutter_team_lints/analysis_options.yaml analyzer: -# language: -# strict-casts: true + language: + strict-casts: true errors: dead_code: error unused_element: error @@ -15,27 +15,18 @@ analyzer: linter: rules: - - always_declare_return_types - avoid_classes_with_only_static_members - avoid_returning_this - avoid_unused_constructor_parameters - avoid_void_async - cancel_subscriptions - - directives_ordering - join_return_with_assignment - library_names - literal_only_boolean_expressions - - omit_local_variable_types - - only_throw_errors - package_prefixed_library_names - prefer_final_in_for_each - prefer_final_locals - - prefer_single_quotes - # - prefer_relative_imports - prefer_void_to_null - - test_types_in_equals - - throw_in_finally - - unawaited_futures - unnecessary_lambdas - unnecessary_parenthesis - unnecessary_statements diff --git a/_analysis_config/pubspec.yaml b/_analysis_config/pubspec.yaml index 1ac28a4b2..986713cd3 100644 --- a/_analysis_config/pubspec.yaml +++ b/_analysis_config/pubspec.yaml @@ -7,4 +7,4 @@ environment: sdk: ^3.10.0-0.0.dev dependencies: - lints: ^5.0.0 + dart_flutter_team_lints: ^3.5.2 diff --git a/dwds/analysis_options.yaml b/dwds/analysis_options.yaml index 25d27d995..65a354293 100644 --- a/dwds/analysis_options.yaml +++ b/dwds/analysis_options.yaml @@ -6,7 +6,3 @@ analyzer: - "lib/data/*" # Ignore debug extension builds - "debug_extension/compiled/*" - -linter: - rules: - - always_use_package_imports diff --git a/dwds/debug_extension/web/background.dart b/dwds/debug_extension/web/background.dart index 22dc2a9d7..f0fdae0be 100644 --- a/dwds/debug_extension/web/background.dart +++ b/dwds/debug_extension/web/background.dart @@ -61,12 +61,12 @@ void _registerListeners() { } Future _handleRuntimeMessages( - dynamic jsRequest, + Object? jsRequest, MessageSender sender, Function sendResponse, ) async { if (jsRequest is! String) return; - + if (sendResponse is! void Function(Object?)) return; interceptMessage( message: jsRequest, expectedType: MessageType.isAuthenticated, diff --git a/dwds/debug_extension/web/chrome_api.dart b/dwds/debug_extension/web/chrome_api.dart index f69faea26..792dfa8ac 100644 --- a/dwds/debug_extension/web/chrome_api.dart +++ b/dwds/debug_extension/web/chrome_api.dart @@ -233,7 +233,7 @@ class Port { @JS() @anonymous class OnPortMessageHandler { - external void addListener(void Function(dynamic, Port) callback); + external void addListener(void Function(Object?, Port) callback); } @JS() @@ -246,7 +246,7 @@ class ConnectionHandler { @anonymous class OnMessageHandler { external void addListener( - dynamic Function(dynamic, MessageSender, Function) callback, + Object? Function(Object?, MessageSender, Function) callback, ); } @@ -307,16 +307,16 @@ class OnChangedHandler { @JS() @anonymous class Tabs { - external dynamic query( + external Object? query( QueryInfo queryInfo, void Function(List) callback, ); - external dynamic create(TabInfo tabInfo, void Function(Tab) callback); + external Object? create(TabInfo tabInfo, void Function(Tab) callback); - external dynamic get(int tabId, void Function(Tab?) callback); + external Object? get(int tabId, void Function(Tab?) callback); - external dynamic remove(int tabId, void Function()? callback); + external Object? remove(int tabId, void Function()? callback); external Object sendMessage( int tabId, @@ -339,7 +339,7 @@ class OnActivatedHandler { @JS() @anonymous class OnRemovedHandler { - external void addListener(void Function(int tabId, dynamic info) callback); + external void addListener(void Function(int tabId, Object? info) callback); } @JS() @@ -403,7 +403,10 @@ class NavigationInfo { @JS() @anonymous class Windows { - external dynamic create(WindowInfo? createData, Function(WindowObj) callback); + external Object? create( + WindowInfo? createData, + void Function(WindowObj) callback, + ); external OnFocusChangedHandler get onFocusChanged; } diff --git a/dwds/debug_extension/web/cider_connection.dart b/dwds/debug_extension/web/cider_connection.dart index 88a46adaf..009652dd5 100644 --- a/dwds/debug_extension/web/cider_connection.dart +++ b/dwds/debug_extension/web/cider_connection.dart @@ -96,12 +96,12 @@ void sendErrorMessageToCider({ void _sendMessageToCider(String json) { final message = {'key': _ciderDartMessageKey, 'json': json}; - _ciderPort!.postMessage(jsify(message)); + _ciderPort!.postMessage(jsify(message) as Object); } -Future _handleMessageFromCider(dynamic message, Port _) async { - final key = getProperty(message, 'key'); - final json = getProperty(message, 'json'); +Future _handleMessageFromCider(Object? message, Port _) async { + final key = getProperty(message!, 'key'); + final json = getProperty(message, 'json'); if (key != _ciderDartMessageKey || json is! String) { sendErrorMessageToCider( errorType: CiderErrorType.invalidRequest, @@ -110,7 +110,7 @@ Future _handleMessageFromCider(dynamic message, Port _) async { return; } - final decoded = jsonDecode(json) as Map; + final decoded = jsonDecode(json) as Map; final messageType = decoded['messageType'] as String?; final messageBody = decoded['messageBody'] as String?; diff --git a/dwds/debug_extension/web/copier.dart b/dwds/debug_extension/web/copier.dart index 961a11e2b..40b797daa 100644 --- a/dwds/debug_extension/web/copier.dart +++ b/dwds/debug_extension/web/copier.dart @@ -21,16 +21,20 @@ void main() { } void _registerListeners() { - chrome.runtime.onMessage.addListener(allowInterop(_handleRuntimeMessages)); + chrome.runtime.onMessage.addListener( + allowInterop( + _handleRuntimeMessages, + ), + ); } void _handleRuntimeMessages( - dynamic jsRequest, + Object? jsRequest, MessageSender sender, Function sendResponse, ) { interceptMessage( - message: jsRequest, + message: jsRequest as String?, expectedType: MessageType.appId, expectedSender: Script.background, expectedRecipient: Script.copier, @@ -38,7 +42,7 @@ void _handleRuntimeMessages( messageHandler: _copyAppId, ); - sendResponse(defaultResponse); + (sendResponse as void Function(Object?))(defaultResponse); } void _copyAppId(String appId) { diff --git a/dwds/debug_extension/web/cross_extension_communication.dart b/dwds/debug_extension/web/cross_extension_communication.dart index 8b7261e0e..447e03599 100644 --- a/dwds/debug_extension/web/cross_extension_communication.dart +++ b/dwds/debug_extension/web/cross_extension_communication.dart @@ -30,11 +30,16 @@ final _eventsForAngularDartDevTools = { }; Future handleMessagesFromAngularDartDevTools( - dynamic jsRequest, + Object? jsRequest, // ignore: avoid-unused-parameters MessageSender sender, Function sendResponse, ) async { + if (sendResponse is! void Function(Object)) { + throw StateError( + 'Unexpected sendResponse signature: ${sendResponse.runtimeType}', + ); + } if (jsRequest == null) return; final message = jsRequest as ExternalExtensionMessage; if (message.name == 'chrome.debugger.sendCommand') { @@ -53,7 +58,7 @@ Future handleMessagesFromAngularDartDevTools( void maybeForwardMessageToAngularDartDevTools({ required String method, - required dynamic params, + required Object? params, required int tabId, }) { if (!_eventsForAngularDartDevTools.contains(method)) return; @@ -67,7 +72,7 @@ void maybeForwardMessageToAngularDartDevTools({ void _forwardCommandToChromeDebugger( ExternalExtensionMessage message, - Function sendResponse, + void Function(Object) sendResponse, ) { try { final options = message.options as SendCommandOptions; @@ -76,7 +81,7 @@ void _forwardCommandToChromeDebugger( options.method, options.commandParams, allowInterop( - ([result]) => _respondWithChromeResult(result, sendResponse), + ([Object? result]) => _respondWithChromeResult(result, sendResponse), ), ); } catch (e) { @@ -84,7 +89,10 @@ void _forwardCommandToChromeDebugger( } } -void _respondWithChromeResult(Object? chromeResult, Function sendResponse) { +void _respondWithChromeResult( + Object? chromeResult, + void Function(Object) sendResponse, +) { // No result indicates that an error occurred. if (chromeResult == null) { sendResponse( @@ -96,7 +104,10 @@ void _respondWithChromeResult(Object? chromeResult, Function sendResponse) { } } -Future _respondWithEncodedUri(int tabId, Function sendResponse) async { +Future _respondWithEncodedUri( + int tabId, + void Function(Object) sendResponse, +) async { final encodedUri = await fetchStorageObject( type: StorageObject.encodedUri, tabId: tabId, @@ -110,7 +121,7 @@ void _forwardMessageToAngularDartDevTools(ExternalExtensionMessage message) { message, // options null, - allowInterop(([result]) => _checkForErrors(result, message.name)), + allowInterop(([Object? result]) => _checkForErrors(result, message.name)), ); } @@ -124,7 +135,7 @@ void _checkForErrors(Object? chromeResult, String messageName) { ExternalExtensionMessage _debugEventMessage({ required String method, - required dynamic params, + required Object? params, required int tabId, }) => ExternalExtensionMessage( name: 'chrome.debugger.event', @@ -134,7 +145,7 @@ ExternalExtensionMessage _debugEventMessage({ ExternalExtensionMessage _dwdsEventMessage({ required String method, - required dynamic params, + required Object? params, required int tabId, }) => ExternalExtensionMessage(name: method, tabId: tabId, options: params); @@ -145,11 +156,11 @@ ExternalExtensionMessage _dwdsEventMessage({ class ExternalExtensionMessage { external int get tabId; external String get name; - external dynamic get options; + external Object? get options; external factory ExternalExtensionMessage({ required int tabId, required String name, - required dynamic options, + required Object? options, }); } diff --git a/dwds/debug_extension/web/debug_session.dart b/dwds/debug_extension/web/debug_session.dart index 3daf21016..2ce5924cb 100644 --- a/dwds/debug_extension/web/debug_session.dart +++ b/dwds/debug_extension/web/debug_session.dart @@ -278,7 +278,9 @@ Future _onDebuggerEvent( } Future _maybeConnectToDwds(int tabId, Object? params) async { - final context = json.decode(JSON.stringify(params))['context']; + final context = + (json.decode(JSON.stringify(params)) as Map)['context']! + as Map; final contextOrigin = context['origin'] as String?; if (contextOrigin == null) return; if (contextOrigin.contains('chrome-extension:')) return; @@ -320,7 +322,7 @@ Future _isDartFrame({required int tabId, required int contextId}) { returnByValue: true, contextId: contextId, ), - allowInterop((dynamic response) { + allowInterop((Object? response) { final evalResponse = response as _EvalResponse; final value = evalResponse.result.value; final appId = value?[0]; @@ -449,7 +451,7 @@ void _forwardDwdsEventToChromeDebugger( Debuggee(tabId: tabId), message.command, js_util.jsify(params), - allowInterop(([e]) { + allowInterop(([Object? e]) { // No arguments indicate that an error occurred. if (e == null) { client.sink.add( @@ -491,7 +493,7 @@ void _forwardDwdsEventToChromeDebugger( void _forwardChromeDebuggerEventToDwds( Debuggee source, String method, - dynamic params, + Object? params, ) { final debugSession = _debugSessions.firstWhereOrNull( (session) => session.appTabId == source.tabId, @@ -736,7 +738,7 @@ DebuggerLocation? _debuggerLocation(int dartAppTabId) { } /// Construct an [ExtensionEvent] from [method] and [params]. -ExtensionEvent _extensionEventFor(String method, dynamic params) { +ExtensionEvent _extensionEventFor(String method, Object? params) { return ExtensionEvent( (b) => b ..params = jsonEncode(json.decode(JSON.stringify(params))) @@ -783,7 +785,7 @@ class _DebugSession { required this.trigger, required void Function(String data) onIncoming, required void Function() onDone, - required void Function(dynamic error) onError, + required void Function(Object? error) onError, required bool cancelOnError, }) : _socketClient = client { // Collect extension events and send them periodically to the server. diff --git a/dwds/debug_extension/web/detector.dart b/dwds/debug_extension/web/detector.dart index 4c482de26..c3e6d8c34 100644 --- a/dwds/debug_extension/web/detector.dart +++ b/dwds/debug_extension/web/detector.dart @@ -82,11 +82,11 @@ void _detectMultipleDartApps() { } void _detectMultipleDartAppsCallback( - List mutations, + List mutations, MutationObserver observer, ) { for (final mutation in mutations) { - if (_isMultipleAppsMutation(mutation)) { + if (_isMultipleAppsMutation(mutation!)) { _sendMessageToBackgroundScript( type: MessageType.multipleAppsDetected, body: 'true', @@ -96,13 +96,14 @@ void _detectMultipleDartAppsCallback( } } -bool _isMultipleAppsMutation(dynamic mutation) { +bool _isMultipleAppsMutation(Object mutation) { final isAttributeMutation = hasProperty(mutation, 'type') && - getProperty(mutation, 'type') == 'attributes'; + getProperty(mutation, 'type') == 'attributes'; if (isAttributeMutation) { return hasProperty(mutation, 'attributeName') && - getProperty(mutation, 'attributeName') == _multipleAppsAttribute; + getProperty(mutation, 'attributeName') == + _multipleAppsAttribute; } return false; } diff --git a/dwds/debug_extension/web/messaging.dart b/dwds/debug_extension/web/messaging.dart index 8d84ca924..d63198037 100644 --- a/dwds/debug_extension/web/messaging.dart +++ b/dwds/debug_extension/web/messaging.dart @@ -24,7 +24,7 @@ import 'utils.dart'; // // Prevents the message port from closing. See: // https://developer.chrome.com/docs/extensions/mv3/messaging/#simple -final defaultResponse = jsify({'response': 'received'}); +final defaultResponse = jsify({'response': 'received'}) as Map; enum Script { background, @@ -68,7 +68,7 @@ class Message { }); factory Message.fromJSON(String json) { - final decoded = jsonDecode(json) as Map; + final decoded = jsonDecode(json) as Map; return Message( to: Script.fromString(decoded['to'] as String), @@ -161,7 +161,7 @@ Future _sendMessage({ body: body, ).toJSON(); final completer = Completer(); - void responseHandler([dynamic _]) { + void responseHandler([Object? _]) { final error = chrome.runtime.lastError; if (error != null) { debugError( diff --git a/dwds/debug_extension/web/panel.dart b/dwds/debug_extension/web/panel.dart index 825c8fa75..788420bbb 100644 --- a/dwds/debug_extension/web/panel.dart +++ b/dwds/debug_extension/web/panel.dart @@ -80,7 +80,7 @@ Future _registerListeners() async { } void _handleRuntimeMessages( - dynamic jsRequest, + Object? jsRequest, // ignore: avoid-unused-parameters MessageSender sender, // ignore: avoid-unused-parameters diff --git a/dwds/debug_extension/web/storage.dart b/dwds/debug_extension/web/storage.dart index 3413f0302..fade49b7a 100644 --- a/dwds/debug_extension/web/storage.dart +++ b/dwds/debug_extension/web/storage.dart @@ -54,7 +54,7 @@ Future setStorageObject({ final completer = Completer(); final storageArea = _getStorageArea(type.persistence); storageArea.set( - jsify(storageObj), + jsify(storageObj) as Object, allowInterop(() { if (callback != null) { callback(); @@ -151,7 +151,7 @@ void interceptStorageChange({ final isExpected = hasProperty(storageObj, expectedStorageKey); if (!isExpected) return; - final objProp = getProperty(storageObj, expectedStorageKey); + final objProp = getProperty(storageObj, expectedStorageKey); final json = getProperty(objProp, 'newValue') as String?; T? decodedObj; if (json == null || T == String) { diff --git a/dwds/debug_extension/web/utils.dart b/dwds/debug_extension/web/utils.dart index ca842f77c..76f9f6ae1 100644 --- a/dwds/debug_extension/web/utils.dart +++ b/dwds/debug_extension/web/utils.dart @@ -124,7 +124,7 @@ final bool isDevMode = () { final bool isMV3 = () { final extensionManifest = chrome.runtime.getManifest(); final manifestVersion = - getProperty(extensionManifest, 'manifest_version') ?? 2; + getProperty(extensionManifest, 'manifest_version') ?? 2; return manifestVersion == 3; }(); diff --git a/dwds/debug_extension/web/web_api.dart b/dwds/debug_extension/web/web_api.dart index 677959a4f..4cd6e3488 100644 --- a/dwds/debug_extension/web/web_api.dart +++ b/dwds/debug_extension/web/web_api.dart @@ -32,7 +32,7 @@ external Object _nativeJsFetch(String resourceUrl, FetchOptions options); Future fetchRequest(String resourceUrl) async { try { final options = FetchOptions(method: 'GET', credentials: 'include'); - final response = await promiseToFuture( + final response = await promiseToFuture( _nativeJsFetch(resourceUrl, options), ); final body = await promiseToFuture( diff --git a/dwds/lib/config.dart b/dwds/lib/config.dart index aaf119321..ddd51b481 100644 --- a/dwds/lib/config.dart +++ b/dwds/lib/config.dart @@ -5,7 +5,7 @@ export 'src/config/tool_configuration.dart' show AppMetadata, - ToolConfiguration, - UrlEncoder, + DebugSettings, DevToolsLauncher, - DebugSettings; + ToolConfiguration, + UrlEncoder; diff --git a/dwds/lib/dart_web_debug_service.dart b/dwds/lib/dart_web_debug_service.dart index cd699677e..f9602513f 100644 --- a/dwds/lib/dart_web_debug_service.dart +++ b/dwds/lib/dart_web_debug_service.dart @@ -4,22 +4,23 @@ import 'dart:async'; -import 'package:dwds/data/build_result.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/connections/debug_connection.dart'; -import 'package:dwds/src/events.dart'; -import 'package:dwds/src/handlers/dev_handler.dart'; -import 'package:dwds/src/handlers/injector.dart'; -import 'package:dwds/src/handlers/socket_connections.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/servers/devtools.dart'; -import 'package:dwds/src/servers/extension_backend.dart'; import 'package:logging/logging.dart'; import 'package:shelf/shelf.dart'; import 'package:sse/server/sse_handler.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import 'data/build_result.dart'; +import 'src/config/tool_configuration.dart'; +import 'src/connections/app_connection.dart'; +import 'src/connections/debug_connection.dart'; +import 'src/events.dart'; +import 'src/handlers/dev_handler.dart'; +import 'src/handlers/injector.dart'; +import 'src/handlers/socket_connections.dart'; +import 'src/readers/asset_reader.dart'; +import 'src/servers/devtools.dart'; +import 'src/servers/extension_backend.dart'; + typedef ConnectionProvider = Future Function(); /// The Dart Web Debug Service. @@ -145,8 +146,9 @@ class Dwds { debugSettings.expressionCompiler, injected, DartDevelopmentServiceConfiguration( - // This technically isn't correct, but DartDevelopmentServiceConfiguration.enable - // is true by default, so this won't break unmigrated tools. + // This technically isn't correct, but + // DartDevelopmentServiceConfiguration.enable is true by default, so + // this won't break unmigrated tools. // ignore: deprecated_member_use_from_same_package enable: debugSettings.spawnDds && debugSettings.ddsConfiguration.enable, // ignore: deprecated_member_use_from_same_package diff --git a/dwds/lib/data/service_extension_request.dart b/dwds/lib/data/service_extension_request.dart index 53ad2446f..f387a1f0e 100644 --- a/dwds/lib/data/service_extension_request.dart +++ b/dwds/lib/data/service_extension_request.dart @@ -14,10 +14,10 @@ abstract class ServiceExtensionRequest String get argsJson; // Store args as JSON string for built_value compatibility - // Helper method to get args as Map - Map get args => argsJson.isEmpty - ? {} - : json.decode(argsJson) as Map; + // Helper method to get args as Map + Map get args => argsJson.isEmpty + ? {} + : json.decode(argsJson) as Map; ServiceExtensionRequest._(); factory ServiceExtensionRequest([ @@ -28,7 +28,7 @@ abstract class ServiceExtensionRequest factory ServiceExtensionRequest.fromArgs({ required String id, required String method, - required Map args, + required Map args, }) => ServiceExtensionRequest( (b) => b ..id = id diff --git a/dwds/lib/data/service_extension_response.dart b/dwds/lib/data/service_extension_response.dart index 8d833894a..b18307917 100644 --- a/dwds/lib/data/service_extension_response.dart +++ b/dwds/lib/data/service_extension_response.dart @@ -17,10 +17,10 @@ abstract class ServiceExtensionResponse int? get errorCode; String? get errorMessage; - // Helper method to get result as Map - Map? get result => resultJson == null || resultJson!.isEmpty + // Helper method to get result as Map + Map? get result => resultJson == null || resultJson!.isEmpty ? null - : json.decode(resultJson!) as Map; + : json.decode(resultJson!) as Map; ServiceExtensionResponse._(); factory ServiceExtensionResponse([ @@ -31,7 +31,7 @@ abstract class ServiceExtensionResponse factory ServiceExtensionResponse.fromResult({ required String id, required bool success, - Map? result, + Map? result, int? errorCode, String? errorMessage, }) => ServiceExtensionResponse( diff --git a/dwds/lib/dwds.dart b/dwds/lib/dwds.dart index a11ae81be..6c58beb44 100644 --- a/dwds/lib/dwds.dart +++ b/dwds/lib/dwds.dart @@ -2,19 +2,19 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -export 'dart_web_debug_service.dart' show Dwds, ConnectionProvider; +export 'dart_web_debug_service.dart' show ConnectionProvider, Dwds; export 'src/config/tool_configuration.dart' show AppMetadata, - UrlEncoder, DartDevelopmentServiceConfiguration, - DevToolsLauncher, DebugSettings, - ToolConfiguration; + DevToolsLauncher, + ToolConfiguration, + UrlEncoder; export 'src/connections/app_connection.dart' show AppConnection; export 'src/connections/debug_connection.dart' show DebugConnection; export 'src/debugging/metadata/provider.dart' - show MetadataProvider, AbsoluteImportUriException; + show AbsoluteImportUriException, MetadataProvider; export 'src/events.dart' show DwdsEvent; export 'src/handlers/dev_handler.dart' show AppConnectionException; export 'src/handlers/socket_connections.dart'; @@ -28,7 +28,7 @@ export 'src/loaders/frontend_server_strategy_provider.dart' FrontendServerRequireStrategyProvider; export 'src/loaders/require.dart' show RequireStrategy; export 'src/loaders/strategy.dart' - show LoadStrategy, ReloadConfiguration, BuildSettings; + show BuildSettings, LoadStrategy, ReloadConfiguration; export 'src/readers/asset_reader.dart' show AssetReader, PackageUriMapper; export 'src/readers/frontend_server_asset_reader.dart' show FrontendServerAssetReader; @@ -38,12 +38,12 @@ export 'src/services/chrome/chrome_debug_exception.dart' show ChromeDebugException; export 'src/services/expression_compiler.dart' show + CompilerOptions, ExpressionCompilationResult, ExpressionCompiler, - ModuleInfo, - CompilerOptions; + ModuleInfo; export 'src/services/expression_compiler_service.dart' show ExpressionCompilerService; export 'src/utilities/ddc_names.dart'; export 'src/utilities/sdk_configuration.dart' - show SdkLayout, SdkConfiguration, SdkConfigurationProvider; + show SdkConfiguration, SdkConfigurationProvider, SdkLayout; diff --git a/dwds/lib/expression_compiler.dart b/dwds/lib/expression_compiler.dart index 674841406..d020be8ac 100644 --- a/dwds/lib/expression_compiler.dart +++ b/dwds/lib/expression_compiler.dart @@ -4,8 +4,8 @@ export 'src/services/expression_compiler.dart' show + CompilerOptions, ExpressionCompilationResult, ExpressionCompiler, - CompilerOptions, ModuleFormat, ModuleInfo; diff --git a/dwds/lib/sdk_configuration.dart b/dwds/lib/sdk_configuration.dart index 1135d373a..b4608c7e6 100644 --- a/dwds/lib/sdk_configuration.dart +++ b/dwds/lib/sdk_configuration.dart @@ -4,7 +4,7 @@ export 'src/utilities/sdk_configuration.dart' show - SdkLayout, + DefaultSdkConfigurationProvider, SdkConfiguration, SdkConfigurationProvider, - DefaultSdkConfigurationProvider; + SdkLayout; diff --git a/dwds/lib/shared/batched_stream.dart b/dwds/lib/shared/batched_stream.dart index b35592e46..9d6add018 100644 --- a/dwds/lib/shared/batched_stream.dart +++ b/dwds/lib/shared/batched_stream.dart @@ -5,7 +5,7 @@ import 'dart:async'; import 'dart:math'; import 'package:async/async.dart'; -import 'package:dwds/src/utilities/shared.dart'; +import '../src/utilities/shared.dart'; /// Stream controller allowing to batch events. class BatchedStreamController { @@ -40,7 +40,7 @@ class BatchedStreamController { Stream> get stream => _outputController.stream; /// Close the controller. - Future close() { + Future close() { safeUnawaited(_inputController.close()); return _completer.future.then((value) => _outputController.close()); } diff --git a/dwds/lib/src/config/tool_configuration.dart b/dwds/lib/src/config/tool_configuration.dart index f5552b84e..47fb7db97 100644 --- a/dwds/lib/src/config/tool_configuration.dart +++ b/dwds/lib/src/config/tool_configuration.dart @@ -2,9 +2,9 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/loaders/strategy.dart'; -import 'package:dwds/src/servers/devtools.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; +import '../loaders/strategy.dart'; +import '../servers/devtools.dart'; +import '../services/expression_compiler.dart'; /// Configuration about the app, debug settings, and file system. /// diff --git a/dwds/lib/src/connections/app_connection.dart b/dwds/lib/src/connections/app_connection.dart index 26f679dd0..c0d9497b1 100644 --- a/dwds/lib/src/connections/app_connection.dart +++ b/dwds/lib/src/connections/app_connection.dart @@ -5,11 +5,11 @@ import 'dart:async'; import 'dart:convert'; -import 'package:dwds/data/connect_request.dart'; -import 'package:dwds/data/run_request.dart'; -import 'package:dwds/data/serializers.dart'; -import 'package:dwds/src/handlers/socket_connections.dart'; -import 'package:dwds/src/utilities/shared.dart'; +import '../../data/connect_request.dart'; +import '../../data/run_request.dart'; +import '../../data/serializers.dart'; +import '../handlers/socket_connections.dart'; +import '../utilities/shared.dart'; /// A connection between the application loaded in the browser and DWDS. class AppConnection { diff --git a/dwds/lib/src/connections/debug_connection.dart b/dwds/lib/src/connections/debug_connection.dart index cdf315138..3d9f5dd80 100644 --- a/dwds/lib/src/connections/debug_connection.dart +++ b/dwds/lib/src/connections/debug_connection.dart @@ -4,17 +4,18 @@ import 'dart:async'; -import 'package:dwds/src/services/app_debug_services.dart'; -import 'package:dwds/src/services/chrome/chrome_proxy_service.dart'; import 'package:vm_service/vm_service.dart'; +import '../services/app_debug_services.dart'; +import '../services/chrome/chrome_proxy_service.dart'; + /// A debug connection between the application in the browser and DWDS. /// /// Supports debugging your running application through the Dart VM Service /// Protocol. class DebugConnection { final AppDebugServices _appDebugServices; - final _onDoneCompleter = Completer(); + final _onDoneCompleter = Completer(); /// Null until [close] is called. /// diff --git a/dwds/lib/src/debugging/chrome_inspector.dart b/dwds/lib/src/debugging/chrome_inspector.dart index 61c0b001b..f5ebda896 100644 --- a/dwds/lib/src/debugging/chrome_inspector.dart +++ b/dwds/lib/src/debugging/chrome_inspector.dart @@ -4,29 +4,30 @@ import 'dart:math' as math; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/debugging/classes.dart'; -import 'package:dwds/src/debugging/debugger.dart'; -import 'package:dwds/src/debugging/execution_context.dart'; -import 'package:dwds/src/debugging/inspector.dart'; -import 'package:dwds/src/debugging/instance.dart'; -import 'package:dwds/src/debugging/libraries.dart'; -import 'package:dwds/src/debugging/location.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/debugging/remote_debugger.dart'; -import 'package:dwds/src/loaders/ddc_library_bundle.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/utilities/conversions.dart'; -import 'package:dwds/src/utilities/dart_uri.dart'; -import 'package:dwds/src/utilities/domain.dart'; -import 'package:dwds/src/utilities/objects.dart'; -import 'package:dwds/src/utilities/server.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../config/tool_configuration.dart'; +import '../connections/app_connection.dart'; +import '../loaders/ddc_library_bundle.dart'; +import '../readers/asset_reader.dart'; +import '../utilities/conversions.dart'; +import '../utilities/dart_uri.dart'; +import '../utilities/domain.dart'; +import '../utilities/objects.dart'; +import '../utilities/server.dart'; +import '../utilities/shared.dart'; +import 'classes.dart'; +import 'debugger.dart'; +import 'execution_context.dart'; +import 'inspector.dart'; +import 'instance.dart'; +import 'libraries.dart'; +import 'location.dart'; +import 'metadata/provider.dart'; +import 'remote_debugger.dart'; + /// An inspector for a running Dart application contained in the /// [WipConnection]. /// @@ -164,7 +165,8 @@ class ChromeAppInspector extends AppInspector { if (namedArgs.isNotEmpty) { throw UnsupportedError('Named arguments are not yet supported'); } - // We use the JS pseudo-variable 'arguments' to get the list of all arguments. + // We use the JS pseudo-variable 'arguments' to get the list of all + // arguments. final send = globalToolConfiguration.loadStrategy.dartRuntimeDebugger .callInstanceMethodJsExpression(methodName); final remote = await jsCallFunctionOn(receiver, send, positionalArgs); @@ -234,7 +236,7 @@ class ChromeAppInspector extends AppInspector { Future invoke( String targetId, String selector, [ - List arguments = const [], + List arguments = const [], ]) async { final remoteArguments = arguments .cast() @@ -532,7 +534,7 @@ class ChromeAppInspector extends AppInspector { params: {'objectId': rangeId, 'ownProperties': true}, ); return jsProperties - .map((each) => Property(each as Map)) + .map((each) => Property(each as Map)) .where(_isVisibleProperty) .toList(); } diff --git a/dwds/lib/src/debugging/classes.dart b/dwds/lib/src/debugging/classes.dart index eee4fdebf..e96e04cf5 100644 --- a/dwds/lib/src/debugging/classes.dart +++ b/dwds/lib/src/debugging/classes.dart @@ -2,14 +2,15 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/chrome_inspector.dart'; -import 'package:dwds/src/debugging/metadata/class.dart'; -import 'package:dwds/src/services/chrome/chrome_debug_exception.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:vm_service/vm_service.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../config/tool_configuration.dart'; +import '../services/chrome/chrome_debug_exception.dart'; +import '../utilities/shared.dart'; +import 'chrome_inspector.dart'; +import 'metadata/class.dart'; + /// Keeps track of Dart classes available in the running application. class ChromeAppClassHelper { /// Map of class ID to [Class]. @@ -93,7 +94,9 @@ class ChromeAppClassHelper { final classDescriptor = _mapify(result.value); final methodRefs = []; - final methodDescriptors = _mapify(classDescriptor['methods']); + final methodDescriptors = _mapify( + classDescriptor['methods'], + ).cast>(); methodDescriptors.forEach((name, descriptor) { final methodId = 'methods|$classId|$name'; methodRefs.add( @@ -112,7 +115,9 @@ class ChromeAppClassHelper { }); final fieldRefs = []; - final fieldDescriptors = _mapify(classDescriptor['fields']); + final fieldDescriptors = _mapify( + classDescriptor['fields'], + ).cast>(); fieldDescriptors.forEach((name, descriptor) { final classMetaData = ClassMetaData( runtimeKind: RuntimeObjectKind.type, @@ -163,6 +168,6 @@ class ChromeAppClassHelper { ); } - Map _mapify(dynamic map) => - (map as Map?) ?? {}; + Map _mapify(Object? map) => + (map as Map?) ?? {}; } diff --git a/dwds/lib/src/debugging/dart_runtime_debugger.dart b/dwds/lib/src/debugging/dart_runtime_debugger.dart index a3e24bb7e..669eb5b03 100644 --- a/dwds/lib/src/debugging/dart_runtime_debugger.dart +++ b/dwds/lib/src/debugging/dart_runtime_debugger.dart @@ -2,7 +2,7 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/loaders/strategy.dart'; +import '../loaders/strategy.dart'; class DartRuntimeDebugger { final LoadStrategy _loadStrategy; @@ -107,7 +107,8 @@ class DartRuntimeDebugger { /// Generates a JS expression for retrieving Dart Developer Extension Names. String getDartDeveloperExtensionNamesJsExpression() { return _generateJsExpression( - "${_loadStrategy.loadModuleSnippet}('dart_sdk').developer._extensions.keys.toList();", + "${_loadStrategy.loadModuleSnippet}('dart_sdk')'" + '.developer._extensions.keys.toList();"', 'dartDevEmbedder.debugger.extensionNames', ); } @@ -180,10 +181,12 @@ class DartRuntimeDebugger { return _generateJsExpression( generateInstanceMethodJsExpression( - '${_loadStrategy.loadModuleSnippet}("dart_sdk").dart.dsendRepl(this, "$methodName", arguments)', + '${_loadStrategy.loadModuleSnippet}("dart_sdk").dart.dsendRepl(this, ' + '"$methodName", arguments)', ), generateInstanceMethodJsExpression( - 'dartDevEmbedder.debugger.callInstanceMethod(this, "$methodName", arguments)', + 'dartDevEmbedder.debugger.callInstanceMethod(this, "$methodName", ' + 'arguments)', ), ); } @@ -191,8 +194,11 @@ class DartRuntimeDebugger { /// Generates a JS expression to invoke a Dart extension method. String invokeExtensionJsExpression(String methodName, String encodedJson) { return _generateJsExpression( - "${_loadStrategy.loadModuleSnippet}('dart_sdk').developer.invokeExtension('$methodName', JSON.stringify($encodedJson));", - "dartDevEmbedder.debugger.invokeExtension('$methodName', JSON.stringify($encodedJson));", + "${_loadStrategy.loadModuleSnippet}('dart_sdk')" + ".developer.invokeExtension('$methodName'," + 'JSON.stringify($encodedJson));', + "dartDevEmbedder.debugger.invokeExtension('$methodName'," + 'JSON.stringify($encodedJson));', ); } @@ -209,14 +215,15 @@ class DartRuntimeDebugger { })(); '''; - // `callLibraryMethod` expects an array of arguments. Chrome DevTools spreads - // arguments individually when calling functions. This code reconstructs the - // expected argument array. + // `callLibraryMethod` expects an array of arguments. Chrome DevTools + // spreads arguments individually when calling functions. This code + // reconstructs the expected argument array. return _generateJsExpression( findLibraryExpression, _wrapWithBundleLoader( '', - 'callLibraryMethod("$libraryUri", "$methodName", Array.from(arguments))', + 'callLibraryMethod("$libraryUri", "$methodName", ' + 'Array.from(arguments))', ), ); } diff --git a/dwds/lib/src/debugging/dart_scope.dart b/dwds/lib/src/debugging/dart_scope.dart index 63c825bce..289b9a96e 100644 --- a/dwds/lib/src/debugging/dart_scope.dart +++ b/dwds/lib/src/debugging/dart_scope.dart @@ -2,10 +2,11 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/debugging/chrome_inspector.dart'; -import 'package:dwds/src/utilities/objects.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../utilities/objects.dart'; +import 'chrome_inspector.dart'; + /// The regular expressions used to filter out temp variables. /// Needs to be kept in sync with SDK repo. /// diff --git a/dwds/lib/src/debugging/debugger.dart b/dwds/lib/src/debugging/debugger.dart index 38e063e32..ba9bf5ec4 100644 --- a/dwds/lib/src/debugging/debugger.dart +++ b/dwds/lib/src/debugging/debugger.dart @@ -4,27 +4,28 @@ import 'dart:async'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/chrome_inspector.dart'; -import 'package:dwds/src/debugging/dart_scope.dart'; -import 'package:dwds/src/debugging/frame_computer.dart'; -import 'package:dwds/src/debugging/inspector.dart'; -import 'package:dwds/src/debugging/location.dart'; -import 'package:dwds/src/debugging/remote_debugger.dart'; -import 'package:dwds/src/debugging/skip_list.dart'; -import 'package:dwds/src/services/chrome/chrome_debug_exception.dart'; -import 'package:dwds/src/utilities/dart_uri.dart'; -import 'package:dwds/src/utilities/domain.dart'; -import 'package:dwds/src/utilities/objects.dart' show Property; -import 'package:dwds/src/utilities/server.dart'; -import 'package:dwds/src/utilities/shared.dart'; -import 'package:dwds/src/utilities/synchronized.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'package:vm_service/vm_service.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart' hide StackTrace; +import '../config/tool_configuration.dart'; +import '../services/chrome/chrome_debug_exception.dart'; +import '../utilities/dart_uri.dart'; +import '../utilities/domain.dart'; +import '../utilities/objects.dart' show Property; +import '../utilities/server.dart'; +import '../utilities/shared.dart'; +import '../utilities/synchronized.dart'; +import 'chrome_inspector.dart'; +import 'dart_scope.dart'; +import 'frame_computer.dart'; +import 'inspector.dart'; +import 'location.dart'; +import 'remote_debugger.dart'; +import 'skip_list.dart'; + /// Adds [event] to the stream with [streamId] if there is anybody listening /// on that stream. typedef StreamNotify = void Function(String streamId, Event event); @@ -68,7 +69,7 @@ class Debugger { this._streamNotify, this._locations, this._skipLists, - root, + String root, ) : _breakpoints = _Breakpoints( locations: _locations, remoteDebugger: _remoteDebugger, @@ -346,8 +347,8 @@ class Debugger { /// If we do not have [Location] data for the embedded JS location, null is /// returned. Future _sourceLocation(DebuggerPausedEvent e) async { - final frame = e.params?['callFrames']?[0]; - final location = frame?['location']; + final frame = (e.params?['callFrames'] as List>?)?[0]; + final location = frame?['location'] as Map?; if (location == null) return null; final scriptId = location['scriptId'] as String?; @@ -368,8 +369,9 @@ class Debugger { /// Returns script ID for the paused event. String? _frameScriptId(DebuggerPausedEvent e) { - final frame = e.params?['callFrames']?[0]; - return frame?['location']?['scriptId'] as String?; + final frame = (e.params?['callFrames'] as List>?)?[0]; + return (frame?['location'] as Map?)?['scriptId'] + as String?; } /// The variables visible in a frame in Dart protocol [BoundVariable] form. @@ -422,6 +424,7 @@ class Debugger { // void _showPausedOverlay() async { // if (_pausedOverlayVisible) return; // handleErrorIfPresent(await _remoteDebugger?.sendCommand('DOM.enable')); + // ignore: lines_longer_than_80_chars // handleErrorIfPresent(await _remoteDebugger?.sendCommand('Overlay.enable')); // handleErrorIfPresent(await _remoteDebugger // ?.sendCommand('Overlay.setPausedInDebuggerMessage', params: { @@ -433,6 +436,7 @@ class Debugger { // Removes the paused at breakpoint overlay from the application. // void _hidePausedOverlay() async { // if (!_pausedOverlayVisible) return; + // ignore: lines_longer_than_80_chars // handleErrorIfPresent(await _remoteDebugger?.sendCommand('Overlay.disable')); // _pausedOverlayVisible = false; // } @@ -498,7 +502,8 @@ class Debugger { void logAnyFrameErrors({required String frameType}) { if (_frameErrorCount > 0) { logger.warning( - 'Error calculating Dart variables for $_frameErrorCount $frameType frames.', + 'Error calculating Dart variables for $_frameErrorCount $frameType ' + 'frames.', ); } _frameErrorCount = 0; @@ -556,8 +561,8 @@ class Debugger { } else if (e.reason == 'exception' || e.reason == 'assert') { InstanceRef? exception; - if (e.data is Map) { - final map = e.data as Map; + if (e.data is Map) { + final map = e.data as Map; if (map['type'] == 'object') { final obj = RemoteObject(map); exception = await inspector.instanceRefFor(obj); @@ -745,7 +750,7 @@ Future sendCommandAndValidateResult( RemoteDebugger remoteDebugger, { required String method, required String resultField, - Map? params, + Map? params, }) async { final response = await remoteDebugger.sendCommand(method, params: params); final result = response.result?[resultField]; @@ -757,7 +762,7 @@ Future sendCommandAndValidateResult( params, ); } - return result; + return result as T; } /// Returns the breakpoint ID for the provided Dart script ID and Dart line diff --git a/dwds/lib/src/debugging/execution_context.dart b/dwds/lib/src/debugging/execution_context.dart index 9662b3914..9249900f5 100644 --- a/dwds/lib/src/debugging/execution_context.dart +++ b/dwds/lib/src/debugging/execution_context.dart @@ -5,9 +5,10 @@ import 'dart:async'; import 'package:async/async.dart'; -import 'package:dwds/src/debugging/remote_debugger.dart'; import 'package:logging/logging.dart'; +import 'remote_debugger.dart'; + abstract class ExecutionContext { /// Returns the context ID that contains the running Dart application, /// if available. @@ -52,7 +53,8 @@ class RemoteDebuggerExecutionContext extends ExecutionContext { 'contextId': context, }, ); - if (result.result?['result']?['value'] != null) { + if ((result.result?['result'] as Map?)?['value'] != + null) { _logger.fine('Found dart execution context: $context'); return context; } @@ -87,10 +89,11 @@ class RemoteDebuggerExecutionContext extends ExecutionContext { _remoteDebugger .eventStream('Runtime.executionContextCreated', (e) { // Parse and add the context ID to the stream. - // If we cannot detect or parse the context ID, add `null` to the stream - // to indicate an error context - those will be skipped when trying to find - // the dart context, with a warning. - final id = e.params?['context']?['id']?.toString(); + // If we cannot detect or parse the context ID, add `null` to the + // stream to indicate an error context - those will be skipped when + // trying to find the dart context, with a warning. + final id = (e.params?['context'] as Map?)?['id'] + ?.toString(); final parsedId = id == null ? null : int.parse(id); if (id == null) { _logger.warning('Cannot find execution context id: $e'); diff --git a/dwds/lib/src/debugging/frame_computer.dart b/dwds/lib/src/debugging/frame_computer.dart index 2f76d2853..4f07e24fe 100644 --- a/dwds/lib/src/debugging/frame_computer.dart +++ b/dwds/lib/src/debugging/frame_computer.dart @@ -2,12 +2,13 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/debugging/debugger.dart'; -import 'package:dwds/src/utilities/synchronized.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../utilities/synchronized.dart'; +import 'debugger.dart'; + class FrameComputer { static final logger = Logger('FrameComputer'); @@ -112,7 +113,7 @@ class FrameComputer { 'url': callFrame.url, 'functionName': callFrame.functionName, 'location': location.json, - 'scopeChain': [], + 'scopeChain': >[], }); final frame = await debugger.calculateDartFrameFor( diff --git a/dwds/lib/src/debugging/inspector.dart b/dwds/lib/src/debugging/inspector.dart index 5827a77a3..307663c08 100644 --- a/dwds/lib/src/debugging/inspector.dart +++ b/dwds/lib/src/debugging/inspector.dart @@ -5,16 +5,17 @@ import 'dart:collection'; import 'package:async/async.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/debugging/libraries.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/utilities/dart_uri.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:meta/meta.dart'; import 'package:vm_service/vm_service.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../config/tool_configuration.dart'; +import '../connections/app_connection.dart'; +import '../utilities/dart_uri.dart'; +import '../utilities/shared.dart'; +import 'libraries.dart'; +import 'metadata/provider.dart'; + /// An inspector for a running Dart application contained in the /// [WipConnection]. /// @@ -181,7 +182,8 @@ abstract class AppInspector { final parts = scripts[uri]; final scriptRefs = [ ScriptRef(uri: uri, id: createId()), - for (final part in parts ?? []) ScriptRef(uri: part, id: createId()), + for (final part in parts ?? []) + ScriptRef(uri: part, id: createId()), ]; final libraryRef = await libraryHelper.libraryRefFor(uri); final libraryId = libraryRef?.id; diff --git a/dwds/lib/src/debugging/instance.dart b/dwds/lib/src/debugging/instance.dart index 34b5da734..58206b4bc 100644 --- a/dwds/lib/src/debugging/instance.dart +++ b/dwds/lib/src/debugging/instance.dart @@ -4,17 +4,18 @@ import 'dart:math'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/chrome_inspector.dart'; -import 'package:dwds/src/debugging/metadata/class.dart'; -import 'package:dwds/src/debugging/metadata/function.dart'; -import 'package:dwds/src/utilities/conversions.dart'; -import 'package:dwds/src/utilities/objects.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../config/tool_configuration.dart'; +import '../utilities/conversions.dart'; +import '../utilities/objects.dart'; +import '../utilities/shared.dart'; +import 'chrome_inspector.dart'; +import 'metadata/class.dart'; +import 'metadata/function.dart'; + /// Contains a set of methods for getting [Instance]s and [InstanceRef]s. class ChromeAppInstanceHelper { final _logger = Logger('InstanceHelper'); @@ -226,8 +227,8 @@ class ChromeAppInstanceHelper { ); } - /// Create a plain instance of [classRef] from [remoteObject] and the JS - /// properties [properties]. + /// Create a plain instance of classRef from [remoteObject] and the JS + /// properties properties. Future _plainInstanceFor( ClassMetaData metaData, RemoteObject remoteObject, { @@ -331,14 +332,14 @@ class ChromeAppInstanceHelper { return associations; } - /// Create a Map instance with class [classRef] from [remoteObject]. + /// Create a Map instance with class classRef from [remoteObject]. /// /// Returns an instance containing [count] associations, if available, /// starting from the [offset]. /// /// If [offset] is `null`, assumes 0 offset. /// If [count] is `null`, return all fields starting from the offset. - /// [length] is the expected length of the whole object, read from + /// length is the expected length of the whole object, read from /// the [ClassMetaData]. Future _mapInstanceFor( ClassMetaData metaData, @@ -372,14 +373,14 @@ class ChromeAppInstanceHelper { ); } - /// Create a List instance of [classRef] from [remoteObject]. + /// Create a List instance of classRef from [remoteObject]. /// /// Returns an instance containing [count] elements, if available, /// starting from the [offset]. /// /// If [offset] is `null`, assumes 0 offset. /// If [count] is `null`, return all fields starting from the offset. - /// [length] is the expected length of the whole object, read from + /// length is the expected length of the whole object, read from /// the [ClassMetaData]. Future _listInstanceFor( ClassMetaData metaData, @@ -469,7 +470,7 @@ class ChromeAppInstanceHelper { /// and `named` fields. /// /// Returns list of field names for the record shape. - Future> _recordShapeFields( + Future> _recordShapeFields( RemoteObject shape, { int? offset, int? count, @@ -519,7 +520,10 @@ class ChromeAppInstanceHelper { count: namedRangeCount, ); final namedElements = - namedInstance?.elements?.map((e) => e.valueAsString) ?? []; + namedInstance?.elements?.cast().map( + (e) => e.valueAsString, + ) ?? + []; return [...positionalElements, ...namedElements]; } @@ -562,8 +566,8 @@ class ChromeAppInstanceHelper { /// Create a list of `BoundField`s from field [names] and [values]. List _elementsToBoundFields( - List names, - List values, + List names, + List values, ) { if (names.length != values.length) { _logger.warning('Bound field names and values are not the same length.'); @@ -581,14 +585,14 @@ class ChromeAppInstanceHelper { return requested < collected ? 0 : requested - collected; } - /// Create a Record instance with class [classRef] from [remoteObject]. + /// Create a Record instance with class classRef from [remoteObject]. /// /// Returns an instance containing [count] fields, if available, /// starting from the [offset]. /// /// If [offset] is `null`, assumes 0 offset. /// If [count] is `null`, return all fields starting from the offset. - /// [length] is the expected length of the whole object, read from + /// length is the expected length of the whole object, read from /// the [ClassMetaData]. Future _recordInstanceFor( ClassMetaData metaData, @@ -621,14 +625,14 @@ class ChromeAppInstanceHelper { ); } - /// Create a RecordType instance with class [classRef] from [remoteObject]. + /// Create a RecordType instance with class classRef from [remoteObject]. /// /// Returns an instance containing [count] fields, if available, /// starting from the [offset]. /// /// If [offset] is `null`, assumes 0 offset. /// If [count] is `null`, return all fields starting from the offset. - /// [length] is the expected length of the whole object, read from + /// length is the expected length of the whole object, read from /// the [ClassMetaData]. Future _recordTypeInstanceFor( ClassMetaData metaData, @@ -742,13 +746,13 @@ class ChromeAppInstanceHelper { return setInstance; } - /// Create Type instance with class [classRef] from [remoteObject]. + /// Create Type instance with class classRef from [remoteObject]. /// /// Collect information from the internal [remoteObject] and present /// it as an instance of [Type] class. /// /// Returns an instance containing `hashCode` and `runtimeType` fields. - /// [length] is the expected length of the whole object, read from + /// length is the expected length of the whole object, read from /// the [ClassMetaData]. Future _plainTypeInstanceFor( ClassMetaData metaData, diff --git a/dwds/lib/src/debugging/libraries.dart b/dwds/lib/src/debugging/libraries.dart index d551f77db..5ef003573 100644 --- a/dwds/lib/src/debugging/libraries.dart +++ b/dwds/lib/src/debugging/libraries.dart @@ -3,17 +3,18 @@ // BSD-style license that can be found in the LICENSE file. import 'package:collection/collection.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/chrome_inspector.dart'; -import 'package:dwds/src/debugging/inspector.dart'; -import 'package:dwds/src/debugging/metadata/class.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/services/chrome/chrome_debug_exception.dart'; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; import 'package:vm_service/vm_service.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../config/tool_configuration.dart'; +import '../services/chrome/chrome_debug_exception.dart'; +import 'chrome_inspector.dart'; +import 'inspector.dart'; +import 'metadata/class.dart'; +import 'metadata/provider.dart'; + /// Keeps track of Dart libraries available in the running application. class LibraryHelper { final Logger _logger = Logger('LibraryHelper'); diff --git a/dwds/lib/src/debugging/location.dart b/dwds/lib/src/debugging/location.dart index d983f280f..168df1864 100644 --- a/dwds/lib/src/debugging/location.dart +++ b/dwds/lib/src/debugging/location.dart @@ -3,16 +3,17 @@ // BSD-style license that can be found in the LICENSE file. import 'package:async/async.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/debugging/modules.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/utilities/dart_uri.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'package:source_maps/parser.dart'; import 'package:source_maps/source_maps.dart'; +import '../config/tool_configuration.dart'; +import '../readers/asset_reader.dart'; +import '../utilities/dart_uri.dart'; +import 'metadata/provider.dart'; +import 'modules.dart'; + var _startTokenId = 1337; /// A source location, with both Dart and JS information. @@ -395,10 +396,10 @@ class Locations { }) { final index = entry.sourceUrlId; if (index == null) return null; - // Source map URLS are relative to the script. They may have platform separators - // or they may use URL semantics. To be sure, we split and re-join them. - // This works on Windows because path treats both / and \ as separators. - // It will fail if the path has both separators in it. + // Source map URLS are relative to the script. They may have platform + // separators or they may use URL semantics. To be sure, we split and + // re-join them. This works on Windows because path treats both / and + // \ as separators. It will fail if the path has both separators in it. final relativeSegments = p.split(sourceUrls[index]); final path = p.url.normalize( p.url.joinAll([scriptLocation, ...relativeSegments]), diff --git a/dwds/lib/src/debugging/metadata/class.dart b/dwds/lib/src/debugging/metadata/class.dart index 79037e683..903fbb641 100644 --- a/dwds/lib/src/debugging/metadata/class.dart +++ b/dwds/lib/src/debugging/metadata/class.dart @@ -2,13 +2,14 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/chrome_inspector.dart'; -import 'package:dwds/src/services/chrome/chrome_debug_exception.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../../config/tool_configuration.dart'; +import '../../services/chrome/chrome_debug_exception.dart'; +import '../chrome_inspector.dart'; + const _dartCoreLibrary = 'dart:core'; /// A hard-coded ClassRef for the Closure class. @@ -169,7 +170,9 @@ class ChromeClassMetaDataHelper { final typeName = metadata['typeName']; final library = metadata['libraryId']; - final runtimeKind = RuntimeObjectKind.parse(metadata['runtimeKind']); + final runtimeKind = RuntimeObjectKind.parse( + metadata['runtimeKind'] as String, + ); final length = metadata['length']; final classRef = classRefFor(library, className); diff --git a/dwds/lib/src/debugging/metadata/function.dart b/dwds/lib/src/debugging/metadata/function.dart index 62cdf9176..7dccbd70d 100644 --- a/dwds/lib/src/debugging/metadata/function.dart +++ b/dwds/lib/src/debugging/metadata/function.dart @@ -2,11 +2,12 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/remote_debugger.dart'; -import 'package:dwds/src/utilities/server.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../../config/tool_configuration.dart'; +import '../../utilities/server.dart'; +import '../remote_debugger.dart'; + /// Meta data for a remote Dart function in Chrome. class FunctionMetaData { final String name; @@ -31,7 +32,9 @@ class FunctionMetaData { }, ); handleErrorIfPresent(response, evalContents: evalExpression); - final name = response.result?['result']?['value'] as String?; + final name = + (response.result?['result'] as Map?)?['value'] + as String?; if (name == null) return FunctionMetaData(''); if (name.isEmpty) return FunctionMetaData('Closure'); return FunctionMetaData(name); diff --git a/dwds/lib/src/debugging/metadata/module_metadata.dart b/dwds/lib/src/debugging/metadata/module_metadata.dart index 02e1dec61..673b6613b 100644 --- a/dwds/lib/src/debugging/metadata/module_metadata.dart +++ b/dwds/lib/src/debugging/metadata/module_metadata.dart @@ -76,12 +76,12 @@ class LibraryMetadata { LibraryMetadata(this.name, this.importUri, this.partUris); - LibraryMetadata.fromJson(Map json) + LibraryMetadata.fromJson(Map json) : name = _readRequiredField(json, 'name'), importUri = _readRequiredField(json, 'importUri'), partUris = _readOptionalList(json, 'partUris') ?? []; - Map toJson() { + Map toJson() { return { 'name': name, 'importUri': importUri, @@ -147,7 +147,7 @@ class ModuleMetadata { } } - ModuleMetadata.fromJson(Map json) + ModuleMetadata.fromJson(Map json) : version = _readRequiredField(json, 'version'), name = _readRequiredField(json, 'name'), closureName = _readRequiredField(json, 'closureName'), @@ -163,12 +163,15 @@ class ModuleMetadata { ); } - for (final l in _readRequiredList(json, 'libraries')) { - addLibrary(LibraryMetadata.fromJson(l as Map)); + for (final l in _readRequiredList>( + json, + 'libraries', + )) { + addLibrary(LibraryMetadata.fromJson(l)); } } - Map toJson() { + Map toJson() { return { 'version': version, 'name': name, @@ -180,22 +183,22 @@ class ModuleMetadata { } } -T _readRequiredField(Map json, String field) { +T _readRequiredField(Map json, String field) { if (!json.containsKey(field)) { throw FormatException('Required field $field is not set in $json'); } return json[field]! as T; } -T? _readOptionalField(Map json, String field) => +T? _readOptionalField(Map json, String field) => json[field] as T?; -List _readRequiredList(Map json, String field) { - final list = _readRequiredField>(json, field); - return List.castFrom(list); +List _readRequiredList(Map json, String field) { + final list = _readRequiredField>(json, field); + return List.castFrom(list); } -List? _readOptionalList(Map json, String field) { - final list = _readOptionalField>(json, field); - return list == null ? null : List.castFrom(list); +List? _readOptionalList(Map json, String field) { + final list = _readOptionalField>(json, field); + return list == null ? null : List.castFrom(list); } diff --git a/dwds/lib/src/debugging/metadata/provider.dart b/dwds/lib/src/debugging/metadata/provider.dart index 1ebdde882..10dc186f8 100644 --- a/dwds/lib/src/debugging/metadata/provider.dart +++ b/dwds/lib/src/debugging/metadata/provider.dart @@ -5,11 +5,12 @@ import 'dart:convert'; import 'package:async/async.dart'; -import 'package:dwds/src/debugging/metadata/module_metadata.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; +import '../../readers/asset_reader.dart'; +import 'module_metadata.dart'; + /// A provider of metadata in which data is collected through DDC outputs. class MetadataProvider { final AssetReader _assetReader; @@ -22,7 +23,7 @@ class MetadataProvider { final Map _moduleToModulePath = {}; final Map> _moduleToLibraries = {}; final Map> _scripts = {}; - final _metadataMemoizer = AsyncMemoizer(); + final _metadataMemoizer = AsyncMemoizer(); /// Implicitly imported libraries in any DDC component. /// @@ -183,7 +184,7 @@ class MetadataProvider { } final moduleJson = json.decode(contents); final metadata = ModuleMetadata.fromJson( - moduleJson as Map, + moduleJson as Map, ); final moduleName = metadata.name; modules[moduleName] = metadata; diff --git a/dwds/lib/src/debugging/modules.dart b/dwds/lib/src/debugging/modules.dart index 7c676c99b..decd2ad7e 100644 --- a/dwds/lib/src/debugging/modules.dart +++ b/dwds/lib/src/debugging/modules.dart @@ -3,12 +3,13 @@ // BSD-style license that can be found in the LICENSE file. import 'package:async/async.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/debugger.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/utilities/dart_uri.dart'; import 'package:logging/logging.dart'; +import '../config/tool_configuration.dart'; +import '../utilities/dart_uri.dart'; +import 'debugger.dart'; +import 'metadata/provider.dart'; + /// Tracks modules for the compiled application. class Modules { final _logger = Logger('Modules'); @@ -96,7 +97,8 @@ class Modules { return _moduleToSources[module]; } - /// Returns the containing library importUri for the provided Dart server path. + /// Returns the containing library importUri for the provided Dart server + /// path. Future libraryForSource(String serverPath) async { await _moduleMemoizer.runOnce(_initializeMapping); return _sourceToLibrary[serverPath]; diff --git a/dwds/lib/src/debugging/remote_debugger.dart b/dwds/lib/src/debugging/remote_debugger.dart index 48657ce81..8565922d2 100644 --- a/dwds/lib/src/debugging/remote_debugger.dart +++ b/dwds/lib/src/debugging/remote_debugger.dart @@ -30,7 +30,7 @@ abstract class RemoteDebugger { Future sendCommand( String command, { - Map? params, + Map? params, }); Future disable(); @@ -47,11 +47,11 @@ abstract class RemoteDebugger { Future removeBreakpoint(String breakpointId); - Future stepInto({Map? params}); + Future stepInto({Map? params}); Future stepOut(); - Future stepOver({Map? params}); + Future stepOver({Map? params}); Future enablePage(); diff --git a/dwds/lib/src/debugging/skip_list.dart b/dwds/lib/src/debugging/skip_list.dart index 6256f823c..8839acf37 100644 --- a/dwds/lib/src/debugging/skip_list.dart +++ b/dwds/lib/src/debugging/skip_list.dart @@ -2,16 +2,16 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/location.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/utilities/dart_uri.dart'; +import '../config/tool_configuration.dart'; +import '../utilities/dart_uri.dart'; +import 'location.dart'; +import 'metadata/provider.dart'; const maxValue = 2147483647; class SkipLists { // Map of script ID to scriptList. - final _idToList = >>{}; + final _idToList = >>{}; // Map of url to script ID. final _urlToId = {}; final String _root; @@ -49,7 +49,7 @@ class SkipLists { /// https://chromedevtools.github.io/devtools-protocol/tot/Debugger/#method-stepInto /// /// Can return a cached value. - List> compute( + List> compute( String scriptId, String url, Set locations, @@ -59,7 +59,7 @@ class SkipLists { final sortedLocations = locations.toList() ..sort((a, b) => a.jsLocation.compareTo(b.jsLocation)); - final ranges = >[]; + final ranges = >[]; var startLine = 0; var startColumn = 0; for (final location in sortedLocations) { @@ -90,7 +90,7 @@ class SkipLists { return ranges; } - Map _rangeFor( + Map _rangeFor( String scriptId, int startLine, int startColumn, diff --git a/dwds/lib/src/debugging/web_socket_inspector.dart b/dwds/lib/src/debugging/web_socket_inspector.dart index 5b5a6f01b..1e44ccfa5 100644 --- a/dwds/lib/src/debugging/web_socket_inspector.dart +++ b/dwds/lib/src/debugging/web_socket_inspector.dart @@ -2,13 +2,14 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/debugging/inspector.dart'; -import 'package:dwds/src/debugging/libraries.dart'; -import 'package:dwds/src/services/web_socket/web_socket_proxy_service.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:vm_service/vm_service.dart'; +import '../connections/app_connection.dart'; +import '../services/web_socket/web_socket_proxy_service.dart'; +import '../utilities/shared.dart'; +import 'inspector.dart'; +import 'libraries.dart'; + /// Provides information about the currently loaded program. class WebSocketAppInspector extends AppInspector { WebSocketAppInspector._( diff --git a/dwds/lib/src/debugging/webkit_debugger.dart b/dwds/lib/src/debugging/webkit_debugger.dart index 6e3806947..c326d47e5 100644 --- a/dwds/lib/src/debugging/webkit_debugger.dart +++ b/dwds/lib/src/debugging/webkit_debugger.dart @@ -2,9 +2,10 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/debugging/remote_debugger.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import 'remote_debugger.dart'; + /// A remote debugger with a Webkit Inspection Protocol connection. class WebkitDebugger implements RemoteDebugger { final WipDebugger _wipDebugger; @@ -27,7 +28,7 @@ class WebkitDebugger implements RemoteDebugger { @override Future sendCommand( String command, { - Map? params, + Map? params, }) => _wipDebugger.sendCommand(command, params: params); @override @@ -58,14 +59,14 @@ class WebkitDebugger implements RemoteDebugger { _wipDebugger.removeBreakpoint(breakpointId); @override - Future stepInto({Map? params}) => + Future stepInto({Map? params}) => _wipDebugger.stepInto(params: params); @override Future stepOut() => _wipDebugger.stepOut(); @override - Future stepOver({Map? params}) => + Future stepOver({Map? params}) => _wipDebugger.stepOver(params: params); @override diff --git a/dwds/lib/src/dwds_vm_client.dart b/dwds/lib/src/dwds_vm_client.dart index a6426cbd1..b677617be 100644 --- a/dwds/lib/src/dwds_vm_client.dart +++ b/dwds/lib/src/dwds_vm_client.dart @@ -5,17 +5,6 @@ import 'dart:async'; import 'dart:convert'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/events.dart'; -import 'package:dwds/src/loaders/ddc_library_bundle.dart'; -import 'package:dwds/src/services/chrome/chrome_debug_exception.dart'; -import 'package:dwds/src/services/chrome/chrome_debug_service.dart'; -import 'package:dwds/src/services/chrome/chrome_proxy_service.dart'; -import 'package:dwds/src/services/debug_service.dart'; -import 'package:dwds/src/services/proxy_service.dart'; -import 'package:dwds/src/services/web_socket/web_socket_debug_service.dart'; -import 'package:dwds/src/services/web_socket/web_socket_proxy_service.dart'; -import 'package:dwds/src/utilities/synchronized.dart'; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; import 'package:uuid/uuid.dart'; @@ -24,6 +13,18 @@ import 'package:vm_service/vm_service_io.dart'; import 'package:vm_service_interface/vm_service_interface.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import 'config/tool_configuration.dart'; +import 'events.dart'; +import 'loaders/ddc_library_bundle.dart'; +import 'services/chrome/chrome_debug_exception.dart'; +import 'services/chrome/chrome_debug_service.dart'; +import 'services/chrome/chrome_proxy_service.dart'; +import 'services/debug_service.dart'; +import 'services/proxy_service.dart'; +import 'services/web_socket/web_socket_debug_service.dart'; +import 'services/web_socket/web_socket_proxy_service.dart'; +import 'utilities/synchronized.dart'; + /// Type of requests added to the request controller. typedef VmRequest = Map; @@ -107,11 +108,14 @@ abstract base class DwdsVmClient< final client = VmService(_responseStream.map(jsonEncode), (request) { if (_requestController.isClosed) { logger.warning( - 'Attempted to send a request but the connection is closed:\n\n$request', + 'Attempted to send a request but the connection is closed:\n\n' + '$request', ); return; } - _requestSink.add(Map.from(jsonDecode(request))); + _requestSink.add( + Map.from(jsonDecode(request) as Map), + ); }); return client; } @@ -214,11 +218,11 @@ abstract base class DwdsVmClient< return {'result': Success().toJson()}; } - void _processSendEvent(Map request, DwdsStats dwdsStats) { - final event = request['params'] as Map?; + void _processSendEvent(Map request, DwdsStats dwdsStats) { + final event = request['params'] as Map?; if (event == null) return; final type = event['type'] as String?; - final payload = event['payload'] as Map?; + final payload = event['payload'] as Map?; switch (type) { case 'DevtoolsEvent': { @@ -262,10 +266,10 @@ abstract base class DwdsVmClient< VmResponse request, Logger logger, ) { - final event = request['params'] as Map?; + final event = request['params'] as Map?; if (event != null) { final type = event['type'] as String?; - final payload = event['payload'] as Map?; + final payload = event['payload'] as Map?; if (type != null && payload != null) { logger.fine('EmitEvent: $type $payload'); emitEvent(DwdsEvent(type, payload)); @@ -283,8 +287,8 @@ abstract base class DwdsVmClient< return { 'result': { 'views': [ - for (final isolate in isolates ?? []) - {'id': isolate.id, 'isolate': isolate.toJson()}, + for (final isolate in isolates ?? []) + {'id': isolate.id!, 'isolate': isolate.toJson()}, ], }, }; @@ -397,7 +401,7 @@ final class ChromeDwdsVmClient return {'result': Success().toJson()}; } - Future> hotRestart( + Future> hotRestart( ChromeProxyService chromeProxyService, VmService client, ) { @@ -412,12 +416,12 @@ final class ChromeDwdsVmClient for (var retry = 0; retry < retries; retry++) { final tryId = await chromeProxyService.executionContext.id; if (tryId != null) return tryId; - await Future.delayed(const Duration(milliseconds: waitInMs)); + await Future.delayed(const Duration(milliseconds: waitInMs)); } throw StateError('No context with the running Dart application.'); } - Future> _hotRestart( + Future> _hotRestart( ChromeProxyService chromeProxyService, VmService client, ) async { @@ -429,6 +433,7 @@ final class ChromeDwdsVmClient logger.info('Attempting to get execution context ID.'); await tryGetContextId(chromeProxyService); logger.info('Got execution context ID.'); + // ignore: avoid_catching_errors } on StateError catch (e) { // We couldn't find the execution context. `hotRestart` may have been // triggered in the middle of a full reload. @@ -456,9 +461,9 @@ final class ChromeDwdsVmClient final runId = const Uuid().v4().toString(); // When using the DDC library bundle format, we determine the sources that - // were reloaded during a hot restart to then wait until all the sources are - // parsed before finishing hot restart. This is necessary before we can - // recompute any source location metadata in the `ChromeProxyService`. + // were reloaded during a hot restart to then wait until all the sources + // are parsed before finishing hot restart. This is necessary before we + // can recompute any source location metadata in the `ChromeProxyService`. // TODO(srujzs): We don't do this for the AMD module format, should we? It // would require adding an extra parameter in the AMD strategy. As we're // planning to deprecate it, for now, do nothing. @@ -468,9 +473,9 @@ final class ChromeDwdsVmClient final reloadedSrcs = {}; late StreamSubscription parsedScriptsSubscription; if (isDdcLibraryBundle) { - // Injected client should send a request to recreate the isolate after the - // hot restart. The creation of the isolate should in turn wait until all - // scripts are parsed. + // Injected client should send a request to recreate the isolate after + // the hot restart. The creation of the isolate should in turn wait + // until all scripts are parsed. chromeProxyService.allowedToCreateIsolate = Completer(); final debugger = await chromeProxyService.debuggerFuture; parsedScriptsSubscription = debugger.parsedScriptsController.stream @@ -549,7 +554,7 @@ final class ChromeDwdsVmClient }); } - Future> _fullReload( + Future> _fullReload( ChromeProxyService chromeProxyService, ) async { logger.info('Attempting a full reload'); diff --git a/dwds/lib/src/events.dart b/dwds/lib/src/events.dart index c7c9d166b..f2577de2f 100644 --- a/dwds/lib/src/events.dart +++ b/dwds/lib/src/events.dart @@ -58,7 +58,7 @@ class DwdsEventKind { class DwdsEvent { final String type; - final Map payload; + final Map payload; DwdsEvent(this.type, this.payload); @@ -128,7 +128,7 @@ class DwdsEvent { 'exception': exception, }); - void addException(dynamic exception) { + void addException(Object? exception) { payload['exception'] = exception; } diff --git a/dwds/lib/src/handlers/dev_handler.dart b/dwds/lib/src/handlers/dev_handler.dart index 94d9e3201..612ff4dca 100644 --- a/dwds/lib/src/handlers/dev_handler.dart +++ b/dwds/lib/src/handlers/dev_handler.dart @@ -8,43 +8,44 @@ import 'dart:io'; import 'package:collection/collection.dart'; import 'package:dds/dds_launcher.dart'; -import 'package:dwds/data/build_result.dart'; -import 'package:dwds/data/connect_request.dart'; -import 'package:dwds/data/debug_event.dart'; -import 'package:dwds/data/devtools_request.dart'; -import 'package:dwds/data/error_response.dart'; -import 'package:dwds/data/hot_reload_response.dart'; -import 'package:dwds/data/hot_restart_response.dart'; -import 'package:dwds/data/isolate_events.dart'; -import 'package:dwds/data/register_event.dart'; -import 'package:dwds/data/serializers.dart'; -import 'package:dwds/data/service_extension_response.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/connections/debug_connection.dart'; -import 'package:dwds/src/debugging/execution_context.dart'; -import 'package:dwds/src/debugging/remote_debugger.dart'; -import 'package:dwds/src/debugging/webkit_debugger.dart'; -import 'package:dwds/src/dwds_vm_client.dart'; -import 'package:dwds/src/events.dart'; -import 'package:dwds/src/handlers/injector.dart'; -import 'package:dwds/src/handlers/socket_connections.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/servers/devtools.dart'; -import 'package:dwds/src/servers/extension_backend.dart'; -import 'package:dwds/src/servers/extension_debugger.dart'; -import 'package:dwds/src/services/app_debug_services.dart'; -import 'package:dwds/src/services/chrome/chrome_debug_service.dart'; -import 'package:dwds/src/services/chrome/chrome_proxy_service.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; -import 'package:dwds/src/services/web_socket/web_socket_debug_service.dart'; -import 'package:dwds/src/services/web_socket/web_socket_proxy_service.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:logging/logging.dart'; import 'package:shelf/shelf.dart'; import 'package:sse/server/sse_handler.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../../data/build_result.dart'; +import '../../data/connect_request.dart'; +import '../../data/debug_event.dart'; +import '../../data/devtools_request.dart'; +import '../../data/error_response.dart'; +import '../../data/hot_reload_response.dart'; +import '../../data/hot_restart_response.dart'; +import '../../data/isolate_events.dart'; +import '../../data/register_event.dart'; +import '../../data/serializers.dart'; +import '../../data/service_extension_response.dart'; +import '../config/tool_configuration.dart'; +import '../connections/app_connection.dart'; +import '../connections/debug_connection.dart'; +import '../debugging/execution_context.dart'; +import '../debugging/remote_debugger.dart'; +import '../debugging/webkit_debugger.dart'; +import '../dwds_vm_client.dart'; +import '../events.dart'; +import '../readers/asset_reader.dart'; +import '../servers/devtools.dart'; +import '../servers/extension_backend.dart'; +import '../servers/extension_debugger.dart'; +import '../services/app_debug_services.dart'; +import '../services/chrome/chrome_debug_service.dart'; +import '../services/chrome/chrome_proxy_service.dart'; +import '../services/expression_compiler.dart'; +import '../services/web_socket/web_socket_debug_service.dart'; +import '../services/web_socket/web_socket_proxy_service.dart'; +import '../utilities/shared.dart'; +import 'injector.dart'; +import 'socket_connections.dart'; + /// When enabled, this logs VM service protocol and Chrome debug protocol /// traffic to disk. /// @@ -147,10 +148,13 @@ class DevHandler { try { injectedConnection.sink.add(jsonEncode(serializers.serialize(request))); successfulSends++; + // ignore: avoid_catching_errors } on StateError catch (e) { - // The sink has already closed (app is disconnected), or another StateError occurred. + // The sink has already closed (app is disconnected), or another + // StateError occurred. _logger.warning( - 'Failed to send request to client, connection likely closed. Error: $e', + 'Failed to send request to client, connection likely closed. ' + 'Error: $e', ); } catch (e, s) { // Catch any other potential errors during sending. @@ -158,7 +162,8 @@ class DevHandler { } } _logger.fine( - 'Sent request to $successfulSends clients out of ${_injectedConnections.length} total connections', + 'Sent request to $successfulSends clients out of ' + '${_injectedConnections.length} total connections', ); return successfulSends; } @@ -202,7 +207,8 @@ class DevHandler { 'expression': r'window["$dartAppInstanceId"];', 'contextId': contextId, }); - final evaluatedAppId = result.result?['result']?['value']; + final evaluatedAppId = + (result.result?['result'] as Map?)?['value']; if (evaluatedAppId == appInstanceId) { appTab = tab; executionContext = RemoteDebuggerExecutionContext( @@ -375,6 +381,7 @@ class DevHandler { ), ), ); + // ignore: avoid_catching_errors } on StateError catch (_) { // The sink has already closed (app is disconnected), swallow the // error. @@ -389,7 +396,8 @@ class DevHandler { if (connection != null) { final appId = connection.request.appId; final services = _servicesByAppId[appId]; - // WebSocket mode doesn't need this because WebSocketProxyService handles connection tracking and cleanup + // WebSocket mode doesn't need this because WebSocketProxyService + // handles connection tracking and cleanup if (!useWebSocketConnection) { _appConnectionByAppId.remove(appId); } @@ -441,7 +449,8 @@ class DevHandler { ? 'WebSocket' : 'Chrome'; throw UnsupportedError( - 'Message type ${message.runtimeType} is not supported in $serviceType mode', + 'Message type ${message.runtimeType} is not supported in $serviceType ' + 'mode', ); } } @@ -561,7 +570,7 @@ class DevHandler { final proxyService = appDebugServices.proxyService; if (proxyService is! WebSocketProxyService) { throw StateError( - 'Expected WebSocketProxyService but got ${proxyService.runtimeType}. ', + 'Expected WebSocketProxyService but got ${proxyService.runtimeType}.', ); } await proxyService.isInitialized; @@ -710,7 +719,8 @@ class DevHandler { // New browser window or initial connection: run main() immediately readyToRunMainCompleter.complete(); - // For WebSocket mode, we need to proactively create and emit a debug connection + // For WebSocket mode, we need to proactively create and emit a debug + // connection try { // Initialize the WebSocket service and create debug connection final debugConnection = await createDebugConnectionForWebSocket( @@ -802,7 +812,8 @@ class DevHandler { } } - /// Handles isolate start events for both WebSocket and Chrome-based debugging. + /// Handles isolate start events for both WebSocket and Chrome-based + /// debugging. Future _handleIsolateStart(AppConnection appConnection) async { final appId = appConnection.request.appId; @@ -826,10 +837,11 @@ class DevHandler { if (!_sseHandlers.containsKey(uri.path)) { final handler = _useSseForInjectedClient ? SseSocketHandler( - // We provide an essentially indefinite keep alive duration because - // the underlying connection could be lost while the application - // is paused. The connection will get re-established after a resume - // or cleaned up on a full page refresh. + // We provide an essentially indefinite keep alive duration + // because the underlying connection could be lost while the + // application is paused. The connection will get + // re-established after a resume or cleaned up on a full page + // refresh. SseHandler(uri, keepAlive: const Duration(days: 3000)), ) : WebSocketSocketHandler(); diff --git a/dwds/lib/src/handlers/injector.dart b/dwds/lib/src/handlers/injector.dart index 83728a365..10db6cdc0 100644 --- a/dwds/lib/src/handlers/injector.dart +++ b/dwds/lib/src/handlers/injector.dart @@ -8,12 +8,13 @@ import 'dart:io'; import 'dart:isolate'; import 'package:crypto/crypto.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/loaders/ddc_library_bundle.dart'; -import 'package:dwds/src/version.dart'; import 'package:logging/logging.dart'; import 'package:shelf/shelf.dart'; +import '../config/tool_configuration.dart'; +import '../loaders/ddc_library_bundle.dart'; +import '../version.dart'; + /// File extension that build_web_compilers will place the /// [entrypointExtensionMarker] in. const bootstrapJsExtension = '.bootstrap.js'; @@ -195,19 +196,21 @@ Future _injectedClientSnippet( final debugSettings = globalToolConfiguration.debugSettings; var injectedBody = - 'window.\$dartAppId = "$appId";\n' - 'window.\$dartReloadConfiguration = "${loadStrategy.reloadConfiguration}";\n' - 'window.\$dartModuleStrategy = "${loadStrategy.id}";\n' - 'window.\$loadModuleConfig = ${loadStrategy.loadModuleSnippet};\n' - 'window.\$dwdsVersion = "$packageVersion";\n' - 'window.\$dwdsDevHandlerPath = "$devHandlerPath";\n' - 'window.\$dwdsEnableDevToolsLaunch = ${debugSettings.enableDevToolsLaunch};\n' - 'window.\$dartEntrypointPath = "$entrypointPath";\n' - 'window.\$dartEmitDebugEvents = ${debugSettings.emitDebugEvents};\n' - 'window.\$isInternalBuild = ${appMetadata.isInternalBuild};\n' - 'window.\$isFlutterApp = ${buildSettings.isFlutterApp};\n' - '${loadStrategy is DdcLibraryBundleStrategy ? 'window.\$reloadedSourcesPath = "${loadStrategy.reloadedSourcesUri.toString()}";\n' : ''}' - '${loadStrategy.loadClientSnippet(_clientScript)}'; + ''' + window.\$dartAppId = "$appId"; + window.\$dartReloadConfiguration = "${loadStrategy.reloadConfiguration}"; + window.\$dartModuleStrategy = "${loadStrategy.id}"; + window.\$loadModuleConfig = ${loadStrategy.loadModuleSnippet}; + window.\$dwdsVersion = "$packageVersion"; + window.\$dwdsDevHandlerPath = "$devHandlerPath"; + window.\$dwdsEnableDevToolsLaunch = ${debugSettings.enableDevToolsLaunch}; + window.\$dartEntrypointPath = "$entrypointPath"; + window.\$dartEmitDebugEvents = ${debugSettings.emitDebugEvents}; + window.\$isInternalBuild = ${appMetadata.isInternalBuild}; + window.\$isFlutterApp = ${buildSettings.isFlutterApp}; + ${loadStrategy is DdcLibraryBundleStrategy ? 'window.\$reloadedSourcesPath = "${loadStrategy.reloadedSourcesUri.toString()}";' : ''} + ${loadStrategy.loadClientSnippet(_clientScript)} +'''; if (extensionUri != null) { injectedBody += 'window.\$dartExtensionUri = "$extensionUri";\n'; diff --git a/dwds/lib/src/handlers/socket_connections.dart b/dwds/lib/src/handlers/socket_connections.dart index bf99f7c62..23f5689c8 100644 --- a/dwds/lib/src/handlers/socket_connections.dart +++ b/dwds/lib/src/handlers/socket_connections.dart @@ -16,7 +16,7 @@ abstract class SocketConnection { bool get isInKeepAlivePeriod; /// Messages added to the sink must be JSON encodable. - StreamSink get sink; + StreamSink get sink; Stream get stream; @@ -24,7 +24,8 @@ abstract class SocketConnection { void shutdown(); } -/// A handler that accepts (transport-agnostic) bidirectional socket connections. +/// A handler that accepts (transport-agnostic) bidirectional socket +/// connections. abstract class SocketHandler { StreamQueue get connections; FutureOr handler(Request request); @@ -32,7 +33,8 @@ abstract class SocketHandler { } /// An implementation of [SocketConnection] that users server-sent events (SSE) -/// and HTTP POSTS for bidirectional communication by wrapping an [SseConnection]. +/// and HTTP POSTS for bidirectional communication by wrapping an +/// [SseConnection]. class SseSocketConnection extends SocketConnection { final SseConnection _connection; @@ -41,7 +43,7 @@ class SseSocketConnection extends SocketConnection { @override bool get isInKeepAlivePeriod => _connection.isInKeepAlivePeriod; @override - StreamSink get sink => _connection.sink; + StreamSink get sink => _connection.sink; @override Stream get stream => _connection.stream; @override @@ -76,8 +78,8 @@ class SseSocketHandler extends SocketHandler { void shutdown() => _sseHandler.shutdown(); } -/// An implementation of [SocketConnection] that uses WebSockets for communication -/// by wrapping [WebSocketChannel]. +/// An implementation of [SocketConnection] that uses WebSockets for +/// communication by wrapping [WebSocketChannel]. class WebSocketConnection extends SocketConnection { final WebSocketChannel _channel; WebSocketConnection(this._channel); @@ -86,10 +88,10 @@ class WebSocketConnection extends SocketConnection { bool get isInKeepAlivePeriod => false; @override - StreamSink get sink => _channel.sink; + StreamSink get sink => _channel.sink; @override - Stream get stream => _channel.stream.map((dynamic o) => o.toString()); + Stream get stream => _channel.stream.map((Object? o) => o.toString()); @override void shutdown() => _channel.sink.close(); diff --git a/dwds/lib/src/injected/client.js b/dwds/lib/src/injected/client.js index 04799eef8..e11c9d03b 100644 --- a/dwds/lib/src/injected/client.js +++ b/dwds/lib/src/injected/client.js @@ -300,7 +300,7 @@ return t1; }, JSArray__compareAny(a, b) { - var t1 = type$.Comparable_dynamic; + var t1 = type$.Comparable_Object?; return J.compareTo$1$ns(t1._as(a), t1._as(b)); }, getInterceptor$(receiver) { @@ -547,7 +547,7 @@ A = {JS_CONST: function JS_CONST() { }, CastIterable_CastIterable(source, $S, $T) { - if (type$.EfficientLengthIterable_dynamic._is(source)) + if (type$.EfficientLengthIterable_Object?._is(source)) return new A._EfficientLengthCastIterable(source, $S._eval$1("@<0>")._bind$1($T)._eval$1("_EfficientLengthCastIterable<1,2>")); return new A.CastIterable(source, $S._eval$1("@<0>")._bind$1($T)._eval$1("CastIterable<1,2>")); }, @@ -600,7 +600,7 @@ return new A.SubListIterable(_iterable, _start, _endOrLength, $E._eval$1("SubListIterable<0>")); }, MappedIterable_MappedIterable(iterable, $function, $S, $T) { - if (type$.EfficientLengthIterable_dynamic._is(iterable)) + if (type$.EfficientLengthIterable_Object?._is(iterable)) return new A.EfficientLengthMappedIterable(iterable, $function, $S._eval$1("@<0>")._bind$1($T)._eval$1("EfficientLengthMappedIterable<1,2>")); return new A.MappedIterable(iterable, $function, $S._eval$1("@<0>")._bind$1($T)._eval$1("MappedIterable<1,2>")); }, @@ -608,13 +608,13 @@ var _s9_ = "takeCount"; A.ArgumentError_checkNotNull(takeCount, _s9_, type$.int); A.RangeError_checkNotNegative(takeCount, _s9_); - if (type$.EfficientLengthIterable_dynamic._is(iterable)) + if (type$.EfficientLengthIterable_Object?._is(iterable)) return new A.EfficientLengthTakeIterable(iterable, takeCount, $E._eval$1("EfficientLengthTakeIterable<0>")); return new A.TakeIterable(iterable, takeCount, $E._eval$1("TakeIterable<0>")); }, SkipIterable_SkipIterable(iterable, count, $E) { var _s5_ = "count"; - if (type$.EfficientLengthIterable_dynamic._is(iterable)) { + if (type$.EfficientLengthIterable_Object?._is(iterable)) { A.ArgumentError_checkNotNull(count, _s5_, type$.int); A.RangeError_checkNotNegative(count, _s5_); return new A.EfficientLengthSkipIterable(iterable, count, $E._eval$1("EfficientLengthSkipIterable<0>")); @@ -1048,7 +1048,7 @@ if (result != null) return result; } - return type$.JavaScriptIndexingBehavior_dynamic._is(object); + return type$.JavaScriptIndexingBehavior_Object?._is(object); }, S(value) { var result; @@ -1327,7 +1327,7 @@ operation = table[index]; } verb = typeof encodedVerb == "string" ? encodedVerb : "modify;remove from;add to".split(";")[encodedVerb]; - object = type$.List_dynamic._is(o) ? "list" : "ByteData"; + object = type$.List_Object?._is(o) ? "list" : "ByteData"; flags = o.$flags | 0; article = "a "; if ((flags & 4) !== 0) @@ -2241,10 +2241,10 @@ }, _ensureNativeList(list) { var t1, result, i; - if (type$.JSIndexable_dynamic._is(list)) + if (type$.JSIndexable_Object?._is(list)) return list; t1 = J.getInterceptor$asx(list); - result = A.List_List$filled(t1.get$length(list), null, false, type$.dynamic); + result = A.List_List$filled(t1.get$length(list), null, false, type$.Object?); for (i = 0; i < t1.get$length(list); ++i) B.JSArray_methods.$indexSet(result, i, t1.$index(list, i)); return result; @@ -2500,7 +2500,7 @@ }, _arrayInstanceType(object) { var rti = object[init.arrayRti], - defaultRti = type$.JSArray_dynamic; + defaultRti = type$.JSArray_Object?; if (rti == null) return defaultRti; if (rti.constructor !== defaultRti.constructor) @@ -2952,7 +2952,7 @@ if (kind === 5) return "erased"; if (kind === 2) - return "dynamic"; + return "Object?"; if (kind === 3) return "void"; if (kind === 1) @@ -3874,13 +3874,13 @@ thenCallback = new A._awaitOnObject_closure(bodyFunction), errorCallback = new A._awaitOnObject_closure0(bodyFunction); if (object instanceof A._Future) - object._thenAwait$1$2(thenCallback, errorCallback, type$.dynamic); + object._thenAwait$1$2(thenCallback, errorCallback, type$.Object?); else { - t1 = type$.dynamic; + t1 = type$.Object?; if (object instanceof A._Future) object.then$1$2$onError(thenCallback, errorCallback, t1); else { - future = new A._Future($.Zone__current, type$._Future_dynamic); + future = new A._Future($.Zone__current, type$._Future_Object?); future._state = 8; future._resultOrListeners = object; future._thenAwait$1$2(thenCallback, errorCallback, t1); @@ -3901,7 +3901,7 @@ } }; }($function, 1); - return $.Zone__current.registerBinaryCallback$3$1(new A._wrapJsFunctionForAsync_closure($protected), type$.void, type$.int, type$.dynamic); + return $.Zone__current.registerBinaryCallback$3$1(new A._wrapJsFunctionForAsync_closure($protected), type$.void, type$.int, type$.Object?); }, _asyncStarHelper(object, bodyFunctionOrErrorCode, controller) { var t1, t2, t3, @@ -3932,7 +3932,7 @@ } return; } - type$.void_Function_int_dynamic._as(bodyFunctionOrErrorCode); + type$.void_Function_int_Object?._as(bodyFunctionOrErrorCode); if (object instanceof A._IterationMarker) { if (controller.cancelationFuture != null) { bodyFunctionOrErrorCode.call$2(2, null); @@ -3947,7 +3947,7 @@ A.scheduleMicrotask(new A._asyncStarHelper_closure(controller, bodyFunctionOrErrorCode)); return; } else if (t1 === 1) { - t1 = controller.$ti._eval$1("Stream<1>")._as(type$.Stream_dynamic._as(object.value)); + t1 = controller.$ti._eval$1("Stream<1>")._as(type$.Stream_Object?._as(object.value)); t2 = controller.___AsyncStarStreamController_controller_A; t2 === $ && A.throwLateFieldNI(_s10_); t2.addStream$2$cancelOnError(t1, false).then$1$1(new A._asyncStarHelper_closure0(controller, bodyFunctionOrErrorCode), type$.Null); @@ -4062,7 +4062,7 @@ _Future__chainCoreFuture(source, target, sync) { var t2, t3, ignoreError, listeners, _box_0 = {}, t1 = _box_0.source = source; - for (t2 = type$._Future_dynamic; t3 = t1._state, (t3 & 4) !== 0; t1 = source) { + for (t2 = type$._Future_Object?; t3 = t1._state, (t3 & 4) !== 0; t1 = source) { source = t2._as(t1._resultOrListeners); _box_0.source = source; } @@ -4074,7 +4074,7 @@ ignoreError = target._state & 1; t2 = t1._state = t3 | ignoreError; if ((t2 & 24) === 0) { - listeners = type$.nullable__FutureListener_dynamic_dynamic._as(target._resultOrListeners); + listeners = type$.nullable__FutureListener_Object?_Object?._as(target._resultOrListeners); target._state = target._state & 1 | 4; target._resultOrListeners = t1; t1._prependListeners$1(listeners); @@ -4099,7 +4099,7 @@ _Future__propagateToListeners(source, listeners) { var t2, t3, _box_0, t4, t5, hasError, asyncError, nextListener, nextListener0, sourceResult, t6, zone, oldZone, result, current, _box_1 = {}, t1 = _box_1.source = source; - for (t2 = type$.AsyncError, t3 = type$.nullable__FutureListener_dynamic_dynamic;;) { + for (t2 = type$.AsyncError, t3 = type$.nullable__FutureListener_Object?_Object?;;) { _box_0 = {}; t4 = t1._state; t5 = (t4 & 16) === 0; @@ -4197,10 +4197,10 @@ } }, _registerErrorHandler(errorHandler, zone) { - if (type$.dynamic_Function_Object_StackTrace._is(errorHandler)) - return zone.registerBinaryCallback$3$1(errorHandler, type$.dynamic, type$.Object, type$.StackTrace); - if (type$.dynamic_Function_Object._is(errorHandler)) - return zone.registerUnaryCallback$2$1(errorHandler, type$.dynamic, type$.Object); + if (type$.Object?_Function_Object_StackTrace._is(errorHandler)) + return zone.registerBinaryCallback$3$1(errorHandler, type$.Object?, type$.Object, type$.StackTrace); + if (type$.Object?_Function_Object._is(errorHandler)) + return zone.registerUnaryCallback$2$1(errorHandler, type$.Object?, type$.Object); throw A.wrapException(A.ArgumentError$value(errorHandler, "onError", string$.Error_)); }, _microtaskLoop() { @@ -4304,9 +4304,9 @@ if (handleError == null) handleError = A.async___nullErrorHandler$closure(); if (type$.void_Function_Object_StackTrace._is(handleError)) - return zone.registerBinaryCallback$3$1(handleError, type$.dynamic, type$.Object, type$.StackTrace); + return zone.registerBinaryCallback$3$1(handleError, type$.Object?, type$.Object, type$.StackTrace); if (type$.void_Function_Object._is(handleError)) - return zone.registerUnaryCallback$2$1(handleError, type$.dynamic, type$.Object); + return zone.registerUnaryCallback$2$1(handleError, type$.Object?, type$.Object); throw A.wrapException(A.ArgumentError$("handleError callback must take either an Object (the error), or both an Object (the error) and a StackTrace.", null)); }, _nullDataHandler(value) { @@ -5027,7 +5027,7 @@ return result; }, ListBase__compareAny(a, b) { - var t1 = type$.Comparable_dynamic; + var t1 = type$.Comparable_Object?; return J.compareTo$1$ns(t1._as(a), t1._as(b)); }, MapBase_mapToString(m) { @@ -6352,7 +6352,7 @@ return A.ioore($.toStringVisiting, -1); $.toStringVisiting.pop(); } - t1 = A.StringBuffer__writeAll(leftDelimiter, type$.Iterable_dynamic._as(parts), ", ") + rightDelimiter; + t1 = A.StringBuffer__writeAll(leftDelimiter, type$.Iterable_Object?._as(parts), ", ") + rightDelimiter; return t1.charCodeAt(0) == 0 ? t1 : t1; }, Iterable_iterableToFullString(iterable, leftDelimiter, rightDelimiter) { @@ -8182,11 +8182,11 @@ return new A.StringJsonObject(value); else if (A._isBool(value)) return new A.BoolJsonObject(value); - else if (type$.List_dynamic._is(value)) + else if (type$.List_Object?._is(value)) return new A.ListJsonObject(new A.UnmodifiableListView(value, type$.UnmodifiableListView_nullable_Object)); else if (type$.Map_of_String_and_nullable_Object._is(value)) return new A.MapJsonObject(new A.UnmodifiableMapView(value, type$.UnmodifiableMapView_of_String_and_nullable_Object)); - else if (type$.Map_dynamic_dynamic._is(value)) + else if (type$.Map_Object?_Object?._is(value)) return new A.MapJsonObject(new A.UnmodifiableMapView(value.cast$2$0(0, type$.String, type$.nullable_Object), type$.UnmodifiableMapView_of_String_and_nullable_Object)); else throw A.wrapException(A.ArgumentError$value(value, "value", "Must be bool, List, Map, num or String")); @@ -8210,7 +8210,7 @@ }, Serializers_Serializers() { var t1 = type$.Type, - t2 = type$.Serializer_dynamic, + t2 = type$.Serializer_Object?, t3 = type$.String; t2 = new A.BuiltJsonSerializersBuilder(A.MapBuilder_MapBuilder(t1, t2), A.MapBuilder_MapBuilder(t3, t2), A.MapBuilder_MapBuilder(t3, t2), A.MapBuilder_MapBuilder(type$.FullType, type$.Function), A.ListBuilder_ListBuilder(B.List_empty0, type$.SerializerPlugin)); t2.add$1(0, new A.BigIntSerializer(A.BuiltList_BuiltList$from([B.Type_BigInt_DZK, A.getRuntimeTypeOfDartObject($.$get$_BigIntImpl_zero())], t1))); @@ -10051,7 +10051,7 @@ var t1 = $.$get$serializers(), t2 = new A.ConnectRequestBuilder(); type$.nullable_void_Function_ConnectRequestBuilder._as(new A._sendConnectRequest_closure()).call$1(t2); - A._trySendEvent(clientSink, B.C_JsonCodec.encode$2$toEncodable(t1.serialize$1(t2._connect_request$_build$0()), null), type$.dynamic); + A._trySendEvent(clientSink, B.C_JsonCodec.encode$2$toEncodable(t1.serialize$1(t2._connect_request$_build$0()), null), type$.Object?); }, _launchCommunicationWithDebugExtension() { var t1, t2; @@ -10109,10 +10109,10 @@ return A._asyncStartSync($async$_authenticateUser, $async$completer); }, _sendResponse(clientSink, builder, requestId, errorMessage, success, $T) { - A._trySendEvent(clientSink, B.C_JsonCodec.encode$2$toEncodable($.$get$serializers().serialize$1(builder.call$1(new A._sendResponse_closure(requestId, success, errorMessage))), null), type$.dynamic); + A._trySendEvent(clientSink, B.C_JsonCodec.encode$2$toEncodable($.$get$serializers().serialize$1(builder.call$1(new A._sendResponse_closure(requestId, success, errorMessage))), null), type$.Object?); }, _sendServiceExtensionResponse(clientSink, requestId, errorCode, errorMessage, result, success) { - A._trySendEvent(clientSink, B.C_JsonCodec.encode$2$toEncodable($.$get$serializers().serialize$1(A.ServiceExtensionResponse_ServiceExtensionResponse$fromResult(errorCode, errorMessage, requestId, result, success)), null), type$.dynamic); + A._trySendEvent(clientSink, B.C_JsonCodec.encode$2$toEncodable($.$get$serializers().serialize$1(A.ServiceExtensionResponse_ServiceExtensionResponse$fromResult(errorCode, errorMessage, requestId, result, success)), null), type$.Object?); }, handleWebSocketHotReloadRequest($event, manager, clientSink) { return A.handleWebSocketHotReloadRequest$body($event, manager, clientSink); @@ -10270,7 +10270,7 @@ // Function start $async$handler = 3; t1 = request.argsJson; - t1 = t1.length === 0 ? A.LinkedHashMap_LinkedHashMap$_empty(type$.String, type$.dynamic) : type$.Map_String_dynamic._as(B.C_JsonCodec.decode$1(t1)); + t1 = t1.length === 0 ? A.LinkedHashMap_LinkedHashMap$_empty(type$.String, type$.Object?) : type$.Map_String_Object?._as(B.C_JsonCodec.decode$1(t1)); $async$goto = 6; return A._asyncAwait(manager.handleServiceExtension$2(request.method, t1), $async$handleServiceExtensionRequest); case 6: @@ -10990,7 +10990,7 @@ A._arrayInstanceType(receiver)._eval$1("Iterable<1>")._as(iterable); receiver.$flags & 1 && A.throwUnsupportedOperation(receiver, "insertAll", 2); A.RangeError_checkValueInInterval(index, 0, receiver.length, "index"); - if (!type$.EfficientLengthIterable_dynamic._is(iterable)) + if (!type$.EfficientLengthIterable_Object?._is(iterable)) iterable = J.toList$0$ax(iterable); insertionLength = J.get$length$asx(iterable); receiver.length = receiver.length + insertionLength; @@ -11046,7 +11046,7 @@ }, _addAllFromArray$1(receiver, array) { var len, i; - type$.JSArray_dynamic._as(array); + type$.JSArray_Object?._as(array); len = array.length; if (len === 0) return; @@ -11064,7 +11064,7 @@ return new A.MappedListIterable(receiver, t1._bind$1($T)._eval$1("1(2)")._as(f), t1._eval$1("@<1>")._bind$1($T)._eval$1("MappedListIterable<1,2>")); }, map$1(receiver, f) { - return this.map$1$1(receiver, f, type$.dynamic); + return this.map$1$1(receiver, f, type$.Object?); }, join$1(receiver, separator) { var i, @@ -11131,7 +11131,7 @@ if ($length === 0) return; A.RangeError_checkNotNegative(skipCount, "skipCount"); - if (type$.List_dynamic._is(iterable)) { + if (type$.List_Object?._is(iterable)) { otherList = iterable; otherStart = skipCount; } else { @@ -11929,7 +11929,7 @@ return new A.MappedListIterable(this, t1._bind$1($T)._eval$1("1(ListIterable.E)")._as(toElement), t1._eval$1("@")._bind$1($T)._eval$1("MappedListIterable<1,2>")); }, map$1(_, toElement) { - return this.map$1$1(0, toElement, type$.dynamic); + return this.map$1$1(0, toElement, type$.Object?); }, reduce$1(_, combine) { var $length, value, i, _this = this; @@ -12124,7 +12124,7 @@ return new A.MappedIterable(this, t1._bind$1($T)._eval$1("1(2)")._as(toElement), t1._eval$1("@<1>")._bind$1($T)._eval$1("MappedIterable<1,2>")); }, map$1(_, toElement) { - return this.map$1$1(0, toElement, type$.dynamic); + return this.map$1$1(0, toElement, type$.Object?); } }; A.WhereIterator.prototype = { @@ -12261,7 +12261,7 @@ return new A.EmptyIterable($T._eval$1("EmptyIterable<0>")); }, map$1(_, toElement) { - return this.map$1$1(0, toElement, type$.dynamic); + return this.map$1$1(0, toElement, type$.Object?); }, skip$1(_, count) { A.RangeError_checkNotNegative(count, "count"); @@ -12374,7 +12374,7 @@ return result; }, map$1(_, transform) { - var t1 = type$.dynamic; + var t1 = type$.Object?; return this.map$2$1(0, transform, t1, t1); }, $isMap: 1 @@ -13257,7 +13257,7 @@ return t1; }, readLocal$0() { - return this.readLocal$1$0(type$.dynamic); + return this.readLocal$1$0(type$.Object?); }, _readLocal$0() { var t1 = this.__late_helper$_value; @@ -13749,7 +13749,7 @@ t2 = t1.___AsyncStarStreamController_controller_A; t2 === $ && A.throwLateFieldNI("controller"); if ((t2._state & 4) === 0) { - t1.cancelationFuture = new A._Future($.Zone__current, type$._Future_dynamic); + t1.cancelationFuture = new A._Future($.Zone__current, type$._Future_Object?); if (t1.isSuspended) { t1.isSuspended = false; A.scheduleMicrotask(new A._AsyncStarStreamController__closure(this.body)); @@ -13856,14 +13856,14 @@ var exception, _this = this, errorCallback = _this.errorCallback, result = null, - t1 = type$.dynamic, + t1 = type$.Object?, t2 = type$.Object, t3 = asyncError.error, t4 = _this.result._zone; - if (type$.dynamic_Function_Object_StackTrace._is(errorCallback)) + if (type$.Object?_Function_Object_StackTrace._is(errorCallback)) result = t4.runBinary$3$3(errorCallback, t3, asyncError.stackTrace, t1, t2, type$.StackTrace); else - result = t4.runUnary$2$2(type$.dynamic_Function_Object._as(errorCallback), t3, t1, t2); + result = t4.runUnary$2$2(type$.Object?_Function_Object._as(errorCallback), t3, t1, t2); try { t1 = _this.$ti._eval$1("2/")._as(result); return t1; @@ -13884,7 +13884,7 @@ t1._bind$1($R)._eval$1("1/(2)")._as(f); currentZone = $.Zone__current; if (currentZone === B.C__RootZone) { - if (onError != null && !type$.dynamic_Function_Object_StackTrace._is(onError) && !type$.dynamic_Function_Object._is(onError)) + if (onError != null && !type$.Object?_Function_Object_StackTrace._is(onError) && !type$.Object?_Function_Object._is(onError)) throw A.wrapException(A.ArgumentError$value(onError, "onError", string$.Error_)); } else { f = currentZone.registerUnaryCallback$2$1(f, $R._eval$1("0/"), t1._precomputed1); @@ -13927,12 +13927,12 @@ }, whenComplete$1(action) { var t1, t2, result; - type$.dynamic_Function._as(action); + type$.Object?_Function._as(action); t1 = this.$ti; t2 = $.Zone__current; result = new A._Future(t2, t1); if (t2 !== B.C__RootZone) - action = t2.registerCallback$1$1(action, type$.dynamic); + action = t2.registerCallback$1$1(action, type$.Object?); this._addListener$1(new A._FutureListener(result, 8, action, null, t1._eval$1("_FutureListener<1,1>"))); return result; }, @@ -13948,11 +13948,11 @@ var source, _this = this, t1 = _this._state; if (t1 <= 3) { - listener._nextListener = type$.nullable__FutureListener_dynamic_dynamic._as(_this._resultOrListeners); + listener._nextListener = type$.nullable__FutureListener_Object?_Object?._as(_this._resultOrListeners); _this._resultOrListeners = listener; } else { if ((t1 & 4) !== 0) { - source = type$._Future_dynamic._as(_this._resultOrListeners); + source = type$._Future_Object?._as(_this._resultOrListeners); if ((source._state & 24) === 0) { source._addListener$1(listener); return; @@ -13969,7 +13969,7 @@ return; t1 = _this._state; if (t1 <= 3) { - existingListeners = type$.nullable__FutureListener_dynamic_dynamic._as(_this._resultOrListeners); + existingListeners = type$.nullable__FutureListener_Object?_Object?._as(_this._resultOrListeners); _this._resultOrListeners = listeners; if (existingListeners != null) { next = listeners._nextListener; @@ -13979,7 +13979,7 @@ } } else { if ((t1 & 4) !== 0) { - source = type$._Future_dynamic._as(_this._resultOrListeners); + source = type$._Future_Object?._as(_this._resultOrListeners); if ((source._state & 24) === 0) { source._prependListeners$1(listeners); return; @@ -13991,7 +13991,7 @@ } }, _removeListeners$0() { - var current = type$.nullable__FutureListener_dynamic_dynamic._as(this._resultOrListeners); + var current = type$.nullable__FutureListener_Object?_Object?._as(this._resultOrListeners); this._resultOrListeners = null; return this._reverseListeners$1(current); }, @@ -14125,7 +14125,7 @@ var e, s, t1, exception, t2, t3, originalSource, joinedResult, _this = this, completeResult = null; try { t1 = _this._box_0.listener; - completeResult = t1.result._zone.run$1$1(type$.dynamic_Function._as(t1.callback), type$.dynamic); + completeResult = t1.result._zone.run$1$1(type$.Object?_Function._as(t1.callback), type$.Object?); } catch (exception) { e = A.unwrapException(exception); s = A.getTraceFromException(exception); @@ -14284,7 +14284,7 @@ return new A._MapStream(t1._bind$1($S)._eval$1("1(Stream.T)")._as(convert), this, t1._eval$1("@")._bind$1($S)._eval$1("_MapStream<1,2>")); }, map$1(_, convert) { - return this.map$1$1(0, convert, type$.dynamic); + return this.map$1$1(0, convert, type$.Object?); }, get$length(_) { var t1 = {}, @@ -14386,13 +14386,13 @@ if (t2 >= 4) throw A.wrapException(_this._badEventState$0()); if ((t2 & 2) !== 0) { - t1 = new A._Future($.Zone__current, type$._Future_dynamic); + t1 = new A._Future($.Zone__current, type$._Future_Object?); t1._asyncComplete$1(null); return t1; } t2 = _this._varData; t3 = cancelOnError === true; - t4 = new A._Future($.Zone__current, type$._Future_dynamic); + t4 = new A._Future($.Zone__current, type$._Future_Object?); t5 = t1._eval$1("~(1)")._as(_this.get$_add()); t6 = t3 ? A._AddStreamState_makeErrorHandler(_this) : _this.get$_addError(); t6 = source.listen$4$cancelOnError$onDone$onError(t5, t3, _this.get$_close(), t6); @@ -14949,7 +14949,7 @@ }; A._DelayedEvent.prototype = { set$next(next) { - this.next = type$.nullable__DelayedEvent_dynamic._as(next); + this.next = type$.nullable__DelayedEvent_Object?._as(next); }, get$next() { return this.next; @@ -15759,7 +15759,7 @@ result = _this._keys; if (result != null) return result; - result = A.List_List$filled(_this._collection$_length, null, false, type$.dynamic); + result = A.List_List$filled(_this._collection$_length, null, false, type$.Object?); strings = _this._strings; index = 0; if (strings != null) { @@ -16047,7 +16047,7 @@ result = _this._collection$_elements; if (result != null) return result; - result = A.List_List$filled(_this._collection$_length, null, false, type$.dynamic); + result = A.List_List$filled(_this._collection$_length, null, false, type$.Object?); strings = _this._strings; index = 0; if (strings != null) { @@ -16315,7 +16315,7 @@ return new A.MappedListIterable(receiver, t1._bind$1($T)._eval$1("1(ListBase.E)")._as(f), t1._eval$1("@")._bind$1($T)._eval$1("MappedListIterable<1,2>")); }, map$1(receiver, f) { - return this.map$1$1(receiver, f, type$.dynamic); + return this.map$1$1(receiver, f, type$.Object?); }, skip$1(receiver, count) { return A.SubListIterable$(receiver, count, null, A.instanceType(receiver)._eval$1("ListBase.E")); @@ -16388,7 +16388,7 @@ if ($length === 0) return; A.RangeError_checkNotNegative(skipCount, "skipCount"); - if (type$.List_dynamic._is(iterable)) { + if (type$.List_Object?._is(iterable)) { otherStart = skipCount; otherList = iterable; } else { @@ -16441,7 +16441,7 @@ return result; }, map$1(_, transform) { - var t1 = type$.dynamic; + var t1 = type$.Object?; return this.map$2$1(0, transform, t1, t1); }, containsKey$1(key) { @@ -16526,7 +16526,7 @@ return this._collection$_map.map$2$1(0, A._instanceType(this)._bind$1($K2)._bind$1($V2)._eval$1("MapEntry<1,2>(3,4)")._as(transform), $K2, $V2); }, map$1(_, transform) { - var t1 = type$.dynamic; + var t1 = type$.Object?; return this.map$2$1(0, transform, t1, t1); }, $isMap: 1 @@ -16685,7 +16685,7 @@ return new A.EfficientLengthMappedIterable(this, t1._bind$1($T)._eval$1("1(2)")._as(f), t1._eval$1("@<1>")._bind$1($T)._eval$1("EfficientLengthMappedIterable<1,2>")); }, map$1(_, f) { - return this.map$1$1(0, f, type$.dynamic); + return this.map$1$1(0, f, type$.Object?); }, toString$0(_) { return A.Iterable_iterableToFullString(this, "{", "}"); @@ -17047,7 +17047,7 @@ }, forEach$1(_, f) { var keys, i, key, value, _this = this; - type$.void_Function_String_dynamic._as(f); + type$.void_Function_String_Object?._as(f); if (_this._processed == null) return _this._convert$_data.forEach$1(0, f); keys = _this._convert$_computeKeys$0(); @@ -17064,7 +17064,7 @@ } }, _convert$_computeKeys$0() { - var keys = type$.nullable_List_dynamic._as(this._convert$_data); + var keys = type$.nullable_List_Object?._as(this._convert$_data); if (keys == null) keys = this._convert$_data = A._setArrayType(Object.keys(this._original), type$.JSArray_String); return keys; @@ -17073,7 +17073,7 @@ var result, keys, i, t1, key, _this = this; if (_this._processed == null) return _this._convert$_data; - result = A.LinkedHashMap_LinkedHashMap$_empty(type$.String, type$.dynamic); + result = A.LinkedHashMap_LinkedHashMap$_empty(type$.String, type$.Object?); keys = _this._convert$_computeKeys$0(); for (i = 0; t1 = keys.length, i < t1; ++i) { key = keys[i]; @@ -17584,7 +17584,7 @@ _this.writeStringContent$1(object); _this.writeString$1('"'); return true; - } else if (type$.List_dynamic._is(object)) { + } else if (type$.List_Object?._is(object)) { _this._checkCycle$1(object); _this.writeList$1(object); t1 = _this._seen; @@ -17592,7 +17592,7 @@ return A.ioore(t1, -1); t1.pop(); return true; - } else if (type$.Map_dynamic_dynamic._is(object)) { + } else if (type$.Map_Object?_Object?._is(object)) { _this._checkCycle$1(object); success = _this.writeMap$1(object); t1 = _this._seen; @@ -18640,7 +18640,7 @@ return A.MappedIterable_MappedIterable(this, t1._bind$1($T)._eval$1("1(Iterable.E)")._as(toElement), t1._eval$1("Iterable.E"), $T); }, map$1(_, toElement) { - return this.map$1$1(0, toElement, type$.dynamic); + return this.map$1$1(0, toElement, type$.Object?); }, contains$1(_, element) { var t1; @@ -18809,7 +18809,7 @@ t1 = false; if (t1) pathToSplit = B.JSString_methods.substring$1(pathToSplit, 1); - result = pathToSplit.length === 0 ? B.List_empty : A.List_List$unmodifiable(new A.MappedListIterable(A._setArrayType(pathToSplit.split("/"), type$.JSArray_String), type$.dynamic_Function_String._as(A.core_Uri_decodeComponent$closure()), type$.MappedListIterable_String_dynamic), type$.String); + result = pathToSplit.length === 0 ? B.List_empty : A.List_List$unmodifiable(new A.MappedListIterable(A._setArrayType(pathToSplit.split("/"), type$.JSArray_String), type$.Object?_Function_String._as(A.core_Uri_decodeComponent$closure()), type$.MappedListIterable_String_Object?), type$.String); _this.___Uri_pathSegments_FI !== $ && A.throwLateFieldADI("pathSegments"); value = _this.___Uri_pathSegments_FI = result; } @@ -19460,7 +19460,7 @@ t1 = this._convertedObjects; if (t1.containsKey$1(o)) return t1.$index(0, o); - if (type$.Map_dynamic_dynamic._is(o)) { + if (type$.Map_Object?_Object?._is(o)) { convertedMap = {}; t1.$indexSet(0, o, convertedMap); for (t1 = o.get$keys(), t1 = t1.get$iterator(t1); t1.moveNext$0();) { @@ -19468,10 +19468,10 @@ convertedMap[key] = this.call$1(o.$index(0, key)); } return convertedMap; - } else if (type$.Iterable_dynamic._is(o)) { + } else if (type$.Iterable_Object?._is(o)) { convertedList = []; t1.$indexSet(0, o, convertedList); - B.JSArray_methods.addAll$1(convertedList, J.map$1$1$ax(o, this, type$.dynamic)); + B.JSArray_methods.addAll$1(convertedList, J.map$1$1$ax(o, this, type$.Object?)); return convertedList; } else return o; @@ -19798,7 +19798,7 @@ return new A.MappedListIterable(t1, t2._bind$1($T)._eval$1("1(2)")._as(this.$ti._bind$1($T)._eval$1("1(2)")._as(f)), t2._eval$1("@<1>")._bind$1($T)._eval$1("MappedListIterable<1,2>")); }, map$1(_, f) { - return this.map$1$1(0, f, type$.dynamic); + return this.map$1$1(0, f, type$.Object?); }, contains$1(_, element) { return B.JSArray_methods.contains$1(this._list, element); @@ -19975,7 +19975,7 @@ A._BuiltListMultimap.prototype = { _BuiltListMultimap$copy$2(keys, lookup, $K, $V) { var t1, t2, t3, key; - for (t1 = keys.get$iterator(keys), t2 = this._list_multimap$_map, t3 = type$.Iterable_dynamic; t1.moveNext$0();) { + for (t1 = keys.get$iterator(keys), t2 = this._list_multimap$_map, t3 = type$.Iterable_Object?; t1.moveNext$0();) { key = t1.get$current(); if ($K._is(key)) t2.$indexSet(0, key, A.BuiltList_BuiltList$from(t3._as(lookup.call$1(key)), $V)); @@ -20052,7 +20052,7 @@ t4 = t1._eval$1("Map<1,BuiltList<2>>"); _this.__ListMultimapBuilder__builtMap_A = t4._as(A.LinkedHashMap_LinkedHashMap$_empty(t2, t3)); _this.__ListMultimapBuilder__builderMap_A = t1._eval$1("Map<1,ListBuilder<2>>")._as(A.LinkedHashMap_LinkedHashMap$_empty(t2, t1._eval$1("ListBuilder<2>"))); - for (t5 = keys.get$iterator(keys), t6 = type$.Iterable_dynamic, t1 = t1._rest[1]; t5.moveNext$0();) { + for (t5 = keys.get$iterator(keys), t6 = type$.Iterable_Object?, t1 = t1._rest[1]; t5.moveNext$0();) { key = t5.get$current(); if (t2._is(key)) for (t7 = J.get$iterator$ax(t6._as(lookup.call$1(key))); t7.moveNext$0();) { @@ -20173,8 +20173,8 @@ return this._map$_map.__js_helper$_length; }, map$1(_, f) { - var t1 = type$.dynamic; - return new A._BuiltMap(null, this._map$_map.map$2$1(0, this.$ti._eval$1("MapEntry<@,@>(1,2)")._as(f), t1, t1), type$._BuiltMap_dynamic_dynamic); + var t1 = type$.Object?; + return new A._BuiltMap(null, this._map$_map.map$2$1(0, this.$ti._eval$1("MapEntry<@,@>(1,2)")._as(f), t1, t1), type$._BuiltMap_Object?_Object?); } }; A.BuiltMap_BuiltMap_closure.prototype = { @@ -20348,7 +20348,7 @@ return new A.EfficientLengthMappedIterable(t1, t2._bind$1($T)._eval$1("1(2)")._as(this.$ti._bind$1($T)._eval$1("1(2)")._as(f)), t2._eval$1("@<1>")._bind$1($T)._eval$1("EfficientLengthMappedIterable<1,2>")); }, map$1(_, f) { - return this.map$1$1(0, f, type$.dynamic); + return this.map$1$1(0, f, type$.Object?); }, contains$1(_, element) { return this._set$_set.contains$1(0, element); @@ -20610,7 +20610,7 @@ t4 = t1._eval$1("Map<1,BuiltSet<2>>"); _this.__SetMultimapBuilder__builtMap_A = t4._as(A.LinkedHashMap_LinkedHashMap$_empty(t2, t3)); _this.__SetMultimapBuilder__builderMap_A = t1._eval$1("Map<1,SetBuilder<2>>")._as(A.LinkedHashMap_LinkedHashMap$_empty(t2, t1._eval$1("SetBuilder<2>"))); - for (t5 = keys.get$iterator(keys), t6 = type$.Iterable_dynamic, t1 = t1._rest[1]; t5.moveNext$0();) { + for (t5 = keys.get$iterator(keys), t6 = type$.Iterable_Object?, t1 = t1._rest[1]; t5.moveNext$0();) { key = t5.get$current(); if (t2._is(key)) for (t7 = J.get$iterator$ax(t6._as(lookup.call$1(key))); t7.moveNext$0();) { @@ -20966,11 +20966,11 @@ serializer = _this.serializerForType$1(t1.get$runtimeType(object)); if (serializer == null) throw A.wrapException(A.StateError$(A._noSerializerMessageFor(t1.get$runtimeType(object).toString$0(0)))); - if (type$.StructuredSerializer_dynamic._is(serializer)) { + if (type$.StructuredSerializer_Object?._is(serializer)) { result = [serializer.get$wireName()]; B.JSArray_methods.addAll$1(result, serializer.serialize$2(_this, object)); return result; - } else if (type$.PrimitiveSerializer_dynamic._is(serializer)) + } else if (type$.PrimitiveSerializer_Object?._is(serializer)) return object == null ? [serializer.get$wireName(), null] : A._setArrayType([serializer.get$wireName(), serializer.serialize$2(_this, object)], type$.JSArray_Object); else throw A.wrapException(A.StateError$(_s62_)); @@ -20978,9 +20978,9 @@ serializer = _this.serializerForType$1(t1); if (serializer == null) return _this.serialize$1(object); - if (type$.StructuredSerializer_dynamic._is(serializer)) + if (type$.StructuredSerializer_Object?._is(serializer)) return object == null ? null : J.toList$0$ax(serializer.serialize$3$specifiedType(_this, object, specifiedType)); - else if (type$.PrimitiveSerializer_dynamic._is(serializer)) + else if (type$.PrimitiveSerializer_Object?._is(serializer)) return object == null ? null : serializer.serialize$3$specifiedType(_this, object, specifiedType); else throw A.wrapException(A.StateError$(_s62_)); @@ -21013,7 +21013,7 @@ serializer = _this._wireNameToSerializer._map$_map.$index(0, wireName); if (serializer == null) throw A.wrapException(A.StateError$(A._noSerializerMessageFor(wireName))); - if (type$.StructuredSerializer_dynamic._is(serializer)) + if (type$.StructuredSerializer_Object?._is(serializer)) try { t1 = serializer.deserialize$2(_this, t1.sublist$1(object, 1)); return t1; @@ -21025,7 +21025,7 @@ } else throw exception; } - else if (type$.PrimitiveSerializer_dynamic._is(serializer)) + else if (type$.PrimitiveSerializer_Object?._is(serializer)) try { primitive = t1.$index(object, 1); t1 = primitive == null ? null : serializer.deserialize$2(_this, primitive); @@ -21043,11 +21043,11 @@ } else { serializer0 = _this.serializerForType$1(t1); if (serializer0 == null) - if (type$.List_dynamic._is(object) && typeof J.get$first$ax(object) == "string") + if (type$.List_Object?._is(object) && typeof J.get$first$ax(object) == "string") return _this.deserialize$1(objectBeforePlugins); else throw A.wrapException(A.StateError$(A._noSerializerMessageFor(t1.toString$0(0)))); - if (type$.StructuredSerializer_dynamic._is(serializer0)) + if (type$.StructuredSerializer_Object?._is(serializer0)) try { t1 = object == null ? null : serializer0.deserialize$3$specifiedType(_this, type$.Iterable_nullable_Object._as(object), specifiedType); return t1; @@ -21059,7 +21059,7 @@ } else throw exception; } - else if (type$.PrimitiveSerializer_dynamic._is(serializer0)) + else if (type$.PrimitiveSerializer_Object?._is(serializer0)) try { t1 = object == null ? null : serializer0.deserialize$3$specifiedType(_this, object, specifiedType); return t1; @@ -21095,7 +21095,7 @@ A.BuiltJsonSerializersBuilder.prototype = { add$1(_, serializer) { var t1, t2, t3, t4, t5, t6, $name, genericsStart, t7; - if (!type$.StructuredSerializer_dynamic._is(serializer) && !type$.PrimitiveSerializer_dynamic._is(serializer)) + if (!type$.StructuredSerializer_Object?._is(serializer) && !type$.PrimitiveSerializer_Object?._is(serializer)) throw A.wrapException(A.ArgumentError$(string$.serial, null)); this._wireNameToSerializer.$indexSet(0, serializer.get$wireName(), serializer); for (t1 = J.get$iterator$ax(serializer.get$types()), t2 = this._typeToSerializer, t3 = t2.$ti, t4 = t3._precomputed1, t3 = t3._rest[1], t5 = this._typeNameToSerializer; t1.moveNext$0();) { @@ -21132,7 +21132,7 @@ A.BuiltListMultimapSerializer.prototype = { serialize$3$specifiedType(serializers, builtListMultimap, specifiedType) { var t1, t2, t3, keyType, valueType, result, key, result0, t4, t5, t6, t7; - type$.BuiltListMultimap_dynamic_dynamic._as(builtListMultimap); + type$.BuiltListMultimap_Object?_Object?._as(builtListMultimap); if (!(specifiedType.root == null || specifiedType.parameters.length === 0)) if (!serializers.builderFactories._map$_map.containsKey$1(specifiedType)) serializers._throwMissingBuilderFactory$1(specifiedType); @@ -21196,7 +21196,7 @@ t2 = type$.Object; result = A.ListMultimapBuilder_ListMultimapBuilder(t2, t2); } else - result = type$.ListMultimapBuilder_dynamic_dynamic._as(serializers.newBuilder$1(specifiedType)); + result = type$.ListMultimapBuilder_Object?_Object?._as(serializers.newBuilder$1(specifiedType)); t2 = J.getInterceptor$asx(serialized); if (B.JSInt_methods.$mod(t2.get$length(serialized), 2) === 1) throw A.wrapException(A.ArgumentError$("odd length", null)); @@ -21262,7 +21262,7 @@ A.BuiltListSerializer.prototype = { serialize$3$specifiedType(serializers, builtList, specifiedType) { var t1, t2, elementType; - type$.BuiltList_dynamic._as(builtList); + type$.BuiltList_Object?._as(builtList); if (!(specifiedType.root == null || specifiedType.parameters.length === 0)) if (!serializers.builderFactories._map$_map.containsKey$1(specifiedType)) serializers._throwMissingBuilderFactory$1(specifiedType); @@ -21284,7 +21284,7 @@ }, deserialize$3$specifiedType(serializers, serialized, specifiedType) { var isUnderspecified, t1, t2, elementType, result; - type$.Iterable_dynamic._as(serialized); + type$.Iterable_Object?._as(serialized); isUnderspecified = specifiedType.root == null || specifiedType.parameters.length === 0; t1 = specifiedType.parameters; t2 = t1.length; @@ -21295,8 +21295,8 @@ return A.ioore(t1, 0); elementType = t1[0]; } - result = isUnderspecified ? A.ListBuilder_ListBuilder(B.List_empty0, type$.Object) : type$.ListBuilder_dynamic._as(serializers.newBuilder$1(specifiedType)); - result.replace$1(J.map$1$1$ax(serialized, new A.BuiltListSerializer_deserialize_closure(serializers, elementType), type$.dynamic)); + result = isUnderspecified ? A.ListBuilder_ListBuilder(B.List_empty0, type$.Object) : type$.ListBuilder_Object?._as(serializers.newBuilder$1(specifiedType)); + result.replace$1(J.map$1$1$ax(serialized, new A.BuiltListSerializer_deserialize_closure(serializers, elementType), type$.Object?)); return result.build$0(); }, deserialize$2(serializers, serialized) { @@ -21326,7 +21326,7 @@ A.BuiltMapSerializer.prototype = { serialize$3$specifiedType(serializers, builtMap, specifiedType) { var t1, t2, t3, keyType, valueType, result, key; - type$.BuiltMap_dynamic_dynamic._as(builtMap); + type$.BuiltMap_Object?_Object?._as(builtMap); if (!(specifiedType.root == null || specifiedType.parameters.length === 0)) if (!serializers.builderFactories._map$_map.containsKey$1(specifiedType)) serializers._throwMissingBuilderFactory$1(specifiedType); @@ -21360,7 +21360,7 @@ }, deserialize$3$specifiedType(serializers, serialized, specifiedType) { var isUnderspecified, t1, t2, t3, keyType, valueType, result, i, key, value; - type$.Iterable_dynamic._as(serialized); + type$.Iterable_Object?._as(serialized); isUnderspecified = specifiedType.root == null || specifiedType.parameters.length === 0; t1 = specifiedType.parameters; t2 = t1.length; @@ -21383,7 +21383,7 @@ t1 = type$.Object; result = A.MapBuilder_MapBuilder(t1, t1); } else - result = type$.MapBuilder_dynamic_dynamic._as(serializers.newBuilder$1(specifiedType)); + result = type$.MapBuilder_Object?_Object?._as(serializers.newBuilder$1(specifiedType)); t1 = J.getInterceptor$asx(serialized); if (B.JSInt_methods.$mod(t1.get$length(serialized), 2) === 1) throw A.wrapException(A.ArgumentError$("odd length", null)); @@ -21413,7 +21413,7 @@ A.BuiltSetMultimapSerializer.prototype = { serialize$3$specifiedType(serializers, builtSetMultimap, specifiedType) { var t1, t2, t3, keyType, valueType, result, key, result0, t4, t5, t6, t7; - type$.BuiltSetMultimap_dynamic_dynamic._as(builtSetMultimap); + type$.BuiltSetMultimap_Object?_Object?._as(builtSetMultimap); if (!(specifiedType.root == null || specifiedType.parameters.length === 0)) if (!serializers.builderFactories._map$_map.containsKey$1(specifiedType)) serializers._throwMissingBuilderFactory$1(specifiedType); @@ -21453,7 +21453,7 @@ }, deserialize$3$specifiedType(serializers, serialized, specifiedType) { var isUnderspecified, t2, t3, t4, keyType, valueType, result, t5, t6, i, key, t7, value, t8, t9, - t1 = type$.Iterable_dynamic; + t1 = type$.Iterable_Object?; t1._as(serialized); isUnderspecified = specifiedType.root == null || specifiedType.parameters.length === 0; t2 = specifiedType.parameters; @@ -21477,7 +21477,7 @@ t2 = type$.Object; result = A.SetMultimapBuilder_SetMultimapBuilder(t2, t2); } else - result = type$.SetMultimapBuilder_dynamic_dynamic._as(serializers.newBuilder$1(specifiedType)); + result = type$.SetMultimapBuilder_Object?_Object?._as(serializers.newBuilder$1(specifiedType)); t2 = J.getInterceptor$asx(serialized); if (B.JSInt_methods.$mod(t2.get$length(serialized), 2) === 1) throw A.wrapException(A.ArgumentError$("odd length", null)); @@ -21533,7 +21533,7 @@ A.BuiltSetSerializer.prototype = { serialize$3$specifiedType(serializers, builtSet, specifiedType) { var t1, t2, elementType; - type$.BuiltSet_dynamic._as(builtSet); + type$.BuiltSet_Object?._as(builtSet); if (!(specifiedType.root == null || specifiedType.parameters.length === 0)) if (!serializers.builderFactories._map$_map.containsKey$1(specifiedType)) serializers._throwMissingBuilderFactory$1(specifiedType); @@ -21555,7 +21555,7 @@ }, deserialize$3$specifiedType(serializers, serialized, specifiedType) { var isUnderspecified, t1, t2, elementType, result; - type$.Iterable_dynamic._as(serialized); + type$.Iterable_Object?._as(serialized); isUnderspecified = specifiedType.root == null || specifiedType.parameters.length === 0; t1 = specifiedType.parameters; t2 = t1.length; @@ -21566,8 +21566,8 @@ return A.ioore(t1, 0); elementType = t1[0]; } - result = isUnderspecified ? A.SetBuilder_SetBuilder(type$.Object) : type$.SetBuilder_dynamic._as(serializers.newBuilder$1(specifiedType)); - result.replace$1(J.map$1$1$ax(serialized, new A.BuiltSetSerializer_deserialize_closure(serializers, elementType), type$.dynamic)); + result = isUnderspecified ? A.SetBuilder_SetBuilder(type$.Object) : type$.SetBuilder_Object?._as(serializers.newBuilder$1(specifiedType)); + result.replace$1(J.map$1$1$ax(serialized, new A.BuiltSetSerializer_deserialize_closure(serializers, elementType), type$.Object?)); return result.build$0(); }, deserialize$2(serializers, serialized) { @@ -21780,7 +21780,7 @@ A.ListSerializer.prototype = { serialize$3$specifiedType(serializers, list, specifiedType) { var t1, t2, elementType; - type$.List_dynamic._as(list); + type$.List_Object?._as(list); if (!(specifiedType.root == null || specifiedType.parameters.length === 0)) if (!serializers.builderFactories._map$_map.containsKey$1(specifiedType)) serializers._throwMissingBuilderFactory$1(specifiedType); @@ -21800,7 +21800,7 @@ }, deserialize$3$specifiedType(serializers, serialized, specifiedType) { var isUnderspecified, t1, t2, elementType, result; - type$.Iterable_dynamic._as(serialized); + type$.Iterable_Object?._as(serialized); isUnderspecified = specifiedType.root == null || specifiedType.parameters.length === 0; t1 = specifiedType.parameters; t2 = t1.length; @@ -21811,7 +21811,7 @@ return A.ioore(t1, 0); elementType = t1[0]; } - result = isUnderspecified ? A._setArrayType([], type$.JSArray_Object) : type$.List_dynamic._as(serializers.newBuilder$1(specifiedType)); + result = isUnderspecified ? A._setArrayType([], type$.JSArray_Object) : type$.List_Object?._as(serializers.newBuilder$1(specifiedType)); for (t1 = J.get$iterator$ax(serialized), t2 = J.getInterceptor$ax(result); t1.moveNext$0();) t2.add$1(result, serializers.deserialize$2$specifiedType(t1.get$current(), elementType)); return result; @@ -21837,7 +21837,7 @@ A.MapSerializer.prototype = { serialize$3$specifiedType(serializers, $Map, specifiedType) { var t1, t2, t3, keyType, valueType, result, key; - type$.Map_dynamic_dynamic._as($Map); + type$.Map_Object?_Object?._as($Map); if (!(specifiedType.root == null || specifiedType.parameters.length === 0)) if (!serializers.builderFactories._map$_map.containsKey$1(specifiedType)) serializers._throwMissingBuilderFactory$1(specifiedType); @@ -21871,7 +21871,7 @@ }, deserialize$3$specifiedType(serializers, serialized, specifiedType) { var isUnderspecified, t1, t2, t3, keyType, valueType, result, i; - type$.Iterable_dynamic._as(serialized); + type$.Iterable_Object?._as(serialized); isUnderspecified = specifiedType.root == null || specifiedType.parameters.length === 0; t1 = specifiedType.parameters; t2 = t1.length; @@ -21894,7 +21894,7 @@ t1 = type$.Object; result = A.LinkedHashMap_LinkedHashMap$_empty(t1, t1); } else - result = type$.Map_dynamic_dynamic._as(serializers.newBuilder$1(specifiedType)); + result = type$.Map_Object?_Object?._as(serializers.newBuilder$1(specifiedType)); t1 = J.getInterceptor$asx(serialized); if (B.JSInt_methods.$mod(t1.get$length(serialized), 2) === 1) throw A.wrapException(A.ArgumentError$("odd length", null)); @@ -21998,7 +21998,7 @@ A.SetSerializer.prototype = { serialize$3$specifiedType(serializers, set, specifiedType) { var t1, t2, elementType; - type$.Set_dynamic._as(set); + type$.Set_Object?._as(set); if (!(specifiedType.root == null || specifiedType.parameters.length === 0)) if (!serializers.builderFactories._map$_map.containsKey$1(specifiedType)) serializers._throwMissingBuilderFactory$1(specifiedType); @@ -22018,7 +22018,7 @@ }, deserialize$3$specifiedType(serializers, serialized, specifiedType) { var isUnderspecified, t1, t2, elementType, result; - type$.Iterable_dynamic._as(serialized); + type$.Iterable_Object?._as(serialized); isUnderspecified = specifiedType.root == null || specifiedType.parameters.length === 0; t1 = specifiedType.parameters; t2 = t1.length; @@ -22029,7 +22029,7 @@ return A.ioore(t1, 0); elementType = t1[0]; } - result = isUnderspecified ? A.LinkedHashSet_LinkedHashSet$_empty(type$.Object) : type$.Set_dynamic._as(serializers.newBuilder$1(specifiedType)); + result = isUnderspecified ? A.LinkedHashSet_LinkedHashSet$_empty(type$.Object) : type$.Set_Object?._as(serializers.newBuilder$1(specifiedType)); for (t1 = J.get$iterator$ax(serialized); t1.moveNext$0();) result.add$1(0, serializers.deserialize$2$specifiedType(t1.get$current(), elementType)); return result; @@ -22170,7 +22170,7 @@ return this._base.map$2$1(0, new A.CanonicalizedMap_map_closure(this, this.$ti._bind$1($K2)._bind$1($V2)._eval$1("MapEntry<1,2>(CanonicalizedMap.K,CanonicalizedMap.V)")._as(transform), $K2, $V2), $K2, $V2); }, map$1(_, transform) { - var t1 = type$.dynamic; + var t1 = type$.Object?; return this.map$2$1(0, transform, t1, t1); }, toString$0(_) { @@ -22393,30 +22393,30 @@ A.DeepCollectionEquality.prototype = { equals$2(e1, e2) { var _this = this, - t1 = type$.Set_dynamic; + t1 = type$.Set_Object?; if (t1._is(e1)) - return t1._is(e2) && new A.SetEquality(_this, type$.SetEquality_dynamic).equals$2(e1, e2); - t1 = type$.Map_dynamic_dynamic; + return t1._is(e2) && new A.SetEquality(_this, type$.SetEquality_Object?).equals$2(e1, e2); + t1 = type$.Map_Object?_Object?; if (t1._is(e1)) - return t1._is(e2) && new A.MapEquality(_this, _this, type$.MapEquality_dynamic_dynamic).equals$2(e1, e2); - t1 = type$.List_dynamic; + return t1._is(e2) && new A.MapEquality(_this, _this, type$.MapEquality_Object?_Object?).equals$2(e1, e2); + t1 = type$.List_Object?; if (t1._is(e1)) - return t1._is(e2) && new A.ListEquality(_this, type$.ListEquality_dynamic).equals$2(e1, e2); - t1 = type$.Iterable_dynamic; + return t1._is(e2) && new A.ListEquality(_this, type$.ListEquality_Object?).equals$2(e1, e2); + t1 = type$.Iterable_Object?; if (t1._is(e1)) - return t1._is(e2) && new A.IterableEquality(_this, type$.IterableEquality_dynamic).equals$2(e1, e2); + return t1._is(e2) && new A.IterableEquality(_this, type$.IterableEquality_Object?).equals$2(e1, e2); return J.$eq$(e1, e2); }, hash$1(o) { var _this = this; - if (type$.Set_dynamic._is(o)) - return new A.SetEquality(_this, type$.SetEquality_dynamic).hash$1(o); - if (type$.Map_dynamic_dynamic._is(o)) - return new A.MapEquality(_this, _this, type$.MapEquality_dynamic_dynamic).hash$1(o); - if (type$.List_dynamic._is(o)) - return new A.ListEquality(_this, type$.ListEquality_dynamic).hash$1(o); - if (type$.Iterable_dynamic._is(o)) - return new A.IterableEquality(_this, type$.IterableEquality_dynamic).hash$1(o); + if (type$.Set_Object?._is(o)) + return new A.SetEquality(_this, type$.SetEquality_Object?).hash$1(o); + if (type$.Map_Object?_Object?._is(o)) + return new A.MapEquality(_this, _this, type$.MapEquality_Object?_Object?).hash$1(o); + if (type$.List_Object?._is(o)) + return new A.ListEquality(_this, type$.ListEquality_Object?).hash$1(o); + if (type$.Iterable_Object?._is(o)) + return new A.IterableEquality(_this, type$.IterableEquality_Object?).hash$1(o); return J.get$hashCode$(o); }, isValidKey$1(o) { @@ -28087,7 +28087,7 @@ t5 = A.StreamController_StreamController(null, null, null, false, type$.List_DebugEvent); debugEventController = new A.BatchedStreamController(t3, 1000, t4, t5, new A._AsyncCompleter(new A._Future(t2, type$._Future_bool), type$._AsyncCompleter_bool), type$.BatchedStreamController_DebugEvent); t2 = A.List_List$filled(A.QueueList__computeInitialCapacity(null), null, false, type$.nullable_Result_DebugEvent); - t3 = A.ListQueue$(type$._EventRequest_dynamic); + t3 = A.ListQueue$(type$._EventRequest_Object?); t6 = type$.StreamQueue_DebugEvent; debugEventController.__BatchedStreamController__inputQueue_A = t6._as(new A.StreamQueue(new A._ControllerStream(t4, A._instanceType(t4)._eval$1("_ControllerStream<1>")), new A.QueueList(t2, 0, 0, type$.QueueList_Result_DebugEvent), t3, t6)); A.safeUnawaited(debugEventController._batchAndSendEvents$0()); @@ -28137,8 +28137,8 @@ t2 = init.G; t3 = type$.nullable_JSArray_nullable_Object; if (pauseIsolatesOnStart === true) { - t4 = new A._Future($.Zone__current, type$._Future_dynamic); - this._box_0.readyToRunMainCompleter = new A._AsyncCompleter(t4, type$._AsyncCompleter_dynamic); + t4 = new A._Future($.Zone__current, type$._Future_Object?); + this._box_0.readyToRunMainCompleter = new A._AsyncCompleter(t4, type$._AsyncCompleter_Object?); return A.FutureOfJSAnyToJSPromise_get_toJS(t1.hotRestart$3$readyToRunMain$reloadedSourcesPath$runId(t4, A._asStringQ(t2.$reloadedSourcesPath), runId), t3); } else return A.FutureOfJSAnyToJSPromise_get_toJS(t1.hotRestart$2$reloadedSourcesPath$runId(A._asStringQ(t2.$reloadedSourcesPath), runId), t3); @@ -28175,7 +28175,7 @@ t2 = $.$get$serializers(); t3 = new A.BatchedDebugEventsBuilder(); type$.nullable_void_Function_BatchedDebugEventsBuilder._as(new A.main___closure2(events)).call$1(t3); - A._trySendEvent(t1, B.C_JsonCodec.encode$2$toEncodable(t2.serialize$1(t3._debug_event$_build$0()), null), type$.dynamic); + A._trySendEvent(t1, B.C_JsonCodec.encode$2$toEncodable(t2.serialize$1(t3._debug_event$_build$0()), null), type$.Object?); } }, $signature: 75 @@ -28221,7 +28221,7 @@ t2 = $.$get$serializers(); t3 = new A.RegisterEventBuilder(); type$.nullable_void_Function_RegisterEventBuilder._as(new A.main___closure0(eventData)).call$1(t3); - A._trySendEvent(t1, B.C_JsonCodec.encode$2$toEncodable(t2.serialize$1(t3._register_event$_build$0()), null), type$.dynamic); + A._trySendEvent(t1, B.C_JsonCodec.encode$2$toEncodable(t2.serialize$1(t3._register_event$_build$0()), null), type$.Object?); }, $signature: 79 }; @@ -28245,7 +28245,7 @@ t2 = $.$get$serializers(); t3 = new A.DevToolsRequestBuilder(); type$.nullable_void_Function_DevToolsRequestBuilder._as(new A.main___closure()).call$1(t3); - A._trySendEvent(t1, B.C_JsonCodec.encode$2$toEncodable(t2.serialize$1(t3._devtools_request$_build$0()), null), type$.dynamic); + A._trySendEvent(t1, B.C_JsonCodec.encode$2$toEncodable(t2.serialize$1(t3._devtools_request$_build$0()), null), type$.Object?); }, $signature: 1 }; @@ -28537,7 +28537,7 @@ }, _getSrcModuleLibraries$1(reloadedSourcesPath) { var $async$goto = 0, - $async$completer = A._makeAsyncAwaitCompleter(type$.List_Map_dynamic_dynamic), + $async$completer = A._makeAsyncAwaitCompleter(type$.List_Map_Object?_Object?), $async$returnValue, t1, xhr, $async$temp1, $async$temp2, $async$temp3; var $async$_getSrcModuleLibraries$1 = A._wrapJsFunctionForAsync(function($async$errorCode, $async$result) { if ($async$errorCode === 1) @@ -28553,13 +28553,13 @@ xhr.open("GET", reloadedSourcesPath, true); xhr.send(); $async$temp1 = J; - $async$temp2 = type$.List_dynamic; + $async$temp2 = type$.List_Object?; $async$temp3 = B.C_JsonCodec; $async$goto = 3; return A._asyncAwait(t1, $async$_getSrcModuleLibraries$1); case 3: // returning from await. - $async$returnValue = $async$temp1.cast$1$0$ax($async$temp2._as($async$temp3.decode$1($async$result)), type$.Map_dynamic_dynamic); + $async$returnValue = $async$temp1.cast$1$0$ax($async$temp2._as($async$temp3.decode$1($async$result)), type$.Map_Object?_Object?); // goto return $async$goto = 1; break; @@ -28629,7 +28629,7 @@ case 3: // returning from await. srcModuleLibraries = $async$result; - for (t3 = J.get$iterator$ax(srcModuleLibraries), t4 = type$.String, t5 = type$.Object, t6 = type$.List_dynamic; t3.moveNext$0();) { + for (t3 = J.get$iterator$ax(srcModuleLibraries), t4 = type$.String, t5 = type$.Object, t6 = type$.List_Object?; t3.moveNext$0();) { srcModuleLibraryCast = t3.get$current().cast$2$0(0, t4, t5); src = A._asString(srcModuleLibraryCast.$index(0, "src")); libraries = J.cast$1$0$ax(t6._as(srcModuleLibraryCast.$index(0, "libraries")), t4); @@ -28674,11 +28674,11 @@ return A._asyncStartSync($async$hotReloadEnd$0, $async$completer); }, handleServiceExtension$2(method, args) { - return this.handleServiceExtension$body$DdcLibraryBundleRestarter(method, type$.Map_String_dynamic._as(args)); + return this.handleServiceExtension$body$DdcLibraryBundleRestarter(method, type$.Map_String_Object?._as(args)); }, handleServiceExtension$body$DdcLibraryBundleRestarter(method, args) { var $async$goto = 0, - $async$completer = A._makeAsyncAwaitCompleter(type$.nullable_Map_String_dynamic), + $async$completer = A._makeAsyncAwaitCompleter(type$.nullable_Map_String_Object?), $async$returnValue, t1, t2, params, $async$temp1, $async$temp2; var $async$handleServiceExtension$2 = A._wrapJsFunctionForAsync(function($async$errorCode, $async$result) { if ($async$errorCode === 1) @@ -28695,7 +28695,7 @@ return A._asyncAwait(A._Debugger_maybeInvokeFlutterReassemble(A._asJSObject(A._asJSObject(init.G.dartDevEmbedder).debugger)), $async$handleServiceExtension$2); case 6: // returning from await. - $async$returnValue = A.LinkedHashMap_LinkedHashMap$_literal(["status", "reassemble invoked"], type$.String, type$.dynamic); + $async$returnValue = A.LinkedHashMap_LinkedHashMap$_literal(["status", "reassemble invoked"], type$.String, type$.Object?); // goto return $async$goto = 1; break; @@ -28711,7 +28711,7 @@ t1 = type$.JSArray_nullable_Object._as(A._asJSObject(A._asJSObject(init.G.dartDevEmbedder).debugger).extensionNames); t1 = type$.List_String._is(t1) ? t1 : new A.CastList(t1, A._arrayInstanceType(t1)._eval$1("CastList<1,String>")); t2 = type$.String; - $async$returnValue = A.LinkedHashMap_LinkedHashMap$_literal(["rpcs", J.cast$1$0$ax(t1, t2)], t2, type$.dynamic); + $async$returnValue = A.LinkedHashMap_LinkedHashMap$_literal(["rpcs", J.cast$1$0$ax(t1, t2)], t2, type$.Object?); // goto return $async$goto = 1; break; @@ -28721,7 +28721,7 @@ case 9: // else params = args.get$isNotEmpty(args) ? B.C_JsonCodec.encode$2$toEncodable(args, null) : "{}"; - $async$temp1 = type$.Map_String_dynamic; + $async$temp1 = type$.Map_String_Object?; $async$temp2 = B.C_JsonCodec; $async$goto = 10; return A._asyncAwait(A.promiseToFuture(A._asJSObject(A._asJSObject(A._asJSObject(init.G.dartDevEmbedder).debugger).invokeExtension(method, params)), type$.String), $async$handleServiceExtension$2); @@ -28811,7 +28811,7 @@ call$1($event) { var t1 = $event.data, message = t1 == null ? null : A.dartify(t1); - if (type$.Map_dynamic_dynamic._is(message) && J.$eq$(message.$index(0, "type"), "DDC_STATE_CHANGE") && J.$eq$(message.$index(0, "state"), "restart_end")) + if (type$.Map_Object?_Object?._is(message) && J.$eq$(message.$index(0, "type"), "DDC_STATE_CHANGE") && J.$eq$(message.$index(0, "state"), "restart_end")) this.reloadCompleter.complete$1(true); }, $signature: 2 @@ -28884,11 +28884,11 @@ return A._asyncStartSync($async$hotReloadEnd$0, $async$completer); }, handleServiceExtension$2(method, args) { - return this.handleServiceExtension$body$ReloadingManager(method, type$.Map_String_dynamic._as(args)); + return this.handleServiceExtension$body$ReloadingManager(method, type$.Map_String_Object?._as(args)); }, handleServiceExtension$body$ReloadingManager(method, args) { var $async$goto = 0, - $async$completer = A._makeAsyncAwaitCompleter(type$.nullable_Map_String_dynamic), + $async$completer = A._makeAsyncAwaitCompleter(type$.nullable_Map_String_Object?), $async$returnValue, $async$self = this, restarter; var $async$handleServiceExtension$2 = A._wrapJsFunctionForAsync(function($async$errorCode, $async$result) { if ($async$errorCode === 1) @@ -29071,7 +29071,7 @@ // returning from await. response = $async$result; t1 = type$.String; - $async$returnValue = type$.Map_dynamic_dynamic._as(B.C_JsonCodec.decode$2$reviver(A.encodingForContentTypeHeader(A._contentTypeForHeaders(response.headers)).decode$1(response.bodyBytes), null)).cast$2$0(0, t1, t1); + $async$returnValue = type$.Map_Object?_Object?._as(B.C_JsonCodec.decode$2$reviver(A.encodingForContentTypeHeader(A._contentTypeForHeaders(response.headers)).decode$1(response.bodyBytes), null)).cast$2$0(0, t1, t1); // goto return $async$goto = 1; break; @@ -29285,8 +29285,8 @@ return A._asyncStartSync($async$_reload$1, $async$completer); }, _reloadModule$1(moduleId) { - var t1 = new A._Future($.Zone__current, type$._Future_dynamic), - completer = new A._AsyncCompleter(t1, type$._AsyncCompleter_dynamic), + var t1 = new A._Future($.Zone__current, type$._Future_Object?), + completer = new A._AsyncCompleter(t1, type$._AsyncCompleter_Object?), stackTrace = A.StackTrace_current(); type$.JavaScriptObject._as(init.G.$requireLoader).forceLoadModule(moduleId, A._functionToJS0(new A.RequireRestarter__reloadModule_closure(completer)), A._functionToJS1(new A.RequireRestarter__reloadModule_closure0(completer, stackTrace))); return t1; @@ -29410,25 +29410,25 @@ _static_0(A, "async___nullDoneHandler$closure", "_nullDoneHandler", 0); _static(A, "async___rootHandleUncaughtError$closure", 5, null, ["call$5"], ["_rootHandleUncaughtError"], 94, 0); _static(A, "async___rootRun$closure", 4, null, ["call$1$4", "call$4"], ["_rootRun", function($self, $parent, zone, f) { - return A._rootRun($self, $parent, zone, f, type$.dynamic); + return A._rootRun($self, $parent, zone, f, type$.Object?); }], 95, 1); _static(A, "async___rootRunUnary$closure", 5, null, ["call$2$5", "call$5"], ["_rootRunUnary", function($self, $parent, zone, f, arg) { - var t1 = type$.dynamic; + var t1 = type$.Object?; return A._rootRunUnary($self, $parent, zone, f, arg, t1, t1); }], 96, 1); _static(A, "async___rootRunBinary$closure", 6, null, ["call$3$6", "call$6"], ["_rootRunBinary", function($self, $parent, zone, f, arg1, arg2) { - var t1 = type$.dynamic; + var t1 = type$.Object?; return A._rootRunBinary($self, $parent, zone, f, arg1, arg2, t1, t1, t1); }], 97, 1); _static(A, "async___rootRegisterCallback$closure", 4, null, ["call$1$4", "call$4"], ["_rootRegisterCallback", function($self, $parent, zone, f) { - return A._rootRegisterCallback($self, $parent, zone, f, type$.dynamic); + return A._rootRegisterCallback($self, $parent, zone, f, type$.Object?); }], 98, 0); _static(A, "async___rootRegisterUnaryCallback$closure", 4, null, ["call$2$4", "call$4"], ["_rootRegisterUnaryCallback", function($self, $parent, zone, f) { - var t1 = type$.dynamic; + var t1 = type$.Object?; return A._rootRegisterUnaryCallback($self, $parent, zone, f, t1, t1); }], 99, 0); _static(A, "async___rootRegisterBinaryCallback$closure", 4, null, ["call$3$4", "call$4"], ["_rootRegisterBinaryCallback", function($self, $parent, zone, f) { - var t1 = type$.dynamic; + var t1 = type$.Object?; return A._rootRegisterBinaryCallback($self, $parent, zone, f, t1, t1, t1); }], 100, 0); _static(A, "async___rootErrorCallback$closure", 5, null, ["call$5"], ["_rootErrorCallback"], 101, 0); @@ -29671,17 +29671,17 @@ BrowserWebSocket: findType("BrowserWebSocket"), BuildResult: findType("BuildResult"), BuildStatus: findType("BuildStatus"), - BuiltListMultimap_dynamic_dynamic: findType("BuiltListMultimap<@,@>"), - BuiltList_dynamic: findType("BuiltList<@>"), + BuiltListMultimap_Object?_Object?: findType("BuiltListMultimap<@,@>"), + BuiltList_Object?: findType("BuiltList<@>"), BuiltList_nullable_Object: findType("BuiltList"), - BuiltMap_dynamic_dynamic: findType("BuiltMap<@,@>"), - BuiltSetMultimap_dynamic_dynamic: findType("BuiltSetMultimap<@,@>"), - BuiltSet_dynamic: findType("BuiltSet<@>"), + BuiltMap_Object?_Object?: findType("BuiltMap<@,@>"), + BuiltSetMultimap_Object?_Object?: findType("BuiltSetMultimap<@,@>"), + BuiltSet_Object?: findType("BuiltSet<@>"), ByteBuffer: findType("ByteBuffer"), ByteData: findType("ByteData"), CaseInsensitiveMap_String: findType("CaseInsensitiveMap"), CodeUnits: findType("CodeUnits"), - Comparable_dynamic: findType("Comparable<@>"), + Comparable_Object?: findType("Comparable<@>"), ConnectRequest: findType("ConnectRequest"), DateTime: findType("DateTime"), DebugEvent: findType("DebugEvent"), @@ -29689,7 +29689,7 @@ DevToolsRequest: findType("DevToolsRequest"), DevToolsResponse: findType("DevToolsResponse"), Duration: findType("Duration"), - EfficientLengthIterable_dynamic: findType("EfficientLengthIterable<@>"), + EfficientLengthIterable_Object?: findType("EfficientLengthIterable<@>"), Error: findType("Error"), ErrorResponse: findType("ErrorResponse"), Exception: findType("Exception"), @@ -29713,9 +29713,9 @@ Int8List: findType("Int8List"), IsolateExit: findType("IsolateExit"), IsolateStart: findType("IsolateStart"), - IterableEquality_dynamic: findType("IterableEquality<@>"), + IterableEquality_Object?: findType("IterableEquality<@>"), Iterable_String: findType("Iterable"), - Iterable_dynamic: findType("Iterable<@>"), + Iterable_Object?: findType("Iterable<@>"), Iterable_int: findType("Iterable"), Iterable_nullable_Object: findType("Iterable"), JSArray_FullType: findType("JSArray"), @@ -29725,41 +29725,41 @@ JSArray_Type: findType("JSArray"), JSArray__Highlight: findType("JSArray<_Highlight>"), JSArray__Line: findType("JSArray<_Line>"), - JSArray_dynamic: findType("JSArray<@>"), + JSArray_Object?: findType("JSArray<@>"), JSArray_int: findType("JSArray"), JSArray_nullable_Object: findType("JSArray"), JSArray_nullable_String: findType("JSArray"), - JSIndexable_dynamic: findType("JSIndexable<@>"), + JSIndexable_Object?: findType("JSIndexable<@>"), JSNull: findType("JSNull"), JSObject: findType("JSObject"), JavaScriptFunction: findType("JavaScriptFunction"), - JavaScriptIndexingBehavior_dynamic: findType("JavaScriptIndexingBehavior<@>"), + JavaScriptIndexingBehavior_Object?: findType("JavaScriptIndexingBehavior<@>"), JavaScriptObject: findType("JavaScriptObject"), JsonObject: findType("JsonObject"), Level: findType("Level"), ListBuilder_DebugEvent: findType("ListBuilder"), ListBuilder_ExtensionEvent: findType("ListBuilder"), - ListBuilder_dynamic: findType("ListBuilder<@>"), - ListEquality_dynamic: findType("ListEquality<@>"), - ListMultimapBuilder_dynamic_dynamic: findType("ListMultimapBuilder<@,@>"), + ListBuilder_Object?: findType("ListBuilder<@>"), + ListEquality_Object?: findType("ListEquality<@>"), + ListMultimapBuilder_Object?_Object?: findType("ListMultimapBuilder<@,@>"), List_DebugEvent: findType("List"), List_ExtensionEvent: findType("List"), - List_Map_dynamic_dynamic: findType("List>"), + List_Map_Object?_Object?: findType("List>"), List_String: findType("List"), - List_dynamic: findType("List<@>"), + List_Object?: findType("List<@>"), List_int: findType("List"), List_nullable_Object: findType("List"), List_nullable__Highlight: findType("List<_Highlight?>"), Logger: findType("Logger"), - MapBuilder_dynamic_dynamic: findType("MapBuilder<@,@>"), + MapBuilder_Object?_Object?: findType("MapBuilder<@,@>"), MapEntry_String_String: findType("MapEntry"), MapEntry_of_Object_and_List__Highlight: findType("MapEntry>"), - MapEquality_dynamic_dynamic: findType("MapEquality<@,@>"), + MapEquality_Object?_Object?: findType("MapEquality<@,@>"), Map_String_String: findType("Map"), - Map_String_dynamic: findType("Map"), - Map_dynamic_dynamic: findType("Map<@,@>"), + Map_String_Object?: findType("Map"), + Map_Object?_Object?: findType("Map<@,@>"), Map_of_String_and_nullable_Object: findType("Map"), - MappedListIterable_String_dynamic: findType("MappedListIterable"), + MappedListIterable_String_Object?: findType("MappedListIterable"), MediaType: findType("MediaType"), NativeArrayBuffer: findType("NativeArrayBuffer"), NativeTypedArrayOfInt: findType("NativeTypedArrayOfInt"), @@ -29767,7 +29767,7 @@ Null: findType("Null"), Object: findType("Object"), PoolResource: findType("PoolResource"), - PrimitiveSerializer_dynamic: findType("PrimitiveSerializer<@>"), + PrimitiveSerializer_Object?: findType("PrimitiveSerializer<@>"), QueueList_Result_DebugEvent: findType("QueueList>"), Record: findType("Record"), Record_0: findType("+()"), @@ -29780,13 +29780,13 @@ ReversedListIterable_String: findType("ReversedListIterable"), RunRequest: findType("RunRequest"), SerializerPlugin: findType("SerializerPlugin"), - Serializer_dynamic: findType("Serializer<@>"), + Serializer_Object?: findType("Serializer<@>"), ServiceExtensionRequest: findType("ServiceExtensionRequest"), ServiceExtensionResponse: findType("ServiceExtensionResponse"), - SetBuilder_dynamic: findType("SetBuilder<@>"), - SetEquality_dynamic: findType("SetEquality<@>"), - SetMultimapBuilder_dynamic_dynamic: findType("SetMultimapBuilder<@,@>"), - Set_dynamic: findType("Set<@>"), + SetBuilder_Object?: findType("SetBuilder<@>"), + SetEquality_Object?: findType("SetEquality<@>"), + SetMultimapBuilder_Object?_Object?: findType("SetMultimapBuilder<@,@>"), + Set_Object?: findType("Set<@>"), SourceLocation: findType("SourceLocation"), SourceSpan: findType("SourceSpan"), SourceSpanWithContext: findType("SourceSpanWithContext"), @@ -29794,11 +29794,11 @@ StackTrace: findType("StackTrace"), StreamChannelController_nullable_Object: findType("StreamChannelController"), StreamQueue_DebugEvent: findType("StreamQueue"), - Stream_dynamic: findType("Stream<@>"), + Stream_Object?: findType("Stream<@>"), StreamedResponse: findType("StreamedResponse"), String: findType("String"), String_Function_Match: findType("String(Match)"), - StructuredSerializer_dynamic: findType("StructuredSerializer<@>"), + StructuredSerializer_Object?: findType("StructuredSerializer<@>"), Timer: findType("Timer"), TrustedGetRuntimeType: findType("TrustedGetRuntimeType"), Type: findType("Type"), @@ -29821,19 +29821,19 @@ _AsyncCompleter_String: findType("_AsyncCompleter"), _AsyncCompleter_Uint8List: findType("_AsyncCompleter"), _AsyncCompleter_bool: findType("_AsyncCompleter"), - _AsyncCompleter_dynamic: findType("_AsyncCompleter<@>"), + _AsyncCompleter_Object?: findType("_AsyncCompleter<@>"), _AsyncCompleter_void: findType("_AsyncCompleter<~>"), _AsyncStreamController_List_int: findType("_AsyncStreamController>"), _BigIntImpl: findType("_BigIntImpl"), - _BuiltMap_dynamic_dynamic: findType("_BuiltMap<@,@>"), - _EventRequest_dynamic: findType("_EventRequest<@>"), + _BuiltMap_Object?_Object?: findType("_BuiltMap<@,@>"), + _EventRequest_Object?: findType("_EventRequest<@>"), _EventStream_JSObject: findType("_EventStream"), _Future_BrowserWebSocket: findType("_Future"), _Future_PoolResource: findType("_Future"), _Future_String: findType("_Future"), _Future_Uint8List: findType("_Future"), _Future_bool: findType("_Future"), - _Future_dynamic: findType("_Future<@>"), + _Future_Object?: findType("_Future<@>"), _Future_int: findType("_Future"), _Future_void: findType("_Future<~>"), _Highlight: findType("_Highlight"), @@ -29847,19 +29847,19 @@ bool_Function_Object: findType("bool(Object)"), bool_Function__Highlight: findType("bool(_Highlight)"), double: findType("double"), - dynamic: findType("@"), - dynamic_Function: findType("@()"), - dynamic_Function_Object: findType("@(Object)"), - dynamic_Function_Object_StackTrace: findType("@(Object,StackTrace)"), - dynamic_Function_String: findType("@(String)"), + Object?: findType("@"), + Object?_Function: findType("@()"), + Object?_Function_Object: findType("@(Object)"), + Object?_Function_Object_StackTrace: findType("@(Object,StackTrace)"), + Object?_Function_String: findType("@(String)"), int: findType("int"), nullable_Future_Null: findType("Future?"), nullable_JSArray_nullable_Object: findType("JSArray?"), nullable_JSObject: findType("JSObject?"), nullable_ListBuilder_DebugEvent: findType("ListBuilder?"), nullable_ListBuilder_ExtensionEvent: findType("ListBuilder?"), - nullable_List_dynamic: findType("List<@>?"), - nullable_Map_String_dynamic: findType("Map?"), + nullable_List_Object?: findType("List<@>?"), + nullable_Map_String_Object?: findType("Map?"), nullable_Map_of_nullable_Object_and_nullable_Object: findType("Map?"), nullable_Object: findType("Object?"), nullable_Result_DebugEvent: findType("Result?"), @@ -29869,8 +29869,8 @@ nullable_Zone: findType("Zone?"), nullable_ZoneDelegate: findType("ZoneDelegate?"), nullable_ZoneSpecification: findType("ZoneSpecification?"), - nullable__DelayedEvent_dynamic: findType("_DelayedEvent<@>?"), - nullable__FutureListener_dynamic_dynamic: findType("_FutureListener<@,@>?"), + nullable__DelayedEvent_Object?: findType("_DelayedEvent<@>?"), + nullable__FutureListener_Object?_Object?: findType("_FutureListener<@,@>?"), nullable__Highlight: findType("_Highlight?"), nullable__LinkedHashSetCell: findType("_LinkedHashSetCell?"), nullable_bool: findType("bool?"), @@ -29897,9 +29897,9 @@ void_Function_List_int: findType("~(List)"), void_Function_Object: findType("~(Object)"), void_Function_Object_StackTrace: findType("~(Object,StackTrace)"), - void_Function_String_dynamic: findType("~(String,@)"), + void_Function_String_Object?: findType("~(String,@)"), void_Function_Timer: findType("~(Timer)"), - void_Function_int_dynamic: findType("~(int,@)") + void_Function_int_Object?: findType("~(int,@)") }; })(); (function constants() { @@ -30162,7 +30162,7 @@ B.Type__$HotReloadRequest_ynq = A.typeLiteral("_$HotReloadRequest"); B.List_dz9 = makeConstList([B.Type_HotReloadRequest_EsW, B.Type__$HotReloadRequest_ynq], type$.JSArray_Type); B.List_empty = makeConstList([], type$.JSArray_String); - B.List_empty0 = makeConstList([], type$.JSArray_dynamic); + B.List_empty0 = makeConstList([], type$.JSArray_Object?); B.List_fAJ = makeConstList(["d", "D", "\u2202", "\xce"], type$.JSArray_String); B.Type__$DebugEvent_YX4 = A.typeLiteral("_$DebugEvent"); B.List_fK8 = makeConstList([B.Type_DebugEvent_gLJ, B.Type__$DebugEvent_YX4], type$.JSArray_Type); @@ -30322,7 +30322,7 @@ _lazyFinal($, "_AsyncRun__scheduleImmediateClosure", "$get$_AsyncRun__scheduleImmediateClosure", () => A._AsyncRun__initializeScheduleImmediate()); _lazyFinal($, "Future__nullFuture", "$get$Future__nullFuture", () => $.$get$nullFuture()); _lazyFinal($, "_RootZone__rootMap", "$get$_RootZone__rootMap", () => { - var t1 = type$.dynamic; + var t1 = type$.Object?; return A.HashMap_HashMap(null, null, null, t1, t1); }); _lazyFinal($, "_Utf8Decoder__reusableBuffer", "$get$_Utf8Decoder__reusableBuffer", () => A.NativeUint8List_NativeUint8List(4096)); diff --git a/dwds/lib/src/loaders/build_runner_require.dart b/dwds/lib/src/loaders/build_runner_require.dart index 459f77d12..e186fcf80 100644 --- a/dwds/lib/src/loaders/build_runner_require.dart +++ b/dwds/lib/src/loaders/build_runner_require.dart @@ -5,15 +5,16 @@ import 'dart:convert'; import 'dart:io'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/loaders/require.dart'; -import 'package:dwds/src/loaders/strategy.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'package:shelf/shelf.dart'; +import '../debugging/metadata/provider.dart'; +import '../readers/asset_reader.dart'; +import '../services/expression_compiler.dart'; +import 'require.dart'; +import 'strategy.dart'; + /// Provides a [RequireStrategy] suitable for use with `package:build_runner`. class BuildRunnerRequireStrategyProvider { final _logger = Logger('BuildRunnerRequireStrategyProvider'); @@ -64,7 +65,7 @@ class BuildRunnerRequireStrategyProvider { throw StateError('Could not read digests at path: $digestsPath'); } final body = await response.readAsString(); - final digests = json.decode(body) as Map; + final digests = json.decode(body) as Map; for (final key in digests.keys) { if (!modules.containsKey(key)) { diff --git a/dwds/lib/src/loaders/ddc.dart b/dwds/lib/src/loaders/ddc.dart index 1ae77faff..f8320b609 100644 --- a/dwds/lib/src/loaders/ddc.dart +++ b/dwds/lib/src/loaders/ddc.dart @@ -4,14 +4,15 @@ import 'dart:convert'; -import 'package:dwds/src/debugging/dart_runtime_debugger.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/loaders/strategy.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; import 'package:path/path.dart' as p; import 'package:shelf/shelf.dart'; +import '../debugging/dart_runtime_debugger.dart'; +import '../debugging/metadata/provider.dart'; +import '../readers/asset_reader.dart'; +import '../services/expression_compiler.dart'; +import 'strategy.dart'; + String removeJsExtension(String path) => path.endsWith('.js') ? p.withoutExtension(path) : path; @@ -127,7 +128,7 @@ class DdcStrategy extends LoadStrategy { /// an app URI. final String? Function(String appUri) _serverPathForAppUri; - /// Returns the relative path in google3, determined by the [absolutePath]. + /// Returns the relative path in google3, determined by the absolutePath. /// /// Returns `null` if not a google3 app. final String? Function(String absolutePath) _g3RelativePath; diff --git a/dwds/lib/src/loaders/ddc_library_bundle.dart b/dwds/lib/src/loaders/ddc_library_bundle.dart index 58a0fc949..347c74986 100644 --- a/dwds/lib/src/loaders/ddc_library_bundle.dart +++ b/dwds/lib/src/loaders/ddc_library_bundle.dart @@ -4,14 +4,15 @@ import 'dart:convert'; -import 'package:dwds/src/debugging/dart_runtime_debugger.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/loaders/ddc.dart'; -import 'package:dwds/src/loaders/strategy.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; import 'package:shelf/shelf.dart'; +import '../debugging/dart_runtime_debugger.dart'; +import '../debugging/metadata/provider.dart'; +import '../readers/asset_reader.dart'; +import '../services/expression_compiler.dart'; +import 'ddc.dart'; +import 'strategy.dart'; + // TODO(srujzs): This is mostly a copy of `DdcStrategy`. Some of the // functionality in here may not make sense with the library bundle format yet. class DdcLibraryBundleStrategy extends LoadStrategy { @@ -97,7 +98,7 @@ class DdcLibraryBundleStrategy extends LoadStrategy { /// an app URI. final String? Function(String appUri) _serverPathForAppUri; - /// Returns the relative path in google3, determined by the [absolutePath]. + /// Returns the relative path in google3, determined by the absolutePath. /// /// Returns `null` if not a google3 app. final String? Function(String absolutePath) _g3RelativePath; diff --git a/dwds/lib/src/loaders/frontend_server_strategy_provider.dart b/dwds/lib/src/loaders/frontend_server_strategy_provider.dart index d9e242dd3..fab3a996a 100644 --- a/dwds/lib/src/loaders/frontend_server_strategy_provider.dart +++ b/dwds/lib/src/loaders/frontend_server_strategy_provider.dart @@ -2,15 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/loaders/ddc.dart'; -import 'package:dwds/src/loaders/ddc_library_bundle.dart'; -import 'package:dwds/src/loaders/require.dart'; -import 'package:dwds/src/loaders/strategy.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; import 'package:path/path.dart' as p; +import '../debugging/metadata/provider.dart'; +import '../readers/asset_reader.dart'; +import '../services/expression_compiler.dart'; +import 'ddc.dart'; +import 'ddc_library_bundle.dart'; +import 'require.dart'; +import 'strategy.dart'; + abstract class FrontendServerStrategyProvider { final ReloadConfiguration _configuration; final AssetReader _assetReader; diff --git a/dwds/lib/src/loaders/require.dart b/dwds/lib/src/loaders/require.dart index a6e9aa778..b26fa0795 100644 --- a/dwds/lib/src/loaders/require.dart +++ b/dwds/lib/src/loaders/require.dart @@ -4,14 +4,15 @@ import 'dart:convert'; -import 'package:dwds/src/debugging/dart_runtime_debugger.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/loaders/strategy.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; import 'package:path/path.dart' as p; import 'package:shelf/shelf.dart'; +import '../debugging/dart_runtime_debugger.dart'; +import '../debugging/metadata/provider.dart'; +import '../readers/asset_reader.dart'; +import '../services/expression_compiler.dart'; +import 'strategy.dart'; + String removeJsExtension(String path) => path.endsWith('.js') ? p.withoutExtension(path) : path; diff --git a/dwds/lib/src/loaders/strategy.dart b/dwds/lib/src/loaders/strategy.dart index e38cea083..846096a5e 100644 --- a/dwds/lib/src/loaders/strategy.dart +++ b/dwds/lib/src/loaders/strategy.dart @@ -5,14 +5,15 @@ import 'dart:io'; import 'dart:typed_data'; -import 'package:dwds/src/debugging/dart_runtime_debugger.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; -import 'package:dwds/src/utilities/dart_uri.dart'; import 'package:path/path.dart' as p; import 'package:shelf/shelf.dart'; +import '../debugging/dart_runtime_debugger.dart'; +import '../debugging/metadata/provider.dart'; +import '../readers/asset_reader.dart'; +import '../services/expression_compiler.dart'; +import '../utilities/dart_uri.dart'; + abstract class LoadStrategy { final AssetReader _assetReader; final String? _packageConfigPath; @@ -79,8 +80,9 @@ abstract class LoadStrategy { String get _defaultPackageConfigPath => p.join(DartUri.currentDirectory, '.dart_tool', 'package_config.json'); - /// Returns the absolute file path of the `package_config.json` file in the `.dart_tool` - /// directory, searching recursively from the current directory hierarchy. + /// Returns the absolute file path of the `package_config.json` file in the + /// `.dart_tool` directory, searching recursively from the current directory + /// hierarchy. static String? _findPackageConfigFilePath() { var candidateDir = Directory(DartUri.currentDirectory).absolute; diff --git a/dwds/lib/src/readers/frontend_server_asset_reader.dart b/dwds/lib/src/readers/frontend_server_asset_reader.dart index 2f705f421..dbef15ad0 100644 --- a/dwds/lib/src/readers/frontend_server_asset_reader.dart +++ b/dwds/lib/src/readers/frontend_server_asset_reader.dart @@ -5,11 +5,12 @@ import 'dart:convert'; import 'dart:io'; -import 'package:dwds/src/readers/asset_reader.dart'; import 'package:logging/logging.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as p; +import 'asset_reader.dart'; + /// A reader for Dart sources and related source maps provided by the Frontend /// Server. class FrontendServerAssetReader implements AssetReader { @@ -110,13 +111,12 @@ class FrontendServerAssetReader implements AssetReader { } final sourceContents = map.readAsBytesSync(); final sourceInfo = - jsonDecode(json.readAsStringSync()) as Map; + jsonDecode(json.readAsStringSync()) as Map; for (final key in sourceInfo.keys) { - final info = sourceInfo[key]; + final info = sourceInfo[key] as Map; + final sourceMap = info['sourcemap'] as List; _mapContents[key] = utf8.decode( - sourceContents - .getRange(info['sourcemap'][0] as int, info['sourcemap'][1] as int) - .toList(), + sourceContents.getRange(sourceMap[0], sourceMap[1]).toList(), ); } } diff --git a/dwds/lib/src/readers/proxy_server_asset_reader.dart b/dwds/lib/src/readers/proxy_server_asset_reader.dart index 7ef30d89c..354989ea1 100644 --- a/dwds/lib/src/readers/proxy_server_asset_reader.dart +++ b/dwds/lib/src/readers/proxy_server_asset_reader.dart @@ -5,13 +5,14 @@ import 'dart:convert'; import 'dart:io'; -import 'package:dwds/src/readers/asset_reader.dart'; import 'package:http/http.dart' as http; import 'package:http/io_client.dart'; import 'package:logging/logging.dart'; import 'package:shelf/shelf.dart'; import 'package:shelf_proxy/shelf_proxy.dart'; +import 'asset_reader.dart'; + /// A reader for resources provided by a proxy server. class ProxyServerAssetReader implements AssetReader { final _logger = Logger('ProxyServerAssetReader'); diff --git a/dwds/lib/src/servers/extension_backend.dart b/dwds/lib/src/servers/extension_backend.dart index 80152c5cf..320bd2b81 100644 --- a/dwds/lib/src/servers/extension_backend.dart +++ b/dwds/lib/src/servers/extension_backend.dart @@ -5,14 +5,15 @@ import 'dart:io'; import 'package:async/async.dart'; -import 'package:dwds/data/extension_request.dart'; -import 'package:dwds/src/events.dart'; -import 'package:dwds/src/handlers/socket_connections.dart'; -import 'package:dwds/src/servers/extension_debugger.dart'; -import 'package:dwds/src/utilities/server.dart'; import 'package:logging/logging.dart'; import 'package:shelf/shelf.dart'; +import '../../data/extension_request.dart'; +import '../events.dart'; +import '../handlers/socket_connections.dart'; +import '../utilities/server.dart'; +import 'extension_debugger.dart'; + const authenticationResponse = 'Dart Debug Authentication Success!\n\n' 'You can close this tab and launch the Dart Debug Extension again.'; diff --git a/dwds/lib/src/servers/extension_debugger.dart b/dwds/lib/src/servers/extension_debugger.dart index 3c8d24230..6a139fe24 100644 --- a/dwds/lib/src/servers/extension_debugger.dart +++ b/dwds/lib/src/servers/extension_debugger.dart @@ -6,17 +6,18 @@ import 'dart:async'; import 'dart:collection'; import 'dart:convert'; -import 'package:dwds/data/devtools_request.dart'; -import 'package:dwds/data/extension_request.dart'; -import 'package:dwds/data/serializers.dart'; -import 'package:dwds/src/debugging/execution_context.dart'; -import 'package:dwds/src/debugging/remote_debugger.dart'; -import 'package:dwds/src/handlers/socket_connections.dart'; -import 'package:dwds/src/services/chrome/chrome_debug_exception.dart'; import 'package:logging/logging.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart' hide StackTrace; +import '../../data/devtools_request.dart'; +import '../../data/extension_request.dart'; +import '../../data/serializers.dart'; +import '../debugging/execution_context.dart'; +import '../debugging/remote_debugger.dart'; +import '../handlers/socket_connections.dart'; +import '../services/chrome/chrome_debug_exception.dart'; + final _logger = Logger('ExtensionDebugger'); /// A remote debugger backed by the Dart Debug Extension with an SSE connection. @@ -91,10 +92,10 @@ class ExtensionDebugger implements RemoteDebugger { 'params': json.decode(message.params), }; // Note: package:sse will try to keep the connection alive, even after - // the client has been closed. Therefore the extension sends an event to - // notify DWDS that we should close the connection, instead of relying - // on the done event sent when the client is closed. See details: - // https://github.com/dart-lang/webdev/pull/1595#issuecomment-1116773378 + // the client has been closed. Therefore the extension sends an event + // to notify DWDS that we should close the connection, instead of + // relying on the done event sent when the client is closed. See + // details: https://github.com/dart-lang/webdev/pull/1595#issuecomment-1116773378 if (map['method'] == 'DebugExtension.detached') { close(); } else { @@ -156,7 +157,7 @@ class ExtensionDebugger implements RemoteDebugger { @override Future sendCommand( String command, { - Map? params, + Map? params, }) { final completer = Completer(); final id = newId(); @@ -174,6 +175,7 @@ class ExtensionDebugger implements RemoteDebugger { ), ), ); + // ignore: avoid_catching_errors } on StateError catch (error, stackTrace) { if (error.message.contains('Cannot add event after closing')) { _logger.severe('Socket connection closed. Shutting down debugger.'); @@ -206,7 +208,8 @@ class ExtensionDebugger implements RemoteDebugger { void closeWithError(Object? error) { _logger.shout( - 'Closing extension debugger due to error. Restart app for debugging functionality', + 'Closing extension debugger due to error. Restart app for debugging ' + 'functionality', error, ); close(); @@ -247,14 +250,14 @@ class ExtensionDebugger implements RemoteDebugger { } @override - Future stepInto({Map? params}) => + Future stepInto({Map? params}) => sendCommand('Debugger.stepInto', params: params); @override Future stepOut() => sendCommand('Debugger.stepOut'); @override - Future stepOver({Map? params}) => + Future stepOver({Map? params}) => sendCommand('Debugger.stepOver', params: params); @override @@ -269,7 +272,7 @@ class ExtensionDebugger implements RemoteDebugger { bool? returnByValue, int? contextId, }) async { - final params = {'expression': expression}; + final params = {'expression': expression}; if (returnByValue != null) { params['returnByValue'] = returnByValue; } @@ -278,7 +281,7 @@ class ExtensionDebugger implements RemoteDebugger { } final response = await sendCommand('Runtime.evaluate', params: params); final result = _validateResult(response.result); - return RemoteObject(result['result'] as Map); + return RemoteObject(result['result'] as Map); } @override @@ -286,7 +289,7 @@ class ExtensionDebugger implements RemoteDebugger { String callFrameId, String expression, ) async { - final params = { + final params = { 'callFrameId': callFrameId, 'expression': expression, }; @@ -295,14 +298,14 @@ class ExtensionDebugger implements RemoteDebugger { params: params, ); final result = _validateResult(response.result); - return RemoteObject(result['result'] as Map); + return RemoteObject(result['result'] as Map); } @override Future> getPossibleBreakpoints( WipLocation start, ) async { - final params = {'start': start.toJsonMap()}; + final params = {'start': start.toJsonMap()}; final response = await sendCommand( 'Debugger.getPossibleBreakpoints', params: params, @@ -310,7 +313,7 @@ class ExtensionDebugger implements RemoteDebugger { final result = _validateResult(response.result); final locations = result['locations'] as List; return List.from( - locations.map((map) => WipBreakLocation(map as Map)), + locations.map((map) => WipBreakLocation(map as Map)), ); } @@ -370,13 +373,13 @@ class ExtensionDebugger implements RemoteDebugger { } } - Map _validateResult(Map? result) { + Map _validateResult(Map? result) { if (result == null) { throw ChromeDebugException({'text': 'null result from Chrome Devtools'}); } if (result.containsKey('exceptionDetails')) { throw ChromeDebugException( - result['exceptionDetails'] as Map, + result['exceptionDetails'] as Map, ); } return result; diff --git a/dwds/lib/src/services/app_debug_services.dart b/dwds/lib/src/services/app_debug_services.dart index dd2f1ab42..9389c5bfd 100644 --- a/dwds/lib/src/services/app_debug_services.dart +++ b/dwds/lib/src/services/app_debug_services.dart @@ -3,10 +3,10 @@ // BSD-style license that can be found in the LICENSE file. import 'package:dds/dds_launcher.dart'; -import 'package:dwds/src/dwds_vm_client.dart'; -import 'package:dwds/src/events.dart'; -import 'package:dwds/src/services/debug_service.dart'; -import 'package:dwds/src/services/proxy_service.dart'; +import '../dwds_vm_client.dart'; +import '../events.dart'; +import 'debug_service.dart'; +import 'proxy_service.dart'; /// Common interface for debug service containers. class AppDebugServices< diff --git a/dwds/lib/src/services/batched_expression_evaluator.dart b/dwds/lib/src/services/batched_expression_evaluator.dart index fbdf9ef5f..087a0d234 100644 --- a/dwds/lib/src/services/batched_expression_evaluator.dart +++ b/dwds/lib/src/services/batched_expression_evaluator.dart @@ -5,17 +5,18 @@ import 'dart:async'; import 'package:collection/collection.dart'; -import 'package:dwds/shared/batched_stream.dart'; -import 'package:dwds/src/debugging/chrome_inspector.dart'; -import 'package:dwds/src/debugging/debugger.dart'; -import 'package:dwds/src/debugging/location.dart'; -import 'package:dwds/src/debugging/modules.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; -import 'package:dwds/src/services/expression_evaluator.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:logging/logging.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../../shared/batched_stream.dart'; +import '../debugging/chrome_inspector.dart'; +import '../debugging/debugger.dart'; +import '../debugging/location.dart'; +import '../debugging/modules.dart'; +import '../utilities/shared.dart'; +import 'expression_compiler.dart'; +import 'expression_evaluator.dart'; + class EvaluateRequest { final String isolateId; final String? libraryUri; @@ -84,7 +85,7 @@ class BatchedExpressionEvaluator extends ExpressionEvaluator { if (libraryUri != request.libraryUri || isolateId != request.isolateId || - !MapEquality().equals(scope, request.scope)) { + !const MapEquality().equals(scope, request.scope)) { _logger.fine('New batch due to'); if (libraryUri != request.libraryUri) { _logger.fine(' - library uri: $libraryUri != ${request.libraryUri}'); @@ -92,7 +93,7 @@ class BatchedExpressionEvaluator extends ExpressionEvaluator { if (isolateId != request.isolateId) { _logger.fine(' - isolateId: $isolateId != ${request.isolateId}'); } - if (!MapEquality().equals(scope, request.scope)) { + if (!const MapEquality().equals(scope, request.scope)) { _logger.fine(' - scope: $scope != ${request.scope}'); } @@ -159,7 +160,7 @@ class BatchedExpressionEvaluator extends ExpressionEvaluator { request.completer.complete(result); }), onError: (error, stackTrace) => - request.completer.completeError(error, stackTrace), + request.completer.completeError(error!, stackTrace), ); } } diff --git a/dwds/lib/src/services/chrome/chrome_debug_exception.dart b/dwds/lib/src/services/chrome/chrome_debug_exception.dart index 3a33022cc..3a2daeedd 100644 --- a/dwds/lib/src/services/chrome/chrome_debug_exception.dart +++ b/dwds/lib/src/services/chrome/chrome_debug_exception.dart @@ -16,11 +16,11 @@ final class ChromeDebugException extends ExceptionDetails implements Exception { late final StackTrace? stackTrace; ChromeDebugException( - Map exceptionDetails, { + Map exceptionDetails, { this.additionalDetails, this.evalContents, }) : super(exceptionDetails) { - final json = exceptionDetails['stackTrace']; + final json = exceptionDetails['stackTrace'] as Map?; stackTrace = json == null ? null : StackTrace(json); } diff --git a/dwds/lib/src/services/chrome/chrome_debug_service.dart b/dwds/lib/src/services/chrome/chrome_debug_service.dart index 6fa2731dd..db0d79120 100644 --- a/dwds/lib/src/services/chrome/chrome_debug_service.dart +++ b/dwds/lib/src/services/chrome/chrome_debug_service.dart @@ -2,19 +2,20 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/asset_reader.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/debugging/execution_context.dart'; -import 'package:dwds/src/debugging/remote_debugger.dart'; -import 'package:dwds/src/services/chrome/chrome_proxy_service.dart'; -import 'package:dwds/src/services/debug_service.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:meta/meta.dart'; import 'package:shelf/shelf.dart' as shelf; import 'package:sse/server/sse_handler.dart'; +import '../../../asset_reader.dart'; +import '../../config/tool_configuration.dart'; +import '../../connections/app_connection.dart'; +import '../../debugging/execution_context.dart'; +import '../../debugging/remote_debugger.dart'; +import '../../utilities/shared.dart'; +import '../debug_service.dart'; +import '../expression_compiler.dart'; +import 'chrome_proxy_service.dart'; + /// A Dart Web Debug Service. /// /// Creates a [ChromeProxyService] from an existing Chrome instance. diff --git a/dwds/lib/src/services/chrome/chrome_proxy_service.dart b/dwds/lib/src/services/chrome/chrome_proxy_service.dart index e5745e606..fd1cf94bb 100644 --- a/dwds/lib/src/services/chrome/chrome_proxy_service.dart +++ b/dwds/lib/src/services/chrome/chrome_proxy_service.dart @@ -6,32 +6,34 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; -import 'package:dwds/data/debug_event.dart'; -import 'package:dwds/data/register_event.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/debugging/chrome_inspector.dart'; -import 'package:dwds/src/debugging/debugger.dart'; -import 'package:dwds/src/debugging/execution_context.dart'; -import 'package:dwds/src/debugging/instance.dart'; -import 'package:dwds/src/debugging/location.dart'; -import 'package:dwds/src/debugging/metadata/provider.dart'; -import 'package:dwds/src/debugging/modules.dart'; -import 'package:dwds/src/debugging/remote_debugger.dart'; -import 'package:dwds/src/debugging/skip_list.dart'; -import 'package:dwds/src/events.dart'; -import 'package:dwds/src/readers/asset_reader.dart'; -import 'package:dwds/src/services/batched_expression_evaluator.dart'; -import 'package:dwds/src/services/chrome/chrome_debug_service.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; -import 'package:dwds/src/services/expression_evaluator.dart'; -import 'package:dwds/src/services/proxy_service.dart'; -import 'package:dwds/src/utilities/dart_uri.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:logging/logging.dart' hide LogRecord; import 'package:vm_service/vm_service.dart' hide vmServiceVersion; import 'package:vm_service_interface/vm_service_interface.dart'; -import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart' + hide StackTrace; + +import '../../../data/debug_event.dart'; +import '../../../data/register_event.dart'; +import '../../config/tool_configuration.dart'; +import '../../connections/app_connection.dart'; +import '../../debugging/chrome_inspector.dart'; +import '../../debugging/debugger.dart'; +import '../../debugging/execution_context.dart'; +import '../../debugging/instance.dart'; +import '../../debugging/location.dart'; +import '../../debugging/metadata/provider.dart'; +import '../../debugging/modules.dart'; +import '../../debugging/remote_debugger.dart'; +import '../../debugging/skip_list.dart'; +import '../../events.dart'; +import '../../readers/asset_reader.dart'; +import '../../utilities/dart_uri.dart'; +import '../../utilities/shared.dart'; +import '../batched_expression_evaluator.dart'; +import '../expression_compiler.dart'; +import '../expression_evaluator.dart'; +import '../proxy_service.dart'; +import 'chrome_debug_service.dart'; /// A proxy from the chrome debug protocol to the dart vm service protocol. final class ChromeProxyService extends ProxyService { @@ -372,7 +374,7 @@ final class ChromeProxyService extends ProxyService { /// Should be called when there is a hot restart or full page refresh. /// - /// Clears out the [_inspector] and all related cached information. + /// Clears out the [inspector] and all related cached information. @override void destroyIsolate() { _logger.fine('Destroying isolate'); @@ -522,7 +524,7 @@ final class ChromeProxyService extends ProxyService { .invokeExtensionJsExpression(method, jsonEncode(stringArgs)); final result = await inspector.jsEvaluate(expression, awaitPromise: true); final decodedResponse = - jsonDecode(result.value as String) as Map; + jsonDecode(result.value as String) as Map; if (decodedResponse.containsKey('code') && decodedResponse.containsKey('message') && decodedResponse.containsKey('data')) { @@ -530,7 +532,6 @@ final class ChromeProxyService extends ProxyService { throw RPCError( method, decodedResponse['code'] as int, - // ignore: avoid-unnecessary-type-casts decodedResponse['message'] as String, decodedResponse['data'] as Map, ); @@ -1254,7 +1255,7 @@ final class ChromeProxyService extends ProxyService { break; case 'dart.developer.log': await _handleDeveloperLog(isolateRef, event).catchError( - (error, stackTrace) => _logger.warning( + (Object error, StackTrace stackTrace) => _logger.warning( 'Error handling developer log:', error, stackTrace, @@ -1271,8 +1272,9 @@ final class ChromeProxyService extends ProxyService { IsolateRef isolateRef, ConsoleAPIEvent event, ) async { - final logObject = event.params?['args'][1] as Map?; - final objectId = logObject?['objectId']; + final logObject = + (event.params?['args'] as List>?>)[1]; + final objectId = logObject?['objectId'] as String?; // Always attempt to fetch the full properties instead of relying on // `RemoteObject.preview` which only has truncated log messages: // https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#type-RemoteObject @@ -1309,7 +1311,7 @@ final class ChromeProxyService extends ProxyService { Future> _fetchFullLogParams( String objectId, { - required Map? logObject, + required Map>? logObject, }) async { final logParams = {}; for (final property in await inspector.getProperties(objectId)) { @@ -1328,10 +1330,14 @@ final class ChromeProxyService extends ProxyService { return logParams; } - Map _fetchAbbreviatedLogParams(Map? logObject) { + Map _fetchAbbreviatedLogParams( + Map>? logObject, + ) { final logParams = {}; - for (final dynamic property in logObject?['preview']?['properties'] ?? []) { - if (property is Map && property['name'] != null) { + for (final property + in logObject?['preview']?['properties'] as List? ?? + []) { + if (property is Map && property['name'] != null) { logParams[property['name'] as String] = RemoteObject(property); } } @@ -1352,7 +1358,7 @@ class _ReloadReportWithMetadata extends ReloadReport { _ReloadReportWithMetadata({super.success}); @override - Map toJson() { + Map toJson() { final jsonified = { 'type': type, 'success': success ?? false, diff --git a/dwds/lib/src/services/debug_service.dart b/dwds/lib/src/services/debug_service.dart index 787a277a0..27ac3aaa5 100644 --- a/dwds/lib/src/services/debug_service.dart +++ b/dwds/lib/src/services/debug_service.dart @@ -9,10 +9,6 @@ import 'dart:math'; import 'dart:typed_data'; import 'package:dds/dds_launcher.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/events.dart'; -import 'package:dwds/src/services/proxy_service.dart'; -import 'package:dwds/src/utilities/server.dart'; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; import 'package:shelf/shelf.dart' as shelf; @@ -20,6 +16,12 @@ import 'package:shelf_web_socket/shelf_web_socket.dart'; import 'package:stream_channel/stream_channel.dart'; import 'package:vm_service/vm_service.dart'; import 'package:vm_service_interface/vm_service_interface.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +import '../config/tool_configuration.dart'; +import '../events.dart'; +import '../utilities/server.dart'; +import 'proxy_service.dart'; bool _acceptNewConnections = true; @@ -37,7 +39,8 @@ abstract class DebugService { required this.useSse, }); - /// The URI pointing to the VM service implementation hosted by the [DebugService]. + /// The URI pointing to the VM service implementation hosted by the + /// [DebugService]. String get uri => _uri.toString(); Uri get _uri => _cachedUri ??= () { @@ -163,9 +166,9 @@ abstract class DebugService { void Function(Map)? onResponse, }) { return _wrapHandler( - webSocketHandler((webSocket, subprotocol) { + webSocketHandler((WebSocketChannel webSocket, subprotocol) { handleConnection( - webSocket, + webSocket.cast(), proxyService, serviceExtensionRegistry, onRequest: onRequest, @@ -181,7 +184,8 @@ abstract class DebugService { if (!_acceptNewConnections) { return shelf.Response.forbidden( 'Cannot connect directly to the VM service as a Dart Development ' - 'Service (DDS) instance has taken control and can be found at $_ddsUri.' + 'Service (DDS) instance has taken control and can be found at ' + '$_ddsUri.' '$_ddsUri.', ); } @@ -195,7 +199,7 @@ abstract class DebugService { @protected @mustCallSuper void handleConnection( - StreamChannel channel, + StreamChannel channel, ProxyService proxyService, ServiceExtensionRegistry serviceExtensionRegistry, { void Function(Map)? onRequest, @@ -210,8 +214,8 @@ abstract class DebugService { // while also being able to determine which client invoked the RPC // without some form of client ID. // - // We can probably do better than this, but it will likely involve some - // refactoring. + // We can probably do better than this, but it will likely involve + // some refactoring. if (response case { 'error': { 'code': DisconnectNonDartDevelopmentServiceClients.kErrorCode, @@ -240,7 +244,9 @@ abstract class DebugService { 'socket, expected a List or String.', ); } - final request = Map.from(jsonDecode(value)); + final request = Map.from( + jsonDecode(value as String) as Map, + ); if (onRequest != null) onRequest(request); return request; }); diff --git a/dwds/lib/src/services/expression_compiler_service.dart b/dwds/lib/src/services/expression_compiler_service.dart index 85d6a0e75..72173701e 100644 --- a/dwds/lib/src/services/expression_compiler_service.dart +++ b/dwds/lib/src/services/expression_compiler_service.dart @@ -6,13 +6,14 @@ import 'dart:async'; import 'dart:isolate'; import 'package:async/async.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; -import 'package:dwds/src/utilities/sdk_configuration.dart'; import 'package:logging/logging.dart'; +import '../utilities/sdk_configuration.dart'; +import 'expression_compiler.dart'; + class _Compiler { static final _logger = Logger('ExpressionCompilerService'); - final StreamQueue _responseQueue; + final StreamQueue _responseQueue; final ReceivePort _receivePort; final SendPort _sendPort; @@ -22,7 +23,7 @@ class _Compiler { /// Sends [request] on [_sendPort] and returns the next event from the /// response stream. - Future> _send(Map request) async { + Future> _send(Map request) async { _sendPort.send(request); if (!await _responseQueue.hasNext) { return { @@ -31,7 +32,7 @@ class _Compiler { }; } final response = await _responseQueue.next; - if (response is! Map) { + if (response is! Map) { return { 'succeeded': false, 'errors': ['compilation worker returned invalid response: $response'], @@ -107,7 +108,7 @@ class _Compiler { } Future updateDependencies(Map modules) async { - final updateCompleter = Completer(); + final updateCompleter = Completer(); _dependencyUpdate = updateCompleter.future; _logger.info('Updating dependencies...'); @@ -189,7 +190,7 @@ class _Compiler { return ExpressionCompilationResult(result, !succeeded); } - String _createErrorMsg(Map response) { + String _createErrorMsg(Map response) { final errors = response['errors'] as List?; if (errors != null && errors.isNotEmpty) return errors.first; @@ -219,7 +220,7 @@ class _Compiler { /// Uses [_address] and [_port] to communicate and to redirect asset /// requests to the asset server. /// -/// Configuration created by [_sdkConfigurationProvider] describes the +/// Configuration created by [sdkConfigurationProvider] describes the /// locations of SDK files used in expression compilation (summaries, /// libraries spec, compiler worker snapshot). /// diff --git a/dwds/lib/src/services/expression_evaluator.dart b/dwds/lib/src/services/expression_evaluator.dart index b8cb71c37..3499c7ba4 100644 --- a/dwds/lib/src/services/expression_evaluator.dart +++ b/dwds/lib/src/services/expression_evaluator.dart @@ -2,19 +2,20 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/debugging/chrome_inspector.dart'; -import 'package:dwds/src/debugging/dart_scope.dart'; -import 'package:dwds/src/debugging/debugger.dart'; -import 'package:dwds/src/debugging/location.dart'; -import 'package:dwds/src/debugging/modules.dart'; -import 'package:dwds/src/services/expression_compiler.dart'; -import 'package:dwds/src/services/javascript_builder.dart'; -import 'package:dwds/src/utilities/conversions.dart'; -import 'package:dwds/src/utilities/objects.dart' as chrome; import 'package:logging/logging.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; +import '../config/tool_configuration.dart'; +import '../debugging/chrome_inspector.dart'; +import '../debugging/dart_scope.dart'; +import '../debugging/debugger.dart'; +import '../debugging/location.dart'; +import '../debugging/modules.dart'; +import '../utilities/conversions.dart'; +import '../utilities/objects.dart' as chrome; +import 'expression_compiler.dart'; +import 'javascript_builder.dart'; + class EvaluationErrorKind { EvaluationErrorKind._(); @@ -46,7 +47,8 @@ class ExpressionEvaluator { 'org-dartlang-debug:synthetic_debug_expression:.*:.*Error: ', ); - /// Find module path from the XHR call network error message received from chrome. + /// Find module path from the XHR call network error message received from + /// Chrome. /// /// Example: /// NetworkError: Failed to load `http://.com/path/to/module.js?` diff --git a/dwds/lib/src/services/proxy_service.dart b/dwds/lib/src/services/proxy_service.dart index 5e551a3ed..b6227dd46 100644 --- a/dwds/lib/src/services/proxy_service.dart +++ b/dwds/lib/src/services/proxy_service.dart @@ -5,23 +5,24 @@ import 'dart:async'; import 'dart:convert'; -import 'package:dwds/data/debug_event.dart'; -import 'package:dwds/data/hot_reload_response.dart'; -import 'package:dwds/data/hot_restart_response.dart'; -import 'package:dwds/data/register_event.dart'; -import 'package:dwds/data/service_extension_response.dart'; -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/debugging/inspector.dart'; -import 'package:dwds/src/events.dart'; -import 'package:dwds/src/services/debug_service.dart'; -import 'package:dwds/src/utilities/dart_uri.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:meta/meta.dart'; import 'package:pub_semver/pub_semver.dart' as semver; import 'package:vm_service/vm_service.dart' as vm_service; import 'package:vm_service/vm_service.dart'; import 'package:vm_service_interface/vm_service_interface.dart'; +import '../../data/debug_event.dart'; +import '../../data/hot_reload_response.dart'; +import '../../data/hot_restart_response.dart'; +import '../../data/register_event.dart'; +import '../../data/service_extension_response.dart'; +import '../connections/app_connection.dart'; +import '../debugging/inspector.dart'; +import '../events.dart'; +import '../utilities/dart_uri.dart'; +import '../utilities/shared.dart'; +import 'debug_service.dart'; + // This event is identical to the one sent by the VM service from // sdk/lib/vmservice/vmservice.dart before existing VM service clients are // disconnected. @@ -31,8 +32,8 @@ final class DartDevelopmentServiceConnectedEvent extends Event { required this.uri, }) : message = 'A Dart Developer Service instance has connected and this direct ' - 'connection to the VM service will now be closed. Please reconnect to ' - 'the Dart Development Service at $uri.', + 'connection to the VM service will now be closed. Please reconnect ' + 'to the Dart Development Service at $uri.', super(kind: 'DartDevelopmentServiceConnected'); final String message; @@ -373,7 +374,7 @@ abstract base class ProxyService ) ..extensionKind = debugEvent.kind ..extensionData = ExtensionData.parse( - jsonDecode(debugEvent.eventData) as Map, + jsonDecode(debugEvent.eventData) as Map, ), ); } @@ -662,7 +663,7 @@ abstract base class ProxyService /// Prevent DWDS from blocking Dart SDK rolls if changes in package:vm_service /// are unimplemented in DWDS. @override - dynamic noSuchMethod(Invocation invocation) { + Object? noSuchMethod(Invocation invocation) { return super.noSuchMethod(invocation); } } diff --git a/dwds/lib/src/services/web_socket/web_socket_debug_service.dart b/dwds/lib/src/services/web_socket/web_socket_debug_service.dart index 36ab4da3d..0a8808f11 100644 --- a/dwds/lib/src/services/web_socket/web_socket_debug_service.dart +++ b/dwds/lib/src/services/web_socket/web_socket_debug_service.dart @@ -2,13 +2,14 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/asset_reader.dart'; -import 'package:dwds/src/config/tool_configuration.dart'; -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/services/debug_service.dart'; -import 'package:dwds/src/services/web_socket/web_socket_proxy_service.dart'; import 'package:meta/meta.dart'; +import '../../../asset_reader.dart'; +import '../../config/tool_configuration.dart'; +import '../../connections/app_connection.dart'; +import '../debug_service.dart'; +import 'web_socket_proxy_service.dart'; + /// Defines callbacks for sending messages to the connected client. /// Returns the number of clients the request was successfully sent to. typedef SendClientRequest = int Function(Object request); diff --git a/dwds/lib/src/services/web_socket/web_socket_proxy_service.dart b/dwds/lib/src/services/web_socket/web_socket_proxy_service.dart index 32b7ce1d0..4acd9d137 100644 --- a/dwds/lib/src/services/web_socket/web_socket_proxy_service.dart +++ b/dwds/lib/src/services/web_socket/web_socket_proxy_service.dart @@ -5,21 +5,22 @@ import 'dart:async'; import 'dart:convert'; -import 'package:dwds/data/hot_reload_request.dart'; -import 'package:dwds/data/hot_reload_response.dart'; -import 'package:dwds/data/hot_restart_request.dart'; -import 'package:dwds/data/hot_restart_response.dart'; -import 'package:dwds/data/service_extension_request.dart'; -import 'package:dwds/data/service_extension_response.dart'; -import 'package:dwds/src/connections/app_connection.dart'; -import 'package:dwds/src/debugging/web_socket_inspector.dart'; -import 'package:dwds/src/services/proxy_service.dart'; -import 'package:dwds/src/services/web_socket/web_socket_debug_service.dart'; -import 'package:dwds/src/utilities/shared.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart' as vm_service; import 'package:vm_service/vm_service.dart'; +import '../../../data/hot_reload_request.dart'; +import '../../../data/hot_reload_response.dart'; +import '../../../data/hot_restart_request.dart'; +import '../../../data/hot_restart_response.dart'; +import '../../../data/service_extension_request.dart'; +import '../../../data/service_extension_response.dart'; +import '../../connections/app_connection.dart'; +import '../../debugging/web_socket_inspector.dart'; +import '../../utilities/shared.dart'; +import '../proxy_service.dart'; +import 'web_socket_debug_service.dart'; + /// Defines callbacks for sending messages to the connected client. /// Returns the number of clients the request was successfully sent to. typedef SendClientRequest = int Function(Object request); @@ -28,7 +29,8 @@ const _pauseIsolatesOnStartFlag = 'pause_isolates_on_start'; /// Grace period before destroying isolate when no clients are detected. /// This handles the race condition during page refresh where the old connection -/// closes before the new connection is established, preventing premature isolate destruction. +/// closes before the new connection is established, preventing premature +/// isolate destruction. const _isolateDestructionGracePeriod = Duration(seconds: 15); /// Error message when no clients are available for hot reload/restart. @@ -216,7 +218,8 @@ final class WebSocketProxyService extends ProxyService { ); } else { _logger.fine( - 'Reconnecting existing connection: $connectionId (total: $_activeConnectionCount)', + 'Reconnecting existing connection: $connectionId (total: ' + '$_activeConnectionCount)', ); } @@ -229,10 +232,12 @@ final class WebSocketProxyService extends ProxyService { _handleConnectionClosed(connectionId); }); - // If we already have a running isolate, just update the connection and return + // If we already have a running isolate, just update the connection and + // return if (isIsolateRunning) { _logger.fine( - 'Reusing existing isolate ${inspector.isolateRef.id} for connection: $connectionId', + 'Reusing existing isolate ${inspector.isolateRef.id} for connection: ' + '$connectionId', ); return; } @@ -293,16 +298,19 @@ final class WebSocketProxyService extends ProxyService { // Decrease active connection count _activeConnectionCount--; _logger.fine( - 'Removed connection: $connectionId (remaining: $_activeConnectionCount)', + 'Removed connection: $connectionId (remaining: ' + '$_activeConnectionCount)', ); _logger.fine( - 'Current tracked connections: ${_appConnectionDoneSubscriptions.keys.toList()}', + 'Current tracked connections: ' + '${_appConnectionDoneSubscriptions.keys.toList()}', ); // Instead of destroying the isolate immediately, check if there are still // clients that can receive hot reload requests if (_activeConnectionCount <= 0) { - // Double-check by asking the sendClientRequest callback how many clients are available + // Double-check by asking the sendClientRequest callback how many + // clients are available final actualClientCount = sendClientRequest({'type': 'ping'}); _logger.fine( 'Actual client count from sendClientRequest: $actualClientCount', @@ -310,9 +318,11 @@ final class WebSocketProxyService extends ProxyService { if (actualClientCount == 0) { _logger.fine( - 'No clients available for hot reload, scheduling isolate destruction', + 'No clients available for hot reload, scheduling isolate ' + 'destruction', ); - // Add a delay before destroying the isolate to handle page refresh race condition + // Add a delay before destroying the isolate to handle page refresh + // race condition Timer(_isolateDestructionGracePeriod, () { // Double-check client count again before destroying final finalClientCount = sendClientRequest({'type': 'ping'}); @@ -323,21 +333,24 @@ final class WebSocketProxyService extends ProxyService { destroyIsolate(); } else { _logger.fine( - 'Final check found $finalClientCount clients, keeping isolate alive', + 'Final check found $finalClientCount clients, keeping isolate ' + 'alive', ); _activeConnectionCount = finalClientCount; } }); } else { _logger.fine( - 'Still have $actualClientCount clients available, keeping isolate alive', + 'Still have $actualClientCount clients available, keeping isolate ' + 'alive', ); // Update our internal counter to match reality _activeConnectionCount = actualClientCount; } } else { _logger.fine( - 'Still have $_activeConnectionCount active connections, keeping isolate alive', + 'Still have $_activeConnectionCount active connections, keeping ' + 'isolate alive', ); } } else { @@ -409,8 +422,8 @@ final class WebSocketProxyService extends ProxyService { _logger.info('Hot reload completed successfully'); return _ReloadReportWithMetadata(success: true); } on NoClientsAvailableException catch (e) { - // Throw RPC error with kIsolateCannotReload code when no browser clients are - // connected. + // Throw RPC error with kIsolateCannotReload code when no browser clients + // are connected. throw vm_service.RPCError( 'reloadSources', vm_service.RPCErrorKind.kIsolateCannotReload.code, @@ -431,8 +444,8 @@ final class WebSocketProxyService extends ProxyService { _logger.info('Hot restart completed successfully'); return {'result': vm_service.Success().toJson()}; } on NoClientsAvailableException catch (e) { - // Throw RPC error with kIsolateCannotReload code when no browser clients are - // connected. + // Throw RPC error with kIsolateCannotReload code when no browser clients + // are connected. throw vm_service.RPCError( 'hotRestart', vm_service.RPCErrorKind.kIsolateCannotReload.code, @@ -456,7 +469,8 @@ final class WebSocketProxyService extends ProxyService { if (tracker == null) { _logger.warning( - 'Received hot reload response but no pending tracker found (id: ${response.id})', + 'Received hot reload response but no pending tracker found (id: ' + '${response.id})', ); return; } @@ -488,7 +502,8 @@ final class WebSocketProxyService extends ProxyService { if (tracker == null) { _logger.warning( - 'Received hot restart response but no pending tracker found (id: ${response.id})', + 'Received hot restart response but no pending tracker found (id: ' + '${response.id})', ); return; } @@ -879,7 +894,7 @@ class _ReloadReportWithMetadata extends vm_service.ReloadReport { _ReloadReportWithMetadata({super.success, this.notices}); @override - Map toJson() { + Map toJson() { final jsonified = { 'type': 'ReloadReport', 'success': success ?? false, diff --git a/dwds/lib/src/sockets.dart b/dwds/lib/src/sockets.dart index 016448f9f..055fd5c2b 100644 --- a/dwds/lib/src/sockets.dart +++ b/dwds/lib/src/sockets.dart @@ -8,7 +8,7 @@ import 'package:sse/client/sse_client.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; abstract class SocketClient { - StreamSink get sink; + StreamSink get sink; Stream get stream; void close(); } @@ -18,7 +18,7 @@ class SseSocketClient extends SocketClient { SseSocketClient(this._client); @override - StreamSink get sink => _client.sink; + StreamSink get sink => _client.sink; @override Stream get stream => _client.stream; @@ -33,9 +33,9 @@ class WebSocketClient extends SocketClient { WebSocketClient(this._channel); @override - StreamSink get sink => _channel.sink; + StreamSink get sink => _channel.sink; @override - Stream get stream => _channel.stream.map((dynamic o) => o.toString()); + Stream get stream => _channel.stream.map((Object? o) => o.toString()); @override void close() => _channel.sink.close(); diff --git a/dwds/lib/src/utilities/conversions.dart b/dwds/lib/src/utilities/conversions.dart index f965c0077..99eff9e98 100644 --- a/dwds/lib/src/utilities/conversions.dart +++ b/dwds/lib/src/utilities/conversions.dart @@ -100,7 +100,7 @@ String dartIdFor(Object? argument) { } return argument.objectId!; } - if (argument is Map) { + if (argument is Map) { final id = argument['objectId'] as String?; if (id == null) { throw ArgumentError.value(argument, 'objectId', 'No objectId found'); diff --git a/dwds/lib/src/utilities/dart_uri.dart b/dwds/lib/src/utilities/dart_uri.dart index c1698a1c8..5f81cfe3f 100644 --- a/dwds/lib/src/utilities/dart_uri.dart +++ b/dwds/lib/src/utilities/dart_uri.dart @@ -2,11 +2,12 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:dwds/src/config/tool_configuration.dart'; import 'package:logging/logging.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as p; +import '../config/tool_configuration.dart'; + /// The URI for a particular Dart file, able to canonicalize from various /// different representations. class DartUri { @@ -181,7 +182,8 @@ class DartUri { /// re-computing. static String get currentDirectoryUri => _currentDirectoryUri; - /// Record library and script uris to enable resolving library and script paths. + /// Record library and script uris to enable resolving library and script + /// paths. static Future initialize() async { clear(); await _loadPackageConfig( diff --git a/dwds/lib/src/utilities/objects.dart b/dwds/lib/src/utilities/objects.dart index 86680aec1..c498044b0 100644 --- a/dwds/lib/src/utilities/objects.dart +++ b/dwds/lib/src/utilities/objects.dart @@ -12,13 +12,13 @@ import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; /// Represents a property of an object. class Property { - final Map? _map; + final Map? _map; RemoteObject? _remoteObjectValue; Property(this._map); - Map? get map => _map; + Map? get map => _map; /// The remote object value in unwrapped form. /// @@ -36,7 +36,7 @@ class Property { if (val is RemoteObject) { _remoteObjectValue = val; } else { - _remoteObjectValue = RemoteObject(val as Map); + _remoteObjectValue = RemoteObject(val as Map); } return _remoteObjectValue; } diff --git a/dwds/lib/src/utilities/server.dart b/dwds/lib/src/utilities/server.dart index e67dfe355..72fe865d4 100644 --- a/dwds/lib/src/utilities/server.dart +++ b/dwds/lib/src/utilities/server.dart @@ -4,7 +4,6 @@ import 'dart:io'; -import 'package:dwds/src/services/chrome/chrome_debug_exception.dart'; import 'package:http_multi_server/http_multi_server.dart'; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart'; @@ -12,6 +11,8 @@ import 'package:stack_trace/stack_trace.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart' as wip; +import '../services/chrome/chrome_debug_exception.dart'; + /// Returns a port that is probably, but not definitely, not in use. /// /// This has a built-in race condition: another process may bind this port at @@ -71,28 +72,28 @@ void serveHttpRequests( }, onError: onError); } -/// Throws an [wip.ExceptionDetails] object if `exceptionDetails` is present on the -/// result. +/// Throws an [wip.ExceptionDetails] object if `exceptionDetails` is present on +/// the result. void handleErrorIfPresent(wip.WipResponse? response, {String? evalContents}) { final result = response?.result; if (result == null) return; if (result.containsKey('exceptionDetails')) { throw ChromeDebugException( - result['exceptionDetails'] as Map, + result['exceptionDetails'] as Map, evalContents: evalContents, ); } } /// Returns result contained in the response. -/// Throws an [wip.ExceptionDetails] object if `exceptionDetails` is present on the -/// result or the result is null. -Map getResultOrHandleError( +/// Throws an [wip.ExceptionDetails] object if `exceptionDetails` is present on +/// the result or the result is null. +Map getResultOrHandleError( wip.WipResponse? response, { String? evalContents, }) { handleErrorIfPresent(response, evalContents: evalContents); - final result = response?.result?['result']; + final result = response?.result?['result'] as Map?; if (result == null) { throw ChromeDebugException({ 'text': 'null result from Chrome Devtools', diff --git a/dwds/lib/src/utilities/shared.dart b/dwds/lib/src/utilities/shared.dart index 1a55bdaf6..c4e8f9716 100644 --- a/dwds/lib/src/utilities/shared.dart +++ b/dwds/lib/src/utilities/shared.dart @@ -19,7 +19,7 @@ final _logger = Logger('Utilities'); void safeUnawaited( Future future, { - void Function(dynamic, StackTrace)? onError, + void Function(Object?, StackTrace)? onError, }) { onError ??= (error, stackTrace) => _logger.warning('Error in unawaited Future:', error, stackTrace); @@ -35,7 +35,7 @@ Future wrapInErrorHandlerAsync( String command, Future Function() asyncCallback, ) { - return asyncCallback().catchError((error) { + return asyncCallback().catchError((Object error) { return Future.error( RPCError( command, diff --git a/dwds/pubspec.yaml b/dwds/pubspec.yaml index 4ef1378ca..62d9f9fae 100644 --- a/dwds/pubspec.yaml +++ b/dwds/pubspec.yaml @@ -31,14 +31,14 @@ dependencies: shelf_static: ^1.1.0 shelf_web_socket: ">=2.0.0 <4.0.0" source_maps: ^0.10.10 + sse: ^4.1.2 stack_trace: ^1.10.0 stream_channel: ^2.1.2 - sse: ^4.1.2 uuid: ^4.0.0 vm_service: ">=14.2.4 <16.0.0" vm_service_interface: ^2.0.1 - web_socket_channel: ">=2.2.0 <4.0.0" web: ^1.1.0 + web_socket_channel: ">=2.2.0 <4.0.0" webkit_inspection_protocol: ^1.0.1 dev_dependencies: @@ -51,9 +51,9 @@ dev_dependencies: build_version: ^2.1.1 build_web_compilers: ^4.4.1 built_value_generator: ^8.4.2 - graphs: ^2.1.0 frontend_server_common: path: ../frontend_server_common + graphs: ^2.1.0 io: ^1.0.5 js: ">=0.6.4 <0.8.0" pubspec_parse: ^1.2.0 diff --git a/dwds/test/build_daemon_callstack_test.dart b/dwds/test/build_daemon_callstack_test.dart index c93b58fc8..bc7d1a218 100644 --- a/dwds/test/build_daemon_callstack_test.dart +++ b/dwds/test/build_daemon_callstack_test.dart @@ -30,7 +30,7 @@ void main() { setUpAll(() async { setCurrentLogWriter(debug: debug); await context.setUp( - testSettings: TestSettings( + testSettings: const TestSettings( compilationMode: CompilationMode.buildDaemon, enableExpressionEvaluation: true, verboseCompiler: debug, diff --git a/dwds/test/common/chrome_proxy_service_common.dart b/dwds/test/common/chrome_proxy_service_common.dart index 0c403d48d..124530b5a 100644 --- a/dwds/test/common/chrome_proxy_service_common.dart +++ b/dwds/test/common/chrome_proxy_service_common.dart @@ -130,7 +130,7 @@ void runTests({ test('addBreakpoint in nonsense location throws', () async { expect( service.addBreakpoint(isolate.id!, mainScript.id!, 200000), - throwsA(predicate((dynamic e) => e is RPCError && e.code == 102)), + throwsA(predicate((Object? e) => e is RPCError && e.code == 102)), ); }); @@ -284,7 +284,7 @@ void runTests({ ), throwsA( predicate( - (dynamic error) => + (Object? error) => error is RPCError && error.code == -32001 && error.details == jsonEncode(errorDetails), @@ -305,7 +305,7 @@ void runTests({ service.callServiceExtension(serviceMethod), throwsA( predicate( - (dynamic error) => + (Object? error) => error is RPCError && error.code == RPCErrorKind.kMethodNotFound.code, ), @@ -743,11 +743,11 @@ void runTests({ expect(inst.count, null); expect(inst.associations!.length, 1001); final fifth = inst.associations![4]; - expect(fifth.key.valueAsString, '4'); - expect(fifth.value.valueAsString, '996'); + expect((fifth.key as InstanceRef).valueAsString, '4'); + expect((fifth.value as InstanceRef).valueAsString, '996'); final sixth = inst.associations![5]; - expect(sixth.key.valueAsString, '5'); - expect(sixth.value.valueAsString, '995'); + expect((sixth.key as InstanceRef).valueAsString, '5'); + expect((sixth.value as InstanceRef).valueAsString, '995'); }); test('bool', () async { @@ -995,11 +995,11 @@ void runTests({ expect(inst.count, null); expect(inst.associations!.length, 1001); final fifth = inst.associations![4]; - expect(fifth.key.valueAsString, '4'); - expect(fifth.value.valueAsString, '996'); + expect((fifth.key as InstanceRef).valueAsString, '4'); + expect((fifth.value as InstanceRef).valueAsString, '996'); final sixth = inst.associations![5]; - expect(sixth.key.valueAsString, '5'); - expect(sixth.value.valueAsString, '995'); + expect((sixth.key as InstanceRef).valueAsString, '5'); + expect((sixth.value as InstanceRef).valueAsString, '995'); }); test('Maps with null count and offset greater than 0 are ' @@ -1020,8 +1020,8 @@ void runTests({ expect(inst.count, null); expect(inst.associations!.length, 1); final only = inst.associations![0]; - expect(only.key.valueAsString, '1000'); - expect(only.value.valueAsString, '0'); + expect((only.key as InstanceRef).valueAsString, '1000'); + expect((only.value as InstanceRef).valueAsString, '0'); }); test('Maps with null count are not truncated', () async { @@ -1041,11 +1041,11 @@ void runTests({ expect(inst.count, null); expect(inst.associations!.length, 1001); final fifth = inst.associations![4]; - expect(fifth.key.valueAsString, '4'); - expect(fifth.value.valueAsString, '996'); + expect((fifth.key as InstanceRef).valueAsString, '4'); + expect((fifth.value as InstanceRef).valueAsString, '996'); final sixth = inst.associations![5]; - expect(sixth.key.valueAsString, '5'); - expect(sixth.value.valueAsString, '995'); + expect((sixth.key as InstanceRef).valueAsString, '5'); + expect((sixth.value as InstanceRef).valueAsString, '995'); }); test('Maps with offset/count are truncated', () async { @@ -1060,11 +1060,11 @@ void runTests({ expect(inst.count, 7); expect(inst.associations!.length, 7); final fifth = inst.associations![0]; - expect(fifth.key.valueAsString, '4'); - expect(fifth.value.valueAsString, '996'); + expect((fifth.key as InstanceRef).valueAsString, '4'); + expect((fifth.value as InstanceRef).valueAsString, '996'); final sixth = inst.associations![1]; - expect(sixth.key.valueAsString, '5'); - expect(sixth.value.valueAsString, '995'); + expect((sixth.key as InstanceRef).valueAsString, '5'); + expect((sixth.value as InstanceRef).valueAsString, '995'); }); test( @@ -1090,8 +1090,8 @@ void runTests({ expect(inst.count, 1); expect(inst.associations!.length, 1); final only = inst.associations![0]; - expect(only.key.valueAsString, '1000'); - expect(only.value.valueAsString, '0'); + expect((only.key as InstanceRef).valueAsString, '1000'); + expect((only.value as InstanceRef).valueAsString, '0'); }, ); @@ -1761,7 +1761,8 @@ void runTests({ (event) => event.kind == EventKind.kPauseException, ); expect(event.exception, isNotNull); - // Check that the exception stack trace has been mapped to Dart source files. + // Check that the exception stack trace has been mapped to Dart source + // files. expect(event.exception!.valueAsString, contains('main.dart')); final stack = await service.getStack(isolateId!); @@ -2010,11 +2011,11 @@ void runTests({ final stream = service.onEvent('Debug'); final vm = await service.getVM(); final isolateId = vm.isolates!.first.id!; - final pauseCompleter = Completer(); + final pauseCompleter = Completer(); final pauseSub = context.tabConnection.debugger.onPaused.listen((_) { pauseCompleter.complete(); }); - final resumeCompleter = Completer(); + final resumeCompleter = Completer(); final resumeSub = context.tabConnection.debugger.onResumed.listen((_) { resumeCompleter.complete(); }); @@ -2468,7 +2469,8 @@ void runTests({ ); String emitDebugEvent(String data) => - "\$emitDebugEvent('$extensionKind', '{ \"$eventData\": \"$data\" }');"; + "\$emitDebugEvent('$extensionKind', '{ \"$eventData\": \"$data\"" + "}');"; final size = 2; final batch1 = List.generate(size, (int i) => 'data$i'); @@ -2485,7 +2487,7 @@ void runTests({ for (final data in batch1) { await context.tabConnection.runtime.evaluate(emitDebugEvent(data)); } - await Future.delayed(delay); + await Future.delayed(delay); for (final data in batch2) { await context.tabConnection.runtime.evaluate(emitDebugEvent(data)); } @@ -2713,7 +2715,7 @@ void runTests({ final _isSuccess = isA(); -TypeMatcher _libRef(uriMatcher) => +TypeMatcher _libRef(Object? uriMatcher) => isA().having((l) => l.uri, 'uri', uriMatcher); void expectEventually(Matcher expectation) {} diff --git a/dwds/test/common/hot_restart_common.dart b/dwds/test/common/hot_restart_common.dart index 980e4e30f..a7168d70b 100644 --- a/dwds/test/common/hot_restart_common.dart +++ b/dwds/test/common/hot_restart_common.dart @@ -119,7 +119,7 @@ void runTests({ moduleFormat: provider.ddcModuleFormat, canaryFeatures: provider.canaryFeatures, ), - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( enableDebugging: false, ), ); @@ -147,7 +147,7 @@ void runTests({ moduleFormat: provider.ddcModuleFormat, canaryFeatures: provider.canaryFeatures, ), - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( enableDebugging: false, useSse: false, ), @@ -168,7 +168,7 @@ void runTests({ }, // `BuildResult`s are only ever emitted when using the build daemon. skip: compilationMode != CompilationMode.buildDaemon, - timeout: Timeout.factor(2), + timeout: const Timeout.factor(2), ); group('Injected client', () { @@ -472,7 +472,7 @@ void runTests({ await fakeClient.callServiceExtension(hotRestart); await logFuture; }); - }, timeout: Timeout.factor(2)); + }, timeout: const Timeout.factor(2)); group( 'Injected client with hot restart', @@ -540,7 +540,7 @@ void runTests({ moduleFormat: provider.ddcModuleFormat, canaryFeatures: provider.canaryFeatures, ), - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( enableDebugging: false, ), ); @@ -565,7 +565,7 @@ void runTests({ }, // `BuildResult`s are only ever emitted when using the build daemon. skip: compilationMode != CompilationMode.buildDaemon, - timeout: Timeout.factor(2), + timeout: const Timeout.factor(2), ); group('when isolates_paused_on_start is true', () { diff --git a/dwds/test/common/hot_restart_correctness_common.dart b/dwds/test/common/hot_restart_correctness_common.dart index 2b1bacc2e..459aeef1b 100644 --- a/dwds/test/common/hot_restart_correctness_common.dart +++ b/dwds/test/common/hot_restart_correctness_common.dart @@ -139,7 +139,7 @@ void runTests({ await logFuture; }, ); - }, timeout: Timeout.factor(2)); + }, timeout: const Timeout.factor(2)); group( 'Injected client with hot restart', @@ -180,7 +180,7 @@ void runTests({ moduleFormat: provider.ddcModuleFormat, canaryFeatures: provider.canaryFeatures, ), - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( enableDebugging: false, ), ); @@ -201,7 +201,7 @@ void runTests({ }, // `BuildResult`s are only ever emitted when using the build daemon. skip: compilationMode != CompilationMode.buildDaemon, - timeout: Timeout.factor(2), + timeout: const Timeout.factor(2), ); } diff --git a/dwds/test/dart_uri_test.dart b/dwds/test/dart_uri_test.dart index dedba33f7..df54e556d 100644 --- a/dwds/test/dart_uri_test.dart +++ b/dwds/test/dart_uri_test.dart @@ -7,6 +7,7 @@ library; import 'package:dwds/src/utilities/dart_uri.dart'; +import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; import 'package:test_common/logging.dart'; @@ -156,8 +157,8 @@ void main() { final logs = []; void logWriter( - level, - message, { + Level level, + String message, { String? error, String? loggerName, String? stackTrace, @@ -207,7 +208,7 @@ void main() { setUpAll(() async { final toolConfiguration = TestToolConfiguration.withLoadStrategy( loadStrategy: G3TestStrategy(FakeAssetReader()), - appMetadata: TestAppMetadata.internalApp(), + appMetadata: const TestAppMetadata.internalApp(), ); setGlobalsForTesting(toolConfiguration: toolConfiguration); await DartUri.initialize(); diff --git a/dwds/test/dds_port_test.dart b/dwds/test/dds_port_test.dart index 7484c8659..e2befdf44 100644 --- a/dwds/test/dds_port_test.dart +++ b/dwds/test/dds_port_test.dart @@ -37,7 +37,7 @@ void main() { await server.close(); await context.setUp( - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( ddsPort: expectedPort, ), ); @@ -52,7 +52,7 @@ void main() { await server.close(); await context.setUp( - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( ddsConfiguration: DartDevelopmentServiceConfiguration( port: expectedPort, ), diff --git a/dwds/test/debug_extension_test.dart b/dwds/test/debug_extension_test.dart index 0a987596c..965195792 100644 --- a/dwds/test/debug_extension_test.dart +++ b/dwds/test/debug_extension_test.dart @@ -50,7 +50,7 @@ void main() async { final title = await context.webDriver.title; if (title == 'Dart DevTools') return; - await Future.delayed(retryWait); + await Future.delayed(retryWait); return waitForDartDevToolsWithRetry( retryCount: retryCount--, retryWait: retryWait, @@ -231,7 +231,7 @@ void main() async { group('With encoding', () { setUp(() async { await context.setUp( - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( enableDebugExtension: true, urlEncoder: (url) async => url.endsWith(r'/$debug') ? 'http://some-encoded-url:8081/' : url, @@ -259,8 +259,10 @@ void main() async { setUp(() async { await context.setUp( - appMetadata: TestAppMetadata.externalApp().copyWith(hostname: 'any'), - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + appMetadata: const TestAppMetadata.externalApp().copyWith( + hostname: 'any', + ), + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( enableDebugExtension: true, ), ); diff --git a/dwds/test/debug_service_test.dart b/dwds/test/debug_service_test.dart index 67089ca82..da13e4d1e 100644 --- a/dwds/test/debug_service_test.dart +++ b/dwds/test/debug_service_test.dart @@ -27,9 +27,11 @@ void main() { setUpAll(() async { // Disable DDS as we're testing DWDS behavior. await context.setUp( - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( spawnDds: false, - ddsConfiguration: DartDevelopmentServiceConfiguration(enable: false), + ddsConfiguration: const DartDevelopmentServiceConfiguration( + enable: false, + ), ), ); }); diff --git a/dwds/test/debugger_test.dart b/dwds/test/debugger_test.dart index fc78cbf55..38ccbbd8d 100644 --- a/dwds/test/debugger_test.dart +++ b/dwds/test/debugger_test.dart @@ -55,7 +55,7 @@ final sampleSyncFrame = WipCallFrame({ 'functionLocation': {'scriptId': '69', 'lineNumber': 88, 'columnNumber': 72}, 'location': {'scriptId': '69', 'lineNumber': 37, 'columnNumber': 0}, 'url': '', - 'scopeChain': [], + 'scopeChain': >[], 'this': {'type': 'undefined'}, }); @@ -68,8 +68,8 @@ final sampleAsyncFrame = CallFrame({ }); final Map scripts = { - '69': WipScript({'url': 'http://127.0.0.1:8081/foo.ddc.js'}), - '71': WipScript({'url': 'http://127.0.0.1:8081/bar.ddc.js'}), + '69': WipScript({'url': 'http://127.0.0.1:8081/foo.ddc.js'}), + '71': WipScript({'url': 'http://127.0.0.1:8081/bar.ddc.js'}), }; void main() async { @@ -91,7 +91,7 @@ void main() async { skipLists = SkipLists(root); debugger = await Debugger.create( webkitDebugger, - (_, __) {}, + (_, _) {}, locations, skipLists, root, @@ -145,10 +145,10 @@ void main() async { asyncStackTrace: StackTrace({ 'callFrames': [sampleAsyncFrame.json], 'parent': StackTrace({ - 'callFrames': [], + 'callFrames': >[], 'parent': StackTrace({ 'callFrames': [sampleAsyncFrame.json], - 'parent': StackTrace({'callFrames': []}).json, + 'parent': StackTrace({'callFrames': >[]}).json, }).json, }).json, }), @@ -176,8 +176,8 @@ void main() async { group('errors', () { setUp(() { - // We need to provide an Isolate so that the code doesn't bail out on a null - // check before it has a chance to throw. + // We need to provide an Isolate so that the code doesn't bail out on a + // null check before it has a chance to throw. inspector = FakeChromeAppInspector( webkitDebugger, fakeIsolate: simpleIsolate, diff --git a/dwds/test/devtools_test.dart b/dwds/test/devtools_test.dart index b5f9d040a..7fb5589c9 100644 --- a/dwds/test/devtools_test.dart +++ b/dwds/test/devtools_test.dart @@ -24,7 +24,7 @@ Future _waitForPageReady(TestContext context) async { while (attempt-- > 0) { final content = await context.webDriver.pageSource; if (content.contains('hello_world')) return; - await Future.delayed(const Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); } throw StateError('Page never initialized'); } @@ -36,135 +36,130 @@ void main() { final context = TestContext(TestProject.test, provider); for (final serveFromDds in [true, false]) { - group( - 'Injected client with DevTools served from ${serveFromDds ? 'DDS' : 'DevTools Launcher'}', - () { - setUp(() async { - await context.setUp( - debugSettings: TestDebugSettings.withDevToolsLaunch( - context, - serveFromDds: serveFromDds, - ), + group('Injected client with DevTools served from ' + '${serveFromDds ? 'DDS' : 'DevTools Launcher'}', () { + setUp(() async { + await context.setUp( + debugSettings: TestDebugSettings.withDevToolsLaunch( + context, + serveFromDds: serveFromDds, + ), + ); + await context.webDriver.driver.keyboard.sendChord([Keyboard.alt, 'd']); + // Wait for DevTools to actually open. + await Future.delayed(const Duration(seconds: 2)); + }); + + tearDown(() async { + await context.tearDown(); + }); + + test('can launch devtools', () async { + final windows = await context.webDriver.windows.toList(); + await context.webDriver.driver.switchTo.window(windows.last); + expect(await context.webDriver.pageSource, contains('DevTools')); + expect(await context.webDriver.currentUrl, contains('ide=Dwds')); + // TODO(https://github.com/dart-lang/webdev/issues/1888): Re-enable. + }, skip: Platform.isWindows); + + test( + 'can not launch devtools for the same app in multiple tabs', + () async { + final appUrl = await context.webDriver.currentUrl; + // Open a new tab, select it, and navigate to the app + await context.webDriver.driver.execute( + "window.open('$appUrl', '_blank');", + [], ); + await Future.delayed(const Duration(seconds: 2)); + final newAppWindow = await context.webDriver.windows.last; + await newAppWindow.setAsActive(); + + // Wait for the page to be ready before trying to open DevTools again. + await _waitForPageReady(context); + + // Try to open devtools and check for the alert. await context.webDriver.driver.keyboard.sendChord([ Keyboard.alt, 'd', ]); - // Wait for DevTools to actually open. - await Future.delayed(const Duration(seconds: 2)); - }); + await Future.delayed(const Duration(seconds: 2)); + final alert = context.webDriver.driver.switchTo.alert; + expect(alert, isNotNull); + expect( + await alert.text, + contains('This app is already being debugged in a different tab'), + ); + await alert.accept(); - tearDown(() async { - await context.tearDown(); - }); + var windows = await context.webDriver.windows.toList(); + for (final window in windows) { + if (window.id != newAppWindow.id) { + await window.setAsActive(); + await window.close(); + } + } - test('can launch devtools', () async { - final windows = await context.webDriver.windows.toList(); - await context.webDriver.driver.switchTo.window(windows.last); + await newAppWindow.setAsActive(); + await context.webDriver.driver.keyboard.sendChord([ + Keyboard.alt, + 'd', + ]); + await Future.delayed(const Duration(seconds: 2)); + windows = await context.webDriver.windows.toList(); + final devToolsWindow = windows.firstWhere( + (window) => window != newAppWindow, + ); + await devToolsWindow.setAsActive(); expect(await context.webDriver.pageSource, contains('DevTools')); - expect(await context.webDriver.currentUrl, contains('ide=Dwds')); - // TODO(https://github.com/dart-lang/webdev/issues/1888): Re-enable. - }, skip: Platform.isWindows); - - test( - 'can not launch devtools for the same app in multiple tabs', - () async { - final appUrl = await context.webDriver.currentUrl; - // Open a new tab, select it, and navigate to the app - await context.webDriver.driver.execute( - "window.open('$appUrl', '_blank');", - [], - ); - await Future.delayed(const Duration(seconds: 2)); - final newAppWindow = await context.webDriver.windows.last; - await newAppWindow.setAsActive(); - - // Wait for the page to be ready before trying to open DevTools again. - await _waitForPageReady(context); - - // Try to open devtools and check for the alert. - await context.webDriver.driver.keyboard.sendChord([ - Keyboard.alt, - 'd', - ]); - await Future.delayed(const Duration(seconds: 2)); - final alert = context.webDriver.driver.switchTo.alert; - expect(alert, isNotNull); - expect( - await alert.text, - contains('This app is already being debugged in a different tab'), - ); - await alert.accept(); - - var windows = await context.webDriver.windows.toList(); - for (final window in windows) { - if (window.id != newAppWindow.id) { - await window.setAsActive(); - await window.close(); - } - } + }, + skip: 'See https://github.com/dart-lang/webdev/issues/2462', + ); - await newAppWindow.setAsActive(); - await context.webDriver.driver.keyboard.sendChord([ - Keyboard.alt, - 'd', - ]); - await Future.delayed(const Duration(seconds: 2)); - windows = await context.webDriver.windows.toList(); - final devToolsWindow = windows.firstWhere( - (window) => window != newAppWindow, - ); - await devToolsWindow.setAsActive(); - expect(await context.webDriver.pageSource, contains('DevTools')); - }, - skip: 'See https://github.com/dart-lang/webdev/issues/2462', - ); + test( + 'destroys and recreates the isolate during a page refresh', + () async { + // This test is the same as one in reload_test, but runs here when + // there is a connected client (DevTools) since it can behave + // differently. + // https://github.com/dart-lang/webdev/pull/901#issuecomment-586438132 + final client = context.debugConnection.vmService; + await client.streamListen('Isolate'); + await context.makeEdits([ + ( + file: context.project.dartEntryFileName, + originalString: 'Hello World!', + newString: 'Bonjour le monde!', + ), + ]); + await context.waitForSuccessfulBuild(propagateToBrowser: true); + + final eventsDone = expectLater( + client.onIsolateEvent, + emitsThrough( + emitsInOrder([ + _hasKind(EventKind.kIsolateExit), + _hasKind(EventKind.kIsolateStart), + _hasKind(EventKind.kIsolateRunnable), + ]), + ), + ); - test( - 'destroys and recreates the isolate during a page refresh', - () async { - // This test is the same as one in reload_test, but runs here when there - // is a connected client (DevTools) since it can behave differently. - // https://github.com/dart-lang/webdev/pull/901#issuecomment-586438132 - final client = context.debugConnection.vmService; - await client.streamListen('Isolate'); - await context.makeEdits([ - ( - file: context.project.dartEntryFileName, - originalString: 'Hello World!', - newString: 'Bonjour le monde!', - ), - ]); - await context.waitForSuccessfulBuild(propagateToBrowser: true); - - final eventsDone = expectLater( - client.onIsolateEvent, - emitsThrough( - emitsInOrder([ - _hasKind(EventKind.kIsolateExit), - _hasKind(EventKind.kIsolateStart), - _hasKind(EventKind.kIsolateRunnable), - ]), - ), - ); - - await context.webDriver.driver.refresh(); - - await eventsDone; - }, - skip: 'https://github.com/dart-lang/webdev/issues/1888', - ); - }, - timeout: Timeout.factor(2), - ); + await context.webDriver.driver.refresh(); + + await eventsDone; + }, + skip: 'https://github.com/dart-lang/webdev/issues/1888', + ); + }, timeout: const Timeout.factor(2)); } group('Injected client without a DevTools server', () { setUp(() async { await context.setUp( - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( enableDevToolsLaunch: true, - ddsConfiguration: DartDevelopmentServiceConfiguration( + ddsConfiguration: const DartDevelopmentServiceConfiguration( serveDevTools: false, ), ), @@ -178,7 +173,7 @@ void main() { test('gives a good error if devtools is not served', () async { // Try to open devtools and check for the alert. await context.webDriver.driver.keyboard.sendChord([Keyboard.alt, 'd']); - await Future.delayed(const Duration(seconds: 2)); + await Future.delayed(const Duration(seconds: 2)); final alert = context.webDriver.driver.switchTo.alert; expect(alert, isNotNull); expect(await alert.text, contains('--debug')); @@ -191,7 +186,7 @@ void main() { () { setUp(() async { await context.setUp( - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( enableDebugExtension: true, ), ); @@ -208,7 +203,7 @@ void main() { }); // Try to open devtools and check for the alert. await context.webDriver.driver.keyboard.sendChord([Keyboard.alt, 'd']); - await Future.delayed(const Duration(seconds: 2)); + await Future.delayed(const Duration(seconds: 2)); final alert = context.webDriver.driver.switchTo.alert; expect(alert, isNotNull); expect(await alert.text, contains('--debug')); @@ -219,7 +214,7 @@ void main() { }, tags: ['extension'], skip: 'https://github.com/dart-lang/webdev/issues/2114', - timeout: Timeout.factor(2), + timeout: const Timeout.factor(2), ); } diff --git a/dwds/test/evaluate_common.dart b/dwds/test/evaluate_common.dart index b4406263c..b0850686b 100644 --- a/dwds/test/evaluate_common.dart +++ b/dwds/test/evaluate_common.dart @@ -150,18 +150,28 @@ void testAll({ } catch (_) {} }); - Future onBreakPoint(script, bpId, body) => - onBp(stream, isolateId, script, bpId, body); - - Future evaluateInFrame(frame, expr, {scope}) async => - await context.service.evaluateInFrame( - isolateId, - frame, - expr, - scope: scope, - ); + Future onBreakPoint( + ScriptRef script, + String bpId, + Future Function(Event) body, + ) => onBp(stream, isolateId, script, bpId, body); + + Future evaluateInFrame( + int frame, + String expr, { + Map? scope, + }) async => await context.service.evaluateInFrame( + isolateId, + frame, + expr, + scope: scope, + ); - Future getInstanceRef(frame, expr, {scope}) async { + Future getInstanceRef( + int frame, + String expr, { + Map? scope, + }) async { final result = await evaluateInFrame(frame, expr, scope: scope); expect(result, isA()); return result as InstanceRef; @@ -586,7 +596,8 @@ void testAll({ attempt, lessThan(maxAttempts), reason: - 'Failed to receive and async frame error in $attempt attempts', + 'Failed to receive and async frame error in $attempt ' + 'attempts', ); await Future.delayed(const Duration(milliseconds: 10)); attempt++; @@ -654,11 +665,22 @@ void testAll({ tearDown(() async {}); - Future evaluate(targetId, expr, {scope}) async => await context - .service - .evaluate(isolateId, targetId, expr, scope: scope); + Future evaluate( + String targetId, + String expr, { + Map? scope, + }) async => await context.service.evaluate( + isolateId, + targetId, + expr, + scope: scope, + ); - Future getInstanceRef(targetId, expr, {scope}) async { + Future getInstanceRef( + String targetId, + String expr, { + Map? scope, + }) async { final result = await evaluate(targetId, expr, scope: scope); expect(result, isA()); return result as InstanceRef; @@ -676,7 +698,7 @@ void testAll({ final libraryId = getRootLibraryId(); final type = await getInstanceRef(libraryId, '(0,1).runtimeType'); - final result = await getInstanceRef(type.id, 'hashCode'); + final result = await getInstanceRef(type.id!, 'hashCode'); expect(result, matchInstanceRefKind('Double')); }, @@ -687,7 +709,7 @@ void testAll({ final libraryId = getRootLibraryId(); final type = await getInstanceRef(libraryId, 'Object()'); - final result = await getInstanceRef(type.id, 'hashCode'); + final result = await getInstanceRef(type.id!, 'hashCode'); expect(result, matchInstanceRefKind('Double')); }); @@ -895,26 +917,27 @@ Future _setBreakpointInInjectedClient(WipDebugger debugger) async { 'columnNumber': 0, }, ); - return result.json['result']['breakpointId']; + return (result.json['result']! as Map)['breakpointId']! + as String; } Matcher matchInstanceRefKind(String kind) => isA().having((instance) => instance.kind, 'kind', kind); -Matcher matchInstanceRef(dynamic value) => isA().having( +Matcher matchInstanceRef(Object? value) => isA().having( (instance) => instance.valueAsString, 'valueAsString', value, ); -Matcher matchInstanceClassName(dynamic className) => isA().having( +Matcher matchInstanceClassName(Object? className) => isA().having( (instance) => instance.classRef!.name, 'class name', className, ); -Matcher matchInstanceRefClassName(dynamic className) => isA() +Matcher matchInstanceRefClassName(Object? className) => isA() .having((instance) => instance.classRef!.name, 'class name', className); -Matcher matchErrorRef(dynamic message) => +Matcher matchErrorRef(Object? message) => isA().having((instance) => instance.message, 'message', message); diff --git a/dwds/test/evaluate_parts_common.dart b/dwds/test/evaluate_parts_common.dart index e417164eb..fdf82dd29 100644 --- a/dwds/test/evaluate_parts_common.dart +++ b/dwds/test/evaluate_parts_common.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -library; - import 'package:test/test.dart'; import 'package:test_common/logging.dart'; import 'package:test_common/test_sdk_configuration.dart'; diff --git a/dwds/test/events_test.dart b/dwds/test/events_test.dart index cb8e5434f..dd9aeb0f9 100644 --- a/dwds/test/events_test.dart +++ b/dwds/test/events_test.dart @@ -41,7 +41,7 @@ void main() { test('emits HTTP_REQUEST_EXCEPTION event', () async { Future throwAsyncException() async { - await Future.delayed(const Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); throw Exception('async error'); } @@ -77,7 +77,7 @@ void main() { // Ignore the response. final response = await request.close(); - await response.drain(); + await response.drain(); // Wait for expected events. await events; @@ -140,7 +140,7 @@ void main() { ), ); await context.setUp( - testSettings: TestSettings(enableExpressionEvaluation: true), + testSettings: const TestSettings(enableExpressionEvaluation: true), debugSettings: TestDebugSettings.withDevToolsLaunch(context), ); keyboard = context.webDriver.driver.keyboard; @@ -302,8 +302,8 @@ void main() { (event) => event.kind == EventKind.kPauseBreakpoint, ); - // Evaluation succeeds and return ErrorRef containing compilation error, - // so event is marked as success. + // Evaluation succeeds and return ErrorRef containing compilation + // error, so event is marked as success. final expression = 'some-bad-expression'; await expectEventDuring( matchesEvent(DwdsEventKind.evaluateInFrame, { @@ -530,7 +530,7 @@ void main() { }, // TODO(elliette): Re-enable (https://github.com/dart-lang/webdev/issues/1852). skip: Platform.isWindows, - timeout: Timeout.factor(2), + timeout: const Timeout.factor(2), ); } diff --git a/dwds/test/execution_context_test.dart b/dwds/test/execution_context_test.dart index 3a02c935c..a6a71c77b 100644 --- a/dwds/test/execution_context_test.dart +++ b/dwds/test/execution_context_test.dart @@ -142,9 +142,9 @@ class TestExtensionDebugger extends ExtensionDebugger { @override Future sendCommand( String command, { - Map? params, + Map? params, }) { - final id = params?['contextId']; + final id = params?['contextId'] as int?; final response = super.sendCommand(command, params: params); /// Mock stale contexts that cause the evaluation to throw. @@ -187,7 +187,7 @@ class TestDebuggerConnection { /// Return the initial context ID from the DevToolsRequest. Future defaultContextId() async { // Give the previous events time to propagate. - await Future.delayed(Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); return TestContextId.from(await extensionDebugger.executionContext!.id); } @@ -201,7 +201,7 @@ class TestDebuggerConnection { final executionContextId = extensionDebugger.executionContext!.id; // Give it time to send the evaluate request. - await Future.delayed(Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); // Respond to the evaluate request. _sendEvaluationResponse({ @@ -221,7 +221,7 @@ class TestDebuggerConnection { final executionContextId = extensionDebugger.executionContext!.id; // Give it time to send the evaluate request. - await Future.delayed(Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); // Respond to the evaluate request. _sendEvaluationResponse({ @@ -259,7 +259,7 @@ class TestDebuggerConnection { ); } - void _sendEvaluationResponse(Map response) { + void _sendEvaluationResponse(Map response) { // Respond to the evaluate request. final extensionResponse = ExtensionResponse( (b) => b @@ -297,7 +297,7 @@ class TestDebuggerConnection { Future _waitForExecutionContext() async { while (extensionDebugger.executionContext == null) { - await Future.delayed(Duration(milliseconds: 20)); + await Future.delayed(const Duration(milliseconds: 20)); } return extensionDebugger.executionContext; } diff --git a/dwds/test/expression_compiler_service_common.dart b/dwds/test/expression_compiler_service_common.dart index bb6f267e9..8c8563f70 100644 --- a/dwds/test/expression_compiler_service_common.dart +++ b/dwds/test/expression_compiler_service_common.dart @@ -75,7 +75,7 @@ void testAll({required CompilerOptions compilerOptions}) { 'localhost', port, verbose: false, - sdkConfigurationProvider: DefaultSdkConfigurationProvider(), + sdkConfigurationProvider: const DefaultSdkConfigurationProvider(), ); await service.initialize(compilerOptions); diff --git a/dwds/test/expression_evaluator_test.dart b/dwds/test/expression_evaluator_test.dart index 1ad7d3e34..f1c8ba6e6 100644 --- a/dwds/test/expression_evaluator_test.dart +++ b/dwds/test/expression_evaluator_test.dart @@ -133,7 +133,10 @@ void main() async { pausedController.sink.add( DebuggerPausedEvent({ 'method': '', - 'params': {'reason': 'other', 'callFrames': []}, + 'params': { + 'reason': 'other', + 'callFrames': >[], + }, }), ); diff --git a/dwds/test/extension_debugger_test.dart b/dwds/test/extension_debugger_test.dart index 5c865b92d..0cd465191 100644 --- a/dwds/test/extension_debugger_test.dart +++ b/dwds/test/extension_debugger_test.dart @@ -14,6 +14,7 @@ import 'package:dwds/data/extension_request.dart'; import 'package:dwds/data/serializers.dart'; import 'package:dwds/src/servers/extension_debugger.dart'; import 'package:test/test.dart'; +import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; import 'fixtures/debugger_data.dart'; import 'fixtures/fakes.dart'; @@ -42,7 +43,7 @@ void main() async { ..id = 0 ..success = true, ); - final resultCompleter = Completer(); + final resultCompleter = Completer(); unawaited( extensionDebugger .sendCommand('Runtime.evaluate', params: {'expression': '\$pi'}) @@ -52,7 +53,10 @@ void main() async { jsonEncode(serializers.serialize(extensionResponse)), ); final response = await resultCompleter.future; - expect(response.result['result']['value'], 3.14); + expect( + (response.result!['result']! as Map)['value'], + 3.14, + ); }); test('an ExtensionEvent', () async { diff --git a/dwds/test/fixtures/context.dart b/dwds/test/fixtures/context.dart index 5b7f4da55..6c13cca42 100644 --- a/dwds/test/fixtures/context.dart +++ b/dwds/test/fixtures/context.dart @@ -122,8 +122,8 @@ class TestContext { /// Internal VM service. /// - /// Prefer using [vmService] instead in tests when possible, to include testing - /// of the VmServerConnection (bypassed when using [service]). + /// Prefer using [vmService] instead in tests when possible, to include + /// testing of the VmServerConnection (bypassed when using [service]). ChromeProxyService get service => fetchChromeProxyService(debugConnection); /// External VM service. @@ -202,7 +202,7 @@ class TestContext { // We therefore wait until ChromeDriver reports that it has started // successfully. - final chromeDriverStartup = Completer(); + final chromeDriverStartup = Completer(); stdOutLines.listen((line) { if (!chromeDriverStartup.isCompleted && line.contains('was started successfully')) { @@ -320,7 +320,7 @@ class TestContext { final entry = p.toUri( p.join(project.webAssetsPath, project.dartEntryFileName), ); - frontendServerFileSystem = LocalFileSystem(); + frontendServerFileSystem = const LocalFileSystem(); final packageUriMapper = await PackageUriMapper.create( frontendServerFileSystem, project.packageConfigFile, @@ -393,7 +393,8 @@ class TestContext { buildSettings, ).strategy, _ => throw Exception( - 'Unsupported DDC module format ${testSettings.moduleFormat.name}.', + 'Unsupported DDC module format ' + '${testSettings.moduleFormat.name}.', ), }; buildResults = const Stream.empty(); @@ -439,8 +440,8 @@ class TestContext { // The debugger tab must be enabled and connected before certain // listeners in DWDS or `main` is run. - final tabConnectionCompleter = Completer(); - final appConnectionCompleter = Completer(); + final tabConnectionCompleter = Completer(); + final appConnectionCompleter = Completer(); final connection = ChromeConnection('localhost', debugPort); // TODO(srujzs): In the case of the frontend server, it doesn't make sense @@ -589,7 +590,9 @@ class TestContext { // timestamp that is guaranteed to be after the previous compile. // TODO(https://github.com/dart-lang/sdk/issues/51937): Remove once this bug // is fixed. - if (Platform.isWindows) await Future.delayed(Duration(seconds: 1)); + if (Platform.isWindows) { + await Future.delayed(const Duration(seconds: 1)); + } for (var (:file, :originalString, :newString) in edits) { if (file == project.dartEntryFileName) { file = project.dartEntryFilePath; @@ -636,7 +639,7 @@ class TestContext { final delay = Platform.isWindows ? const Duration(seconds: 5) : const Duration(seconds: 2); - await Future.delayed(delay); + await Future.delayed(delay); } } diff --git a/dwds/test/fixtures/debugger_data.dart b/dwds/test/fixtures/debugger_data.dart index 5b2022654..43a0b1926 100644 --- a/dwds/test/fixtures/debugger_data.dart +++ b/dwds/test/fixtures/debugger_data.dart @@ -15,7 +15,7 @@ import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; /// level of stack. List frames1 = frames1Json.map(WipCallFrame.new).toList(); -List> frames1Json = [ +List> frames1Json = [ { "callFrameId": "{\"ordinal\":0,\"injectedScriptId\":2}", "functionName": "", @@ -92,10 +92,10 @@ List> frames1Json = [ /// elements of a scope chain. /// /// It has two variables named 'a' and 'b' in the first scope. -var variables1 = [ +List variables1 = [ WipResponse({ 'id': 1, - 'result': {'result': []}, + 'result': {'result': []}, }), WipResponse({ 'id': 2, @@ -114,7 +114,7 @@ var variables1 = [ }), WipResponse({ 'id': 3, - 'result': {'result': []}, + 'result': {'result': []}, }), // Fake that the SDK is loaded. WipResponse({ @@ -128,16 +128,16 @@ var variables1 = [ }), WipResponse({ 'id': 5, - 'result': {'result': []}, + 'result': {'result': []}, }), WipResponse({ 'id': 6, - 'result': {'result': []}, + 'result': {'result': []}, }), ]; /// Sample data for a Debugger.scriptParsed event -var scriptParsedParams = { +Map scriptParsedParams = { "endColumn": 0, "endLine": 53, "executionContextAuxData": { diff --git a/dwds/test/fixtures/fakes.dart b/dwds/test/fixtures/fakes.dart index 2cd6083b2..73413d0c8 100644 --- a/dwds/test/fixtures/fakes.dart +++ b/dwds/test/fixtures/fakes.dart @@ -80,10 +80,8 @@ class FakeChromeAppInspector extends FakeInspector 'Runtime.getProperties', params: {'objectId': objectId, 'ownProperties': true}, ); - final result = response.result?['result']; - return result - .map((each) => Property(each as Map)) - .toList(); + final result = response.result?['result'] as List>; + return result.map(Property.new).toList(); } @override @@ -212,9 +210,9 @@ class FakeWebkitDebugger implements WebkitDebugger { ReloadConfiguration.none, (_) async => {}, (_) async => {}, - (_, __) async => null, - (MetadataProvider _, String __) async => '', - (MetadataProvider _, String __) async => '', + (_, _) async => null, + (MetadataProvider _, String _) async => '', + (MetadataProvider _, String _) async => '', (String _) => '', (MetadataProvider _) async => {}, FakeAssetReader(), @@ -234,19 +232,20 @@ class FakeWebkitDebugger implements WebkitDebugger { Stream? get onClosed => null; @override - Stream get onGlobalObjectCleared => Stream.empty(); + Stream get onGlobalObjectCleared => + const Stream.empty(); @override late Stream onPaused; @override - Stream get onResumed => Stream.empty(); + Stream get onResumed => const Stream.empty(); @override - Stream get onScriptParsed => Stream.empty(); + Stream get onScriptParsed => const Stream.empty(); @override - Stream get onTargetCrashed => Stream.empty(); + Stream get onTargetCrashed => const Stream.empty(); @override Future pause() async => fakeWipResponse; @@ -263,7 +262,7 @@ class FakeWebkitDebugger implements WebkitDebugger { @override Future sendCommand( String command, { - Map? params, + Map? params, }) async { // Force the results that we expect for looking up the variables. if (command == 'Runtime.getProperties') { @@ -281,27 +280,27 @@ class FakeWebkitDebugger implements WebkitDebugger { fakeWipResponse; @override - Future stepInto({Map? params}) async => + Future stepInto({Map? params}) async => fakeWipResponse; @override Future stepOut() async => fakeWipResponse; @override - Future stepOver({Map? params}) async => + Future stepOver({Map? params}) async => fakeWipResponse; @override - Stream get onConsoleAPICalled => Stream.empty(); + Stream get onConsoleAPICalled => const Stream.empty(); @override - Stream get onExceptionThrown => Stream.empty(); + Stream get onExceptionThrown => const Stream.empty(); @override Future close() async {} @override - Stream get onClose => Stream.empty(); + Stream get onClose => const Stream.empty(); @override Future evaluate( @@ -315,7 +314,7 @@ class FakeWebkitDebugger implements WebkitDebugger { String callFrameId, String expression, ) async { - return RemoteObject({}); + return RemoteObject({}); } @override @@ -422,18 +421,16 @@ class FakeStrategy extends LoadStrategy { class FakeAssetReader implements AssetReader { String? metadata; - final String? _dartSource; - final String? _sourceMap; - FakeAssetReader({this.metadata, dartSource, sourceMap}) - : _dartSource = dartSource, - _sourceMap = sourceMap; + final String? dartSource; + final String? sourceMap; + FakeAssetReader({this.metadata, this.dartSource, this.sourceMap}); @override String get basePath => ''; @override Future dartSourceContents(String serverPath) { - return _throwUnimplementedOrReturnContents(_dartSource); + return _throwUnimplementedOrReturnContents(dartSource); } @override @@ -443,7 +440,7 @@ class FakeAssetReader implements AssetReader { @override Future sourceMapContents(String serverPath) { - return _throwUnimplementedOrReturnContents(_sourceMap); + return _throwUnimplementedOrReturnContents(sourceMap); } @override diff --git a/dwds/test/fixtures/project.dart b/dwds/test/fixtures/project.dart index 62415aecf..ee83b1084 100644 --- a/dwds/test/fixtures/project.dart +++ b/dwds/test/fixtures/project.dart @@ -270,7 +270,7 @@ class TestProject { _fixturesCopy.deleteSync(recursive: true); break; } on FileSystemException catch (_) { - await Future.delayed(Duration(seconds: seconds)); + await Future.delayed(Duration(seconds: seconds)); seconds *= 2; } } diff --git a/dwds/test/fixtures/utilities.dart b/dwds/test/fixtures/utilities.dart index bccc8f325..5c66cdab7 100644 --- a/dwds/test/fixtures/utilities.dart +++ b/dwds/test/fixtures/utilities.dart @@ -21,7 +21,7 @@ Future connectClient( String dartPath, String workingDirectory, List options, - Function(ServerLog) logHandler, + void Function(ServerLog) logHandler, ) => BuildDaemonClient.connect(workingDirectory, [ dartPath, 'run', @@ -55,7 +55,7 @@ Future retryFn( throw Exception(failureMessage); } - await Future.delayed(Duration(milliseconds: delayInMs)); + await Future.delayed(Duration(milliseconds: delayInMs)); try { final result = callback(); if (expectedResult != null && result == expectedResult) return result; @@ -84,7 +84,7 @@ Future retryFnAsync( throw Exception(failureMessage); } - await Future.delayed(Duration(milliseconds: delayInMs)); + await Future.delayed(Duration(milliseconds: delayInMs)); try { final result = await callback(); if (result != null) return result; diff --git a/dwds/test/frontend_server_callstack_test.dart b/dwds/test/frontend_server_callstack_test.dart index 64ff9e359..5f9a5a620 100644 --- a/dwds/test/frontend_server_callstack_test.dart +++ b/dwds/test/frontend_server_callstack_test.dart @@ -30,7 +30,7 @@ void main() { setUpAll(() async { setCurrentLogWriter(debug: debug); await context.setUp( - testSettings: TestSettings( + testSettings: const TestSettings( compilationMode: CompilationMode.frontendServer, enableExpressionEvaluation: true, verboseCompiler: debug, diff --git a/dwds/test/handlers/asset_handler_test.dart b/dwds/test/handlers/asset_handler_test.dart index acde9797a..27de25664 100644 --- a/dwds/test/handlers/asset_handler_test.dart +++ b/dwds/test/handlers/asset_handler_test.dart @@ -22,7 +22,7 @@ void main() { setUpAll(() async { setCurrentLogWriter(); await context.setUp( - testSettings: TestSettings( + testSettings: const TestSettings( enableExpressionEvaluation: true, verboseCompiler: false, ), diff --git a/dwds/test/handlers/injector_test.dart b/dwds/test/handlers/injector_test.dart index 1d87d166d..b791deaa7 100644 --- a/dwds/test/handlers/injector_test.dart +++ b/dwds/test/handlers/injector_test.dart @@ -311,7 +311,7 @@ void main() { late DwdsInjector injector; setUp(() async { final toolConfiguration = TestToolConfiguration.withDefaultLoadStrategy( - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( useSse: false, ), ); diff --git a/dwds/test/hot_reload_breakpoints_test.dart b/dwds/test/hot_reload_breakpoints_test.dart index 608b47e46..a29f12186 100644 --- a/dwds/test/hot_reload_breakpoints_test.dart +++ b/dwds/test/hot_reload_breakpoints_test.dart @@ -47,7 +47,7 @@ void main() { setUp(() async { setCurrentLogWriter(debug: debug); await context.setUp( - testSettings: TestSettings( + testSettings: const TestSettings( enableExpressionEvaluation: true, compilationMode: CompilationMode.frontendServer, moduleFormat: ModuleFormat.ddc, @@ -523,7 +523,7 @@ void main() { // the old string still as the closure has not been reevaluated. await callEvaluateAndWaitForLog(oldCapturedString); }); - }, timeout: Timeout.factor(2)); + }, timeout: const Timeout.factor(2)); group('when pause_isolates_on_start is false', () { late VmService client; @@ -531,7 +531,7 @@ void main() { setUp(() async { setCurrentLogWriter(debug: debug); await context.setUp( - testSettings: TestSettings( + testSettings: const TestSettings( enableExpressionEvaluation: true, compilationMode: CompilationMode.frontendServer, moduleFormat: ModuleFormat.ddc, @@ -590,7 +590,7 @@ void main() { // Program should not be paused, so this should execute. await callEvaluateAndWaitForLog(newString); }); - }, timeout: Timeout.factor(2)); + }, timeout: const Timeout.factor(2)); } TypeMatcher _hasKind(String kind) => diff --git a/dwds/test/hot_reload_test.dart b/dwds/test/hot_reload_test.dart index 41080f79a..14c77f99c 100644 --- a/dwds/test/hot_reload_test.dart +++ b/dwds/test/hot_reload_test.dart @@ -81,7 +81,7 @@ void main() { setUp(() async { setCurrentLogWriter(debug: debug); await context.setUp( - testSettings: TestSettings( + testSettings: const TestSettings( enableExpressionEvaluation: true, compilationMode: CompilationMode.frontendServer, moduleFormat: ModuleFormat.ddc, @@ -134,5 +134,5 @@ void main() { await callEvaluateAndWaitForLog(newString); }); - }, timeout: Timeout.factor(2)); + }, timeout: const Timeout.factor(2)); } diff --git a/dwds/test/inspector_test.dart b/dwds/test/inspector_test.dart index 3909cdc54..925d1c37b 100644 --- a/dwds/test/inspector_test.dart +++ b/dwds/test/inspector_test.dart @@ -142,7 +142,7 @@ void main() { await inspector.getObject(remoteObject.objectId!) as Instance; final classRef = instance.classRef!; final clazz = await inspector.getObject(classRef.id!) as Class; - expect(clazz.name, 'MyTestClass'); + expect(clazz.name, 'MyTestClass'); }); }); diff --git a/dwds/test/instances/common/class_inspection_common.dart b/dwds/test/instances/common/class_inspection_common.dart index ed0d22f7f..306a1f5b2 100644 --- a/dwds/test/instances/common/class_inspection_common.dart +++ b/dwds/test/instances/common/class_inspection_common.dart @@ -31,7 +31,10 @@ void runTests({ late String isolateId; late ScriptRef mainScript; - Future onBreakPoint(breakPointId, body) => testInspector.onBreakPoint( + Future onBreakPoint( + String breakPointId, + Future Function(Event) body, + ) => testInspector.onBreakPoint( stream, isolateId, mainScript, @@ -39,7 +42,8 @@ void runTests({ body, ); - Future getObject(instanceId) => service.getObject(isolateId, instanceId); + Future getObject(String instanceId) => + service.getObject(isolateId, instanceId); group('$compilationMode |', () { setUpAll(() async { diff --git a/dwds/test/instances/common/dot_shorthands_common.dart b/dwds/test/instances/common/dot_shorthands_common.dart index 9c09be1ee..289bdb8b2 100644 --- a/dwds/test/instances/common/dot_shorthands_common.dart +++ b/dwds/test/instances/common/dot_shorthands_common.dart @@ -38,7 +38,7 @@ void runTests({ body, ); - Future getInstanceRef(frame, expression) => + Future getInstanceRef(int frame, String expression) => testInspector.getInstanceRef(isolateId, frame, expression); group('$compilationMode | dot shorthands:', () { diff --git a/dwds/test/instances/common/instance_common.dart b/dwds/test/instances/common/instance_common.dart index 377da0a78..ec1fcbba9 100644 --- a/dwds/test/instances/common/instance_common.dart +++ b/dwds/test/instances/common/instance_common.dart @@ -136,8 +136,8 @@ void runTests({ final unsupportedTestMsg = 'This test is not supported with the DDC Library ' - "Bundle Format because the dartDevEmbedder doesn't let you access compiled " - 'constructors at runtime.'; + "Bundle Format because the dartDevEmbedder doesn't let you access " + 'compiled constructors at runtime.'; group('instanceRef', () { setUp(() => setCurrentLogWriter(debug: debug)); @@ -175,11 +175,11 @@ void runTests({ final ref = await inspector.instanceRefFor(count); expect(ref!.kind, InstanceKind.kPlainInstance); final classRef = ref.classRef!; - expect(classRef.name, 'MyTestClass'); + expect(classRef.name, 'MyTestClass'); expect( classRef.id, 'classes|org-dartlang-app:///example/scopes/main.dart' - '|MyTestClass', + '|MyTestClass', ); expect(inspector.isDisplayableObject(ref), isTrue); }); @@ -327,7 +327,7 @@ void runTests({ expect(instance!.kind, InstanceKind.kPlainInstance); final classRef = instance.classRef!; expect(classRef, isNotNull); - expect(classRef.name, 'MyTestClass'); + expect(classRef.name, 'MyTestClass'); final boundFieldNames = instance.fields! .map((boundField) => boundField.decl!.name) .toList(); @@ -376,7 +376,7 @@ void runTests({ expect(instance!.kind, InstanceKind.kPlainInstance); final classRef = instance.classRef!; expect(classRef, isNotNull); - expect(classRef.name, 'MyTestClass'); + expect(classRef.name, 'MyTestClass'); expect(inspector.isDisplayableObject(instance), isTrue); }); @@ -387,7 +387,7 @@ void runTests({ final classRef = instance.classRef!; expect(classRef, isNotNull); expect(classRef.name, matchListClassName('String')); - final first = instance.elements![0]; + final first = instance.elements![0] as InstanceRef; expect(first.valueAsString, 'library'); expect(inspector.isDisplayableObject(instance), isTrue); }); @@ -413,7 +413,7 @@ void runTests({ expect(instance!.kind, InstanceKind.kMap); final classRef = instance.classRef!; expect(classRef.name, 'IdentityMap'); - final first = instance.associations![0].value; + final first = instance.associations![0].value as InstanceRef; expect(first.valueAsString, '1'); expect(inspector.isDisplayableObject(instance), isTrue); }); diff --git a/dwds/test/instances/common/instance_inspection_common.dart b/dwds/test/instances/common/instance_inspection_common.dart index 185c5cd0f..ceb1802a0 100644 --- a/dwds/test/instances/common/instance_inspection_common.dart +++ b/dwds/test/instances/common/instance_inspection_common.dart @@ -28,7 +28,10 @@ void runTests({ final testInspector = TestInspector(context); - Future onBreakPoint(breakPointId, body) => testInspector.onBreakPoint( + Future onBreakPoint( + String breakPointId, + Future Function(Event) body, + ) => testInspector.onBreakPoint( stream, isolateId, mainScript, @@ -36,21 +39,25 @@ void runTests({ body, ); - Future getInstance(frame, expression) => + Future getInstance(int frame, String expression) => testInspector.getInstance(isolateId, frame, expression); - Future getObject(instanceId) => service.getObject(isolateId, instanceId); + Future getObject(String instanceId) => + service.getObject(isolateId, instanceId); - Future getInstanceRef(frame, expression) => + Future getInstanceRef(int frame, String expression) => testInspector.getInstanceRef(isolateId, frame, expression); - Future> getFields(instanceRef, {offset, count}) => - testInspector.getFields( - isolateId, - instanceRef, - offset: offset, - count: count, - ); + Future> getFields( + InstanceRef instanceRef, { + int? offset, + int? count, + }) => testInspector.getFields( + isolateId, + instanceRef, + offset: offset, + count: count, + ); group('$compilationMode |', () { setUpAll(() async { @@ -189,7 +196,10 @@ void runTests({ expect(await getObject(instanceId), matchListInstance(type: 'int')); expect(await getFields(instanceRef), {0: 0.0, 1: 1.0, 2: 2.0}); - expect(await getFields(instanceRef, offset: 1, count: 0), {}); + expect( + await getFields(instanceRef, offset: 1, count: 0), + {}, + ); expect(await getFields(instanceRef, offset: 0), { 0: 0.0, 1: 1.0, @@ -202,7 +212,10 @@ void runTests({ 0: 1.0, 1: 2.0, }); - expect(await getFields(instanceRef, offset: 3, count: 3), {}); + expect( + await getFields(instanceRef, offset: 3, count: 3), + {}, + ); }); }); @@ -241,7 +254,10 @@ void runTests({ expect(await getFields(instanceRef), {'a': 1, 'b': 2, 'c': 3}); - expect(await getFields(instanceRef, offset: 1, count: 0), {}); + expect( + await getFields(instanceRef, offset: 1, count: 0), + {}, + ); expect(await getFields(instanceRef, offset: 0), { 'a': 1, 'b': 2, @@ -254,7 +270,10 @@ void runTests({ 'b': 2, 'c': 3, }); - expect(await getFields(instanceRef, offset: 3, count: 3), {}); + expect( + await getFields(instanceRef, offset: 3, count: 3), + {}, + ); }); }); @@ -312,8 +331,14 @@ void runTests({ 0: 5.0, 1: 7.0, }); - expect(await getFields(instanceRef, offset: 1, count: 0), {}); - expect(await getFields(instanceRef, offset: 10, count: 2), {}); + expect( + await getFields(instanceRef, offset: 1, count: 0), + {}, + ); + expect( + await getFields(instanceRef, offset: 10, count: 2), + {}, + ); }); }); diff --git a/dwds/test/instances/common/patterns_inspection_common.dart b/dwds/test/instances/common/patterns_inspection_common.dart index 57836a991..350fce3a7 100644 --- a/dwds/test/instances/common/patterns_inspection_common.dart +++ b/dwds/test/instances/common/patterns_inspection_common.dart @@ -26,7 +26,10 @@ void runTests({ late String isolateId; late ScriptRef mainScript; - Future onBreakPoint(breakPointId, body) => testInspector.onBreakPoint( + Future onBreakPoint( + String breakPointId, + Future Function(Event) body, + ) => testInspector.onBreakPoint( stream, isolateId, mainScript, @@ -34,16 +37,19 @@ void runTests({ body, ); - Future getInstanceRef(frame, expression) => + Future getInstanceRef(int frame, String expression) => testInspector.getInstanceRef(isolateId, frame, expression); - Future> getFields(instanceRef, {offset, count}) => - testInspector.getFields( - isolateId, - instanceRef, - offset: offset, - count: count, - ); + Future> getFields( + InstanceRef instanceRef, { + int? offset, + int? count, + }) => testInspector.getFields( + isolateId, + instanceRef, + offset: offset, + count: count, + ); Future> getFrameVariables(Frame frame) => testInspector.getFrameVariables(isolateId, frame); diff --git a/dwds/test/instances/common/record_inspection_common.dart b/dwds/test/instances/common/record_inspection_common.dart index 25e404df4..69065cfb1 100644 --- a/dwds/test/instances/common/record_inspection_common.dart +++ b/dwds/test/instances/common/record_inspection_common.dart @@ -26,7 +26,10 @@ void runTests({ late String isolateId; late ScriptRef mainScript; - Future onBreakPoint(breakPointId, body) => testInspector.onBreakPoint( + Future onBreakPoint( + String breakPointId, + Future Function(Event) body, + ) => testInspector.onBreakPoint( stream, isolateId, mainScript, @@ -34,19 +37,20 @@ void runTests({ body, ); - Future getInstance(frame, expression) => + Future getInstance(int frame, String expression) => testInspector.getInstance(isolateId, frame, expression); - Future getObject(instanceId) => service.getObject(isolateId, instanceId); + Future getObject(String instanceId) => + service.getObject(isolateId, instanceId); - Future getInstanceRef(frame, expression) => + Future getInstanceRef(int frame, String expression) => testInspector.getInstanceRef(isolateId, frame, expression); Future> getFields( - instanceRef, { - offset, - count, - depth = -1, + InstanceRef instanceRef, { + int? offset, + int? count, + int depth = -1, }) => testInspector.getFields( isolateId, instanceRef, @@ -94,7 +98,7 @@ void runTests({ final frame = event.topFrame!.index!; final instanceRef = await getInstanceRef(frame, 'record'); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordClass); @@ -123,8 +127,11 @@ void runTests({ expect(await getFields(instanceRef), {1: true, 2: 3}); expect(await getFields(instanceRef, offset: 0), {1: true, 2: 3}); expect(await getFields(instanceRef, offset: 1), {2: 3}); - expect(await getFields(instanceRef, offset: 2), {}); - expect(await getFields(instanceRef, offset: 0, count: 0), {}); + expect(await getFields(instanceRef, offset: 2), {}); + expect( + await getFields(instanceRef, offset: 0, count: 0), + {}, + ); expect(await getFields(instanceRef, offset: 0, count: 1), {1: true}); expect(await getFields(instanceRef, offset: 0, count: 2), { 1: true, @@ -134,7 +141,10 @@ void runTests({ 1: true, 2: 3, }); - expect(await getFields(instanceRef, offset: 2, count: 5), {}); + expect( + await getFields(instanceRef, offset: 2, count: 5), + {}, + ); }); }); @@ -158,7 +168,7 @@ void runTests({ final frame = event.topFrame!.index!; final instanceRef = await getInstanceRef(frame, 'record'); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordClass); @@ -190,8 +200,11 @@ void runTests({ 'cat': 'Vasya', }); expect(await getFields(instanceRef, offset: 1), {'cat': 'Vasya'}); - expect(await getFields(instanceRef, offset: 2), {}); - expect(await getFields(instanceRef, offset: 0, count: 0), {}); + expect(await getFields(instanceRef, offset: 2), {}); + expect( + await getFields(instanceRef, offset: 0, count: 0), + {}, + ); expect(await getFields(instanceRef, offset: 0, count: 1), {1: true}); expect(await getFields(instanceRef, offset: 0, count: 2), { 1: true, @@ -201,7 +214,10 @@ void runTests({ 1: true, 'cat': 'Vasya', }); - expect(await getFields(instanceRef, offset: 2, count: 5), {}); + expect( + await getFields(instanceRef, offset: 2, count: 5), + {}, + ); }); }); @@ -225,7 +241,7 @@ void runTests({ final frame = event.topFrame!.index!; final instanceRef = await getInstanceRef(frame, 'record'); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordClass); @@ -273,8 +289,11 @@ void runTests({ expect(await getFields(instanceRef, offset: 2), { 3: {'a': 1, 'b': 5}, }); - expect(await getFields(instanceRef, offset: 3), {}); - expect(await getFields(instanceRef, offset: 0, count: 0), {}); + expect(await getFields(instanceRef, offset: 3), {}); + expect( + await getFields(instanceRef, offset: 0, count: 0), + {}, + ); expect(await getFields(instanceRef, offset: 0, count: 1), {1: true}); expect(await getFields(instanceRef, offset: 0, count: 2), { 1: true, @@ -285,7 +304,10 @@ void runTests({ 2: 3, 3: {'a': 1, 'b': 5}, }); - expect(await getFields(instanceRef, offset: 3, count: 5), {}); + expect( + await getFields(instanceRef, offset: 3, count: 5), + {}, + ); }); }); @@ -313,7 +335,7 @@ void runTests({ final frame = event.topFrame!.index!; final instanceRef = await getInstanceRef(frame, 'record'); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordClass); @@ -361,8 +383,11 @@ void runTests({ expect(await getFields(instanceRef, offset: 2), { 'array': {'a': 1, 'b': 5}, }); - expect(await getFields(instanceRef, offset: 3), {}); - expect(await getFields(instanceRef, offset: 0, count: 0), {}); + expect(await getFields(instanceRef, offset: 3), {}); + expect( + await getFields(instanceRef, offset: 0, count: 0), + {}, + ); expect(await getFields(instanceRef, offset: 0, count: 1), {1: true}); expect(await getFields(instanceRef, offset: 0, count: 2), { 1: true, @@ -373,7 +398,10 @@ void runTests({ 2: 3, 'array': {'a': 1, 'b': 5}, }); - expect(await getFields(instanceRef, offset: 3, count: 5), {}); + expect( + await getFields(instanceRef, offset: 3, count: 5), + {}, + ); }); }); @@ -401,7 +429,7 @@ void runTests({ final frame = event.topFrame!.index!; final instanceRef = await getInstanceRef(frame, 'record'); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordClass); @@ -438,8 +466,11 @@ void runTests({ expect(await getFields(instanceRef, offset: 1), { 2: {1: false, 2: 5}, }); - expect(await getFields(instanceRef, offset: 2), {}); - expect(await getFields(instanceRef, offset: 0, count: 0), {}); + expect(await getFields(instanceRef, offset: 2), {}); + expect( + await getFields(instanceRef, offset: 0, count: 0), + {}, + ); expect(await getFields(instanceRef, offset: 0, count: 1), {1: true}); expect(await getFields(instanceRef, offset: 0, count: 2), { 1: true, @@ -449,7 +480,10 @@ void runTests({ 1: true, 2: {1: false, 2: 5}, }); - expect(await getFields(instanceRef, offset: 2, count: 5), {}); + expect( + await getFields(instanceRef, offset: 2, count: 5), + {}, + ); }); }); @@ -472,7 +506,7 @@ void runTests({ final frame = event.topFrame!.index!; final instanceRef = await getInstanceRef(frame, 'record'); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordClass); @@ -515,8 +549,11 @@ void runTests({ expect(await getFields(instanceRef, offset: 1, count: 2), { 'inner': {1: false, 2: 5}, }); - expect(await getFields(instanceRef, offset: 2), {}); - expect(await getFields(instanceRef, offset: 0, count: 0), {}); + expect(await getFields(instanceRef, offset: 2), {}); + expect( + await getFields(instanceRef, offset: 0, count: 0), + {}, + ); expect(await getFields(instanceRef, offset: 0, count: 1), {1: true}); expect(await getFields(instanceRef, offset: 0, count: 2), { 1: true, @@ -526,7 +563,10 @@ void runTests({ 1: true, 'inner': {1: false, 2: 5}, }); - expect(await getFields(instanceRef, offset: 2, count: 5), {}); + expect( + await getFields(instanceRef, offset: 2, count: 5), + {}, + ); }); }); diff --git a/dwds/test/instances/common/record_type_inspection_common.dart b/dwds/test/instances/common/record_type_inspection_common.dart index 5ee5d3517..4ae3daf96 100644 --- a/dwds/test/instances/common/record_type_inspection_common.dart +++ b/dwds/test/instances/common/record_type_inspection_common.dart @@ -26,7 +26,10 @@ void runTests({ late String isolateId; late ScriptRef mainScript; - Future onBreakPoint(breakPointId, body) => testInspector.onBreakPoint( + Future onBreakPoint( + String breakPointId, + Future Function(Event) body, + ) => testInspector.onBreakPoint( stream, isolateId, mainScript, @@ -34,9 +37,10 @@ void runTests({ body, ); - Future getObject(instanceId) => service.getObject(isolateId, instanceId); + Future getObject(String instanceId) => + service.getObject(isolateId, instanceId); - Future getInstanceRef(frame, expression) => + Future getInstanceRef(int frame, String expression) => testInspector.getInstanceRef(isolateId, frame, expression); Future> getDisplayedFields(InstanceRef ref) => @@ -96,7 +100,7 @@ void runTests({ expect(instanceRef, matchRecordTypeInstanceRef(length: 2)); expect(await getObject(instanceId), matchRecordTypeInstance(length: 2)); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordTypeClass); }); }); @@ -155,7 +159,7 @@ void runTests({ expect(instanceRef, matchRecordTypeInstanceRef(length: 3)); expect(await getObject(instanceId), matchRecordTypeInstance(length: 3)); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordTypeClass); }); }); @@ -219,7 +223,7 @@ void runTests({ expect(instanceRef, matchRecordTypeInstanceRef(length: 3)); expect(await getObject(instanceId), matchRecordTypeInstance(length: 3)); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordTypeClass); }); }); @@ -284,7 +288,7 @@ void runTests({ expect(instanceRef, matchRecordTypeInstanceRef(length: 2)); expect(await getObject(instanceId), matchRecordTypeInstance(length: 2)); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordTypeClass); }); }); @@ -358,7 +362,7 @@ void runTests({ expect(instanceRef, matchRecordTypeInstanceRef(length: 2)); expect(instance, matchRecordTypeInstance(length: 2)); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordTypeClass); }); }); @@ -409,7 +413,7 @@ void runTests({ final frame = event.topFrame!.index!; final instanceRef = await getInstanceRef(frame, 'record.runtimeType'); final instance = await getObject(instanceRef.id!); - final typeClassId = instance.classRef!.id; + final typeClassId = instance.classRef!.id!; expect(await getObject(typeClassId), matchRecordTypeClass); diff --git a/dwds/test/instances/common/test_inspector.dart b/dwds/test/instances/common/test_inspector.dart index 0dc201e3d..52e2dbe19 100644 --- a/dwds/test/instances/common/test_inspector.dart +++ b/dwds/test/instances/common/test_inspector.dart @@ -49,7 +49,7 @@ class TestInspector { } } - Future> getFields( + Future> getFields( String isolateId, InstanceRef instanceRef, { int? offset, @@ -80,7 +80,7 @@ class TestInspector { final associations = instance.associations; final elements = instance.elements; - Map? fieldRefs; + Map? fieldRefs; if (fields != null) { fieldRefs = _boundFieldsToMap(fields); } else if (associations != null) { @@ -98,7 +98,7 @@ class TestInspector { return fieldRefs; } - final fieldValues = {}; + final fieldValues = {}; for (final p in fieldRefs.entries) { fieldValues[p.key] = _getValue(p.value) ?? @@ -174,34 +174,34 @@ class TestInspector { await service.invoke(isolateId, instanceId, 'toString', []) as InstanceRef; - Future> getDisplayedFields( + Future> getDisplayedFields( String isolateId, InstanceRef ref, ) async { final fieldRefs = - await getFields(isolateId, ref, depth: 1) as Map; + await getFields(isolateId, ref, depth: 1) as Map; Future toStringValue(InstanceRef ref) async => ref.valueAsString ?? (await getDisplayedRef(isolateId, ref.id!)).valueAsString; final fields = await Future.wait(fieldRefs.values.map(toStringValue)); - return Map.fromIterables(fieldRefs.keys, fields); + return Map.fromIterables(fieldRefs.keys, fields); } - Future> getDisplayedGetters( + Future> getDisplayedGetters( String isolateId, InstanceRef ref, ) async { final fieldRefs = - await getGetters(isolateId, ref) as Map; + await getGetters(isolateId, ref) as Map; Future toStringValue(InstanceRef ref) async => ref.valueAsString ?? (await getDisplayedRef(isolateId, ref.id!)).valueAsString; final fields = await Future.wait(fieldRefs.values.map(toStringValue)); - return Map.fromIterables(fieldRefs.keys, fields); + return Map.fromIterables(fieldRefs.keys, fields); } Future> getElements( @@ -240,8 +240,8 @@ class TestInspector { /// A limit on the number of stops to record. /// - /// The program will not be resumed after the length of [recordedStops] - /// becomes [numStops]. + /// The program will not be resumed after the length of recordedStops + /// becomes numStops. int numStops, ) async { final completer = Completer(); @@ -271,20 +271,23 @@ class TestInspector { Map _associationsToMap( Iterable associations, -) => Map.fromEntries( - associations.map((e) => MapEntry(e.key.valueAsString, e.value)), +) => Map.fromEntries( + associations.map( + (e) => + MapEntry((e.key as InstanceRef).valueAsString!, e.value as InstanceRef), + ), ); -Map _boundFieldsToMap(Iterable fields) => +Map _boundFieldsToMap(Iterable fields) => Map.fromEntries( - fields.where((e) => e.name != null).map((e) => MapEntry(e.name, e.value)), + fields + .where((e) => e.name != null) + .map((e) => MapEntry(e.name, e.value as InstanceRef)), ); -Map _elementsToMap(List fields) => +Map _elementsToMap(List fields) => Map.fromEntries( - fields - .where((e) => e != null) - .map((e) => MapEntry(fields.indexOf(e), e!)), + fields.nonNulls.map((e) => MapEntry(fields.indexOf(e), e as InstanceRef)), ); Matcher matchRecordInstanceRef({required int length}) => isA() @@ -297,7 +300,7 @@ Matcher matchRecordTypeInstanceRef({required int length}) => isA() .having((e) => e.length, 'length', length) .having((e) => e.classRef!, 'classRef', matchRecordTypeClassRef); -Matcher matchTypeInstanceRef(dynamic name) => isA() +Matcher matchTypeInstanceRef(Object? name) => isA() .having((e) => e.kind, 'kind', InstanceKind.kType) .having((e) => e.name, 'type ref name', name) .having((e) => e.classRef, 'classRef', matchTypeClassRef); @@ -307,12 +310,12 @@ Matcher matchPrimitiveInstanceRef({required String kind}) => Matcher matchPrimitiveInstance({ required String kind, - required dynamic value, + required Object? value, }) => isA() .having((e) => e.kind, 'kind', kind) .having(_getValue, 'value', value); -Matcher matchPlainInstance({required libraryId, required String type}) => +Matcher matchPlainInstance({required String libraryId, required String type}) => isA() .having((e) => e.kind, 'kind', InstanceKind.kPlainInstance) .having( @@ -321,7 +324,7 @@ Matcher matchPlainInstance({required libraryId, required String type}) => matchClassRef(name: type, libraryId: libraryId), ); -Matcher matchListInstance({required dynamic type}) => isA() +Matcher matchListInstance({required String type}) => isA() .having((e) => e.kind, 'kind', InstanceKind.kList) .having((e) => e.classRef, 'classRef', matchListClassRef(type)); @@ -343,10 +346,10 @@ Matcher matchRecordTypeInstance({required int length}) => isA() .having((e) => e.length, 'length', length) .having((e) => e.classRef, 'classRef', matchRecordTypeClassRef); -Matcher matchTypeStringInstance(dynamic name) => +Matcher matchTypeStringInstance(Object? name) => matchPrimitiveInstance(kind: InstanceKind.kString, value: name); -Matcher matchTypeInstance(dynamic name) => isA() +Matcher matchTypeInstance(Object? name) => isA() .having((e) => e.kind, 'kind', InstanceKind.kType) .having((e) => e.name, 'type name', name) .having((e) => e.classRef, 'classRef', matchTypeClassRef); @@ -368,7 +371,7 @@ Matcher matchRecordTypeClass = anyOf( matchClass(name: matchRecordTypeClassName, libraryId: _dartRuntimeLibrary), ); -Matcher matchClass({dynamic name, String? libraryId}) => isA() +Matcher matchClass({Object? name, String? libraryId}) => isA() .having((e) => e.name, 'class name', name) .having((e) => e.library, 'library', matchLibraryRef(libraryId)); @@ -397,11 +400,11 @@ Matcher matchMapClassRef(String type) => Matcher matchSetClassRef(String type) => matchClassRef(name: type, libraryId: _dartJsHelperLibrary); -Matcher matchClassRef({dynamic name, dynamic libraryId}) => isA() +Matcher matchClassRef({Object? name, Object? libraryId}) => isA() .having((e) => e.name, 'class ref name', name) .having((e) => e.library, 'library', matchLibraryRef(libraryId)); -Matcher matchLibraryRef(dynamic libraryId) => isA() +Matcher matchLibraryRef(Object? libraryId) => isA() .having((e) => e.name, 'library name', libraryId) .having((e) => e.id, 'id', libraryId) .having((e) => e.uri, 'uri', libraryId); diff --git a/dwds/test/instances/common/type_inspection_common.dart b/dwds/test/instances/common/type_inspection_common.dart index 46ce1d081..76e112064 100644 --- a/dwds/test/instances/common/type_inspection_common.dart +++ b/dwds/test/instances/common/type_inspection_common.dart @@ -27,7 +27,10 @@ void runTests({ late String isolateId; late ScriptRef mainScript; - Future onBreakPoint(breakPointId, body) => testInspector.onBreakPoint( + Future onBreakPoint( + String breakPointId, + Future Function(Event) body, + ) => testInspector.onBreakPoint( stream, isolateId, mainScript, @@ -35,22 +38,23 @@ void runTests({ body, ); - Future getObject(instanceId) => service.getObject(isolateId, instanceId); + Future getObject(String instanceId) => + service.getObject(isolateId, instanceId); - Future> getDisplayedFields(instanceRef) => + Future> getDisplayedFields(InstanceRef instanceRef) => testInspector.getDisplayedFields(isolateId, instanceRef); - Future> getDisplayedGetters(instanceRef) => + Future> getDisplayedGetters(InstanceRef instanceRef) => testInspector.getDisplayedGetters(isolateId, instanceRef); - Future getInstanceRef(frame, expression) => + Future getInstanceRef(int frame, String expression) => testInspector.getInstanceRef(isolateId, frame, expression); Future> getFields( - instanceRef, { - offset, - count, - depth = -1, + InstanceRef instanceRef, { + int? offset, + int? count, + int depth = -1, }) => testInspector.getFields( isolateId, instanceRef, @@ -62,9 +66,9 @@ void runTests({ Future> getElements(String instanceId) => testInspector.getElements(isolateId, instanceId); - final matchTypeObjectFields = {}; + final matchTypeObjectFields = {}; - final matchDisplayedTypeObjectFields = {}; + final matchDisplayedTypeObjectFields = {}; final matchDisplayedTypeObjectGetters = { 'hashCode': matches('[0-9]*'), @@ -114,7 +118,7 @@ void runTests({ final instance = await getObject(instanceId); expect(instance, matchTypeInstance('String')); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchTypeClass); expect(await getFields(instanceRef, depth: 1), matchTypeObjectFields); expect( @@ -146,7 +150,7 @@ void runTests({ final instance = await getObject(instanceId); expect(instance, matchTypeInstance('int')); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchTypeClass); expect(await getFields(instanceRef, depth: 1), matchTypeObjectFields); expect( @@ -178,7 +182,7 @@ void runTests({ final instance = await getObject(instanceId); expect(instance, matchTypeInstance('List')); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchTypeClass); expect(await getFields(instanceRef, depth: 1), matchTypeObjectFields); expect( @@ -205,7 +209,7 @@ void runTests({ final instance = await getObject(instanceId); expect(instance, matchTypeInstance('IdentityMap')); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchTypeClass); expect(await getFields(instanceRef, depth: 1), matchTypeObjectFields); expect( @@ -240,7 +244,7 @@ void runTests({ final instance = await getObject(instanceId); expect(instance, matchTypeInstance('IdentitySet')); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchTypeClass); expect(await getFields(instanceRef, depth: 1), matchTypeObjectFields); expect( @@ -276,7 +280,7 @@ void runTests({ matchTypeInstance('String'), ]); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchRecordTypeClass); expect(await getFields(instanceRef, depth: 2), { 1: matchTypeObjectFields, @@ -311,7 +315,7 @@ void runTests({ final instance = await getObject(instanceId); expect(instance, matchTypeInstance('_Uri')); - final classId = instanceRef.classRef!.id; + final classId = instanceRef.classRef!.id!; expect(await getObject(classId), matchTypeClass); expect(await getFields(instanceRef, depth: 1), matchTypeObjectFields); expect( diff --git a/dwds/test/load_strategy_test.dart b/dwds/test/load_strategy_test.dart index bb104702e..c33ee7773 100644 --- a/dwds/test/load_strategy_test.dart +++ b/dwds/test/load_strategy_test.dart @@ -59,7 +59,7 @@ void main() { group('When default build settings defined', () { late final strategy = FakeStrategy( FakeAssetReader(), - buildSettings: TestBuildSettings.dart(), + buildSettings: const TestBuildSettings.dart(), ); test('uses the default app entrypoint', () { diff --git a/dwds/test/metadata/class_test.dart b/dwds/test/metadata/class_test.dart index 6bf247cb8..f2caa2702 100644 --- a/dwds/test/metadata/class_test.dart +++ b/dwds/test/metadata/class_test.dart @@ -10,7 +10,7 @@ import 'package:test/test.dart'; void main() { test('Gracefully handles invalid length objects', () async { - ClassMetaData createMetadata(dynamic length) => ClassMetaData( + ClassMetaData createMetadata(Object? length) => ClassMetaData( length: length, runtimeKind: RuntimeObjectKind.object, classRef: classRefForUnknown, diff --git a/dwds/test/package_uri_mapper_test.dart b/dwds/test/package_uri_mapper_test.dart index 2ad85d089..8d8e8957a 100644 --- a/dwds/test/package_uri_mapper_test.dart +++ b/dwds/test/package_uri_mapper_test.dart @@ -21,7 +21,7 @@ void main() { for (final useDebuggerModuleNames in [true, false]) { group('Package uri mapper with debugger module names: ' ' $useDebuggerModuleNames |', () { - final fileSystem = LocalFileSystem(); + final fileSystem = const LocalFileSystem(); final packageUri = Uri( scheme: 'package', diff --git a/dwds/test/puppeteer/extension_common.dart b/dwds/test/puppeteer/extension_common.dart index 11b28962e..d95036825 100644 --- a/dwds/test/puppeteer/extension_common.dart +++ b/dwds/test/puppeteer/extension_common.dart @@ -12,7 +12,7 @@ import 'package:dwds/data/extension_request.dart'; import 'package:dwds/src/servers/extension_backend.dart'; import 'package:dwds/src/utilities/server.dart'; import 'package:path/path.dart' as p; -import 'package:puppeteer/puppeteer.dart' hide Response; +import 'package:puppeteer/puppeteer.dart' hide Request, Response; import 'package:shelf/shelf.dart'; import 'package:shelf_static/shelf_static.dart'; import 'package:test/test.dart'; @@ -396,7 +396,8 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { await browser.close(); }); test( - 'isFlutterApp=$isFlutterApp and isInternalBuild=false are saved in storage', + 'isFlutterApp=$isFlutterApp and isInternalBuild=false are saved in ' + 'storage', () async { final appUrl = context.appUrl; // Navigate to the Dart app: @@ -505,7 +506,8 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { await browser.close(); }); test( - 'isFlutterApp=$isFlutterApp and isInternalBuild=true are saved in storage', + 'isFlutterApp=$isFlutterApp and isInternalBuild=true are saved in ' + 'storage', () async { // Verify that we have debug info for the Dart app: await workerEvalDelay(); @@ -529,9 +531,9 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { 'the correct extension panels are added to Chrome DevTools', () async { final chromeDevToolsPage = await getChromeDevToolsPage(browser); - // There are no hooks for when a panel is added to Chrome DevTools, - // therefore we rely on a slight delay: - await Future.delayed(Duration(seconds: 1)); + // There are no hooks for when a panel is added to Chrome + // DevTools, therefore we rely on a slight delay: + await Future.delayed(const Duration(seconds: 1)); if (isFlutterApp) { await _tabLeft(chromeDevToolsPage); final inspectorPanelElement = await _getPanelElement( @@ -555,16 +557,18 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { await _takeScreenshot( chromeDevToolsPage, screenshotName: - 'debuggerPanelLandingPage_${isFlutterApp ? 'flutterApp' : 'dartApp'}', + 'debuggerPanelLandingPage_' + '${isFlutterApp ? 'flutterApp' : 'dartApp'}', ); }, ); - test('Dart DevTools is embedded for debug session lifetime', () async { + test('Dart DevTools is embedded for debug session ' + 'lifetime', () async { final chromeDevToolsPage = await getChromeDevToolsPage(browser); // There are no hooks for when a panel is added to Chrome DevTools, // therefore we rely on a slight delay: - await Future.delayed(Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); // Navigate to the Dart Debugger panel: await _tabLeft(chromeDevToolsPage); if (isFlutterApp) { @@ -603,7 +607,8 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { await _takeScreenshot( chromeDevToolsPage, screenshotName: - 'debuggerPanelDisconnected_${isFlutterApp ? 'flutterApp' : 'dartApp'}', + 'debuggerPanelDisconnected_' + '${isFlutterApp ? 'flutterApp' : 'dartApp'}', ); // Navigate back to the Dart app: await appTab.goto(context.appUrl, wait: Until.domContentLoaded); @@ -624,57 +629,55 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { // origin, and being able to connect to the embedded Dart app. // See https://github.com/dart-lang/webdev/issues/1779 - test( - 'The Dart DevTools IFRAME has the correct query parameters and path', - () async { - final chromeDevToolsPage = await getChromeDevToolsPage(browser); - // There are no hooks for when a panel is added to Chrome DevTools, - // therefore we rely on a slight delay: - await Future.delayed(Duration(seconds: 1)); - // Navigate to the Dart Debugger panel: + test('The Dart DevTools IFRAME has the correct query ' + 'parameters and path', () async { + final chromeDevToolsPage = await getChromeDevToolsPage(browser); + // There are no hooks for when a panel is added to Chrome DevTools, + // therefore we rely on a slight delay: + await Future.delayed(const Duration(seconds: 1)); + // Navigate to the Dart Debugger panel: + await _tabLeft(chromeDevToolsPage); + if (isFlutterApp) { await _tabLeft(chromeDevToolsPage); - if (isFlutterApp) { - await _tabLeft(chromeDevToolsPage); - } - await _clickLaunchButton(browser, panel: Panel.debugger); - // Expect the Dart DevTools IFRAME to be added: - final devToolsUrlFragment = - 'ide=ChromeDevTools&embed=true&page=debugger'; - final iframeTarget = await browser.waitForTarget( - (target) => target.url.contains(devToolsUrlFragment), - ); - final iframeUrl = iframeTarget.url; - // Expect the correct query parameters to be on the IFRAME url: - final uri = Uri.parse(iframeUrl); - final queryParameters = uri.queryParameters; - expect( - queryParameters.keys, - unorderedMatches([ - 'uri', - 'ide', - 'embed', - 'page', - 'backgroundColor', - ]), - ); - expect(queryParameters, containsPair('ide', 'ChromeDevTools')); - expect(queryParameters, containsPair('uri', isNotEmpty)); - expect(queryParameters, containsPair('page', isNotEmpty)); - expect( - queryParameters, - containsPair('backgroundColor', isNotEmpty), - ); - expect(uri.path, equals('/')); - }, - ); + } + await _clickLaunchButton(browser, panel: Panel.debugger); + // Expect the Dart DevTools IFRAME to be added: + final devToolsUrlFragment = + 'ide=ChromeDevTools&embed=true&page=debugger'; + final iframeTarget = await browser.waitForTarget( + (target) => target.url.contains(devToolsUrlFragment), + ); + final iframeUrl = iframeTarget.url; + // Expect the correct query parameters to be on the IFRAME url: + final uri = Uri.parse(iframeUrl); + final queryParameters = uri.queryParameters; + expect( + queryParameters.keys, + unorderedMatches([ + 'uri', + 'ide', + 'embed', + 'page', + 'backgroundColor', + ]), + ); + expect(queryParameters, containsPair('ide', 'ChromeDevTools')); + expect(queryParameters, containsPair('uri', isNotEmpty)); + expect(queryParameters, containsPair('page', isNotEmpty)); + expect( + queryParameters, + containsPair('backgroundColor', isNotEmpty), + ); + expect(uri.path, equals('/')); + }); test( 'Trying to debug a page with multiple Dart apps shows warning', () async { final chromeDevToolsPage = await getChromeDevToolsPage(browser); - // There are no hooks for when a panel is added to Chrome DevTools, - // therefore we rely on a slight delay: - await Future.delayed(Duration(seconds: 1)); + // There are no hooks for when a panel is added to Chrome + // DevTools, therefore we rely on a slight delay: + await Future.delayed(const Duration(seconds: 1)); // Navigate to the Dart Debugger panel: await _tabLeft(chromeDevToolsPage); if (isFlutterApp) { @@ -691,7 +694,7 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { isFalse, ); // Set the 'data-multiple-dart-apps' attribute on the DOM. - await appTab.evaluate(_setMultipleAppsAttributeJs); + await appTab.evaluate(_setMultipleAppsAttributeJs); final appTabId = await _getCurrentTabId( worker: worker, backgroundPage: backgroundPage, @@ -714,7 +717,8 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { await _takeScreenshot( chromeDevToolsPage, screenshotName: - 'debuggerMultipleAppsDetected_${isFlutterApp ? 'flutterApp' : 'dartApp'}', + 'debuggerMultipleAppsDetected_' + '${isFlutterApp ? 'flutterApp' : 'dartApp'}', ); expect( warningMsg, @@ -748,7 +752,7 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { ); browser = await puppeteer.launch( headless: false, - timeout: Duration(seconds: 60), + timeout: const Duration(seconds: 60), args: [ '--load-extension=$extensionPath', '--disable-extensions-except=$extensionPath', @@ -872,7 +876,7 @@ Future _clickLaunchButton(Browser browser, {required Panel panel}) async { elementSelector: '#launchDebugConnectionButton', ); // Slight delay to guarantee button is clickable: - await Future.delayed(Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); await launchButton!.click(); return true; } catch (_) { @@ -943,16 +947,18 @@ Future _fetchStorageObj( Page? backgroundPage, }) async { final json = await retryFnAsync(() async { - final storageObj = await evaluate( - _fetchStorageObjJs( - storageKey, - // Only local storage exists for MV2: - storageArea: worker != null ? storageArea : 'local', - ), - worker: worker, - backgroundPage: backgroundPage, - ); - return storageObj[storageKey]; + final storageObj = + (await evaluate( + _fetchStorageObjJs( + storageKey, + // Only local storage exists for MV2: + storageArea: worker != null ? storageArea : 'local', + ), + worker: worker, + backgroundPage: backgroundPage, + )) + as Map; + return storageObj[storageKey]!; }); if (T == String) return json as T; return serializers.deserialize(jsonDecode(json)) as T; @@ -1014,7 +1020,7 @@ Future _takeScreenshot( // coerced into having a "page" type, there doesn't seem to be a way to verify // that the DOM has been loaded. Therefore we use a slight delay before taking // a screenshot. See https://github.com/puppeteer/puppeteer/issues/9371. - await Future.delayed(Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); final screenshot = await page.screenshot(); final screenshotPath = p.join( 'test', @@ -1037,7 +1043,7 @@ Future _fakeServer({ return server; } -Response _fakeAuthHandler(request) { +Response _fakeAuthHandler(Request request) { if (request.url.path == authenticationPath) { return Response.ok(authenticationResponse); } diff --git a/dwds/test/puppeteer/test_utils.dart b/dwds/test/puppeteer/test_utils.dart index a1769eb58..8661d701f 100644 --- a/dwds/test/puppeteer/test_utils.dart +++ b/dwds/test/puppeteer/test_utils.dart @@ -14,9 +14,9 @@ import '../fixtures/utilities.dart'; enum ConsoleSource { background, devTools, worker } -final _backgroundLogs = []; -final _devToolsLogs = []; -final _workerLogs = []; +final _backgroundLogs = []; +final _devToolsLogs = []; +final _workerLogs = []; Future buildDebugExtension({required bool isMV3}) async { final extensionDir = absolutePath(pathFromDwds: 'debug_extension'); @@ -49,7 +49,7 @@ Future setUpExtensionTest( ? TestDebugSettings.withDevToolsLaunch( context, ).copyWith(enableDebugExtension: true, useSse: useSse) - : TestDebugSettings.noDevToolsLaunch().copyWith( + : const TestDebugSettings.noDevToolsLaunch().copyWith( enableDebugExtension: true, useSse: useSse, ), @@ -57,7 +57,7 @@ Future setUpExtensionTest( return await puppeteer.launch( devTools: openChromeDevTools, headless: false, - timeout: Duration(seconds: 60), + timeout: const Duration(seconds: 60), args: [ '--load-extension=$extensionPath', '--disable-extensions-except=$extensionPath', @@ -160,8 +160,7 @@ Future clickOnExtensionIcon({ // Note: The following delay is required to reduce flakiness. It makes // sure the service worker execution context is ready. Future workerEvalDelay() async { - await Future.delayed(Duration(seconds: 1)); - return; + await Future.delayed(const Duration(seconds: 1)); } Future navigateToPage( diff --git a/dwds/test/refresh_test.dart b/dwds/test/refresh_test.dart index 3d7cf927f..7e7e9c86f 100644 --- a/dwds/test/refresh_test.dart +++ b/dwds/test/refresh_test.dart @@ -40,7 +40,7 @@ void main() { test('can add and remove after a refresh', () async { final stream = service.onEvent('Isolate'); // Wait for the page to be fully loaded before refreshing. - await Future.delayed(const Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); // Now wait for the shutdown event. final exitEvent = stream.firstWhere( (e) => e.kind != EventKind.kIsolateExit, diff --git a/dwds/test/run_request_test.dart b/dwds/test/run_request_test.dart index d5e00cbf2..48a04a81f 100644 --- a/dwds/test/run_request_test.dart +++ b/dwds/test/run_request_test.dart @@ -31,7 +31,10 @@ void main() { setUp(() async { setCurrentLogWriter(debug: debug); await context.setUp( - testSettings: TestSettings(autoRun: false, verboseCompiler: debug), + testSettings: const TestSettings( + autoRun: false, + verboseCompiler: debug, + ), ); service = context.service; }); @@ -45,7 +48,7 @@ void main() { final isolate = await service.getIsolate(vm.isolates!.first.id!); expect(isolate.pauseEvent!.kind, EventKind.kPauseStart); final stream = service.onEvent('Debug'); - final resumeCompleter = Completer(); + final resumeCompleter = Completer(); // The underlying stream is a broadcast stream so we need to add a // listener before calling resume so that we don't miss events. unawaited( @@ -67,13 +70,13 @@ void main() { await stream.firstWhere((event) => event.kind == EventKind.kResume); expect(isolate.pauseEvent!.kind, EventKind.kResume); }); - }, timeout: Timeout.factor(2)); + }, timeout: const Timeout.factor(2)); group('while debugger is not attached', () { setUp(() async { setCurrentLogWriter(debug: debug); await context.setUp( - testSettings: TestSettings(autoRun: false, waitToDebug: true), + testSettings: const TestSettings(autoRun: false, waitToDebug: true), ); }); diff --git a/dwds/test/sdk_configuration_test.dart b/dwds/test/sdk_configuration_test.dart index bf2901dab..3bf2b374b 100644 --- a/dwds/test/sdk_configuration_test.dart +++ b/dwds/test/sdk_configuration_test.dart @@ -26,13 +26,13 @@ void main() { group('Basic configuration', () { test('Can validate default configuration layout', () async { final defaultConfiguration = - await DefaultSdkConfigurationProvider().configuration; + await const DefaultSdkConfigurationProvider().configuration; defaultConfiguration.validateSdkDir(); defaultConfiguration.validateSummaries(); }); test('Cannot validate an empty configuration layout', () async { - final emptyConfiguration = SdkConfiguration.empty(); + final emptyConfiguration = const SdkConfiguration.empty(); expect(emptyConfiguration.validateSdkDir, _throwsDoesNotExistException); expect(emptyConfiguration.validate, _throwsDoesNotExistException); }); @@ -52,7 +52,7 @@ void main() { test('Can validate existing configuration layout', () async { final defaultSdkConfiguration = - await DefaultSdkConfigurationProvider().configuration; + await const DefaultSdkConfigurationProvider().configuration; final sdkDirectory = outputDir.path; final sdkLayout = FakeSdkLayout(sdkDirectory); diff --git a/dwds/test/skip_list_test.dart b/dwds/test/skip_list_test.dart index 0707fdc0b..354ed5612 100644 --- a/dwds/test/skip_list_test.dart +++ b/dwds/test/skip_list_test.dart @@ -107,16 +107,16 @@ void main() { } void _validateRange( - Map range, + Map range, int startLine, int startColumn, int endLine, int endColumn, ) { - final start = range['start']; + final start = range['start']! as Map; expect(start['lineNumber'], startLine); expect(start['columnNumber'], startColumn); - final end = range['end']; + final end = range['end']! as Map; expect(end['lineNumber'], endLine); expect(end['columnNumber'], endColumn); } diff --git a/dwds/test/utilities_test.dart b/dwds/test/utilities_test.dart index 8b9f42881..83231ea95 100644 --- a/dwds/test/utilities_test.dart +++ b/dwds/test/utilities_test.dart @@ -15,7 +15,7 @@ void main() { group('wrapInErrorHandlerAsync', () { test('returns future success value if callback succeeds', () async { Future successCallback() async { - await Future.delayed(Duration(milliseconds: 500)); + await Future.delayed(const Duration(milliseconds: 500)); return true; } @@ -28,7 +28,7 @@ void main() { test('throws RPCError if callback throws RPCError', () async { Future rpcErrorCallback() async { - await Future.delayed(Duration(milliseconds: 500)); + await Future.delayed(const Duration(milliseconds: 500)); throw RPCError( 'rpcErrorCallback', RPCErrorKind.kInvalidRequest.code, @@ -46,7 +46,7 @@ void main() { 'throws SentinelException if callback throws SentinelException', () async { Future sentinelExceptionCallback() async { - await Future.delayed(Duration(milliseconds: 500)); + await Future.delayed(const Duration(milliseconds: 500)); throw SentinelException.parse('sentinelExceptionCallback', { 'message': 'a sentinel exception', }); @@ -64,7 +64,7 @@ void main() { test('throws RPCError if callback throws other error type', () async { Future exceptionCallback() async { - await Future.delayed(Duration(milliseconds: 500)); + await Future.delayed(const Duration(milliseconds: 500)); throw Exception('An unexpected exception'); } @@ -75,7 +75,8 @@ void main() { expect( error, isRPCErrorWithMessage( - 'Unexpected DWDS error for exceptionCallback: Exception: An unexpected exception', + 'Unexpected DWDS error for exceptionCallback: Exception: An ' + 'unexpected exception', ), ); } diff --git a/dwds/test/variable_scope_test.dart b/dwds/test/variable_scope_test.dart index 14bd0cf0d..6b3ab1227 100644 --- a/dwds/test/variable_scope_test.dart +++ b/dwds/test/variable_scope_test.dart @@ -28,7 +28,9 @@ void main() { setUpAll(() async { setCurrentLogWriter(debug: debug); - await context.setUp(testSettings: TestSettings(verboseCompiler: debug)); + await context.setUp( + testSettings: const TestSettings(verboseCompiler: debug), + ); }); tearDownAll(() async { @@ -287,8 +289,8 @@ void main() { ); expect(parameter.value, matches(RegExp(r'\d+ world'))); final ticks = await debugger.evaluateJsOnCallFrameIndex(1, 'ticks'); - // We don't know how many ticks there were before we stopped, but it should - // be a positive number. + // We don't know how many ticks there were before we stopped, but it + // should be a positive number. expect(ticks.value, isPositive); }); }); diff --git a/dwds/test/web/batched_stream_test.dart b/dwds/test/web/batched_stream_test.dart index 1603256fc..78e824999 100644 --- a/dwds/test/web/batched_stream_test.dart +++ b/dwds/test/web/batched_stream_test.dart @@ -35,7 +35,7 @@ void main() { final inputAdded = controller.sink.addStream(inputController.stream); batchOne.forEach(inputController.sink.add); - await Future.delayed(delay); + await Future.delayed(delay); batchTwo.forEach(inputController.sink.add); await inputController.close(); @@ -63,7 +63,7 @@ void main() { final input = List.generate(size, (index) => index); for (final e in input) { inputController.sink.add(e); - await Future.delayed(delay); + await Future.delayed(delay); } await inputController.close(); diff --git a/dwds/web/client.dart b/dwds/web/client.dart index 5f18df50f..bb3629dcd 100644 --- a/dwds/web/client.dart +++ b/dwds/web/client.dart @@ -215,9 +215,9 @@ Future? main() { }, onError: (error) { // An error is propagated on a full page reload as Chrome presumably - // forces the SSE connection to close in a bad state. This does not cause - // any adverse effects so simply swallow this error as to not print the - // misleading unhandled error message. + // forces the SSE connection to close in a bad state. This does not + // cause any adverse effects so simply swallow this error as to not + // print the misleading unhandled error message. }, ); @@ -274,6 +274,7 @@ $stackTrace void _trySendEvent(StreamSink sink, T serialized) { try { sink.add(serialized); + // ignore: avoid_catching_errors } on StateError catch (_) { // An error is propagated on a full page reload as Chrome presumably // forces the SSE connection to close in a bad state. @@ -377,9 +378,8 @@ Future _authenticateUser(String authUrl) async { return responseText.contains('Dart Debug Authentication Success!'); } -void _sendResponse( +void _sendHotReloadResponse( StreamSink clientSink, - T Function(void Function(dynamic)) builder, String requestId, { bool success = true, String? errorMessage, @@ -388,7 +388,7 @@ void _sendResponse( clientSink, jsonEncode( serializers.serialize( - builder((b) { + HotReloadResponse((HotReloadResponseBuilder b) { b.id = requestId; b.success = success; if (errorMessage != null) b.errorMessage = errorMessage; @@ -398,33 +398,23 @@ void _sendResponse( ); } -void _sendHotReloadResponse( - StreamSink clientSink, - String requestId, { - bool success = true, - String? errorMessage, -}) { - _sendResponse( - clientSink, - HotReloadResponse.new, - requestId, - success: success, - errorMessage: errorMessage, - ); -} - void _sendHotRestartResponse( StreamSink clientSink, String requestId, { bool success = true, String? errorMessage, }) { - _sendResponse( + _trySendEvent( clientSink, - HotRestartResponse.new, - requestId, - success: success, - errorMessage: errorMessage, + jsonEncode( + serializers.serialize( + HotRestartResponse((HotRestartResponseBuilder b) { + b.id = requestId; + b.success = success; + if (errorMessage != null) b.errorMessage = errorMessage; + }), + ), + ), ); } @@ -434,7 +424,7 @@ void _sendServiceExtensionResponse( bool success = true, String? errorMessage, int? errorCode, - Map? result, + Map? result, }) { _trySendEvent( clientSink, @@ -589,9 +579,6 @@ external String get dartEntrypointPath; @JS(r'$dwdsEnableDevToolsLaunch') external bool get dwdsEnableDevToolsLaunch; -@JS('window.top.document.dispatchEvent') -external void dispatchEvent(CustomEvent event); - @JS(r'$dartEmitDebugEvents') external bool get dartEmitDebugEvents; @@ -601,12 +588,6 @@ external set emitDebugEvent(JSFunction func); @JS(r'$emitRegisterEvent') external set emitRegisterEvent(JSFunction func); -@JS(r'$isInternalBuild') -external bool get isInternalBuild; - -@JS(r'$isFlutterApp') -external bool get isFlutterApp; - @JS(r'$dartWorkspaceName') external String? get dartWorkspaceName; diff --git a/dwds/web/reloader/ddc_library_bundle_restarter.dart b/dwds/web/reloader/ddc_library_bundle_restarter.dart index 4556c77c7..f98c3aaea 100644 --- a/dwds/web/reloader/ddc_library_bundle_restarter.dart +++ b/dwds/web/reloader/ddc_library_bundle_restarter.dart @@ -153,9 +153,9 @@ class DdcLibraryBundleRestarter implements Restarter { } /// Handles service extension requests using the dart dev embedder - Future?> handleServiceExtension( + Future?> handleServiceExtension( String method, - Map args, + Map args, ) async { if (method == 'ext.flutter.reassemble') { await _dartDevEmbedder.debugger.maybeInvokeFlutterReassemble(); @@ -170,7 +170,7 @@ class DdcLibraryBundleRestarter implements Restarter { final resultJson = await _dartDevEmbedder.debugger .invokeExtension(method, params) .toDart; - return jsonDecode(resultJson.toDart) as Map; + return jsonDecode(resultJson.toDart) as Map; } } } diff --git a/dwds/web/reloader/manager.dart b/dwds/web/reloader/manager.dart index b044cf4af..32080b67f 100644 --- a/dwds/web/reloader/manager.dart +++ b/dwds/web/reloader/manager.dart @@ -100,10 +100,11 @@ class ReloadingManager { window.location.reload(); } - /// Handles service extension requests by delegating to the appropriate restarter - Future?> handleServiceExtension( + /// Handles service extension requests by delegating to the appropriate + /// restarter. + Future?> handleServiceExtension( String method, - Map args, + Map args, ) async { final restarter = _restarter; if (restarter is DdcLibraryBundleRestarter) { diff --git a/dwds/web/reloader/require_restarter.dart b/dwds/web/reloader/require_restarter.dart index d2e7eb170..61ba85303 100644 --- a/dwds/web/reloader/require_restarter.dart +++ b/dwds/web/reloader/require_restarter.dart @@ -126,7 +126,7 @@ class RequireRestarter implements Restarter { late SplayTreeSet _dirtyModules; var _running = Completer()..complete(true); - var count = 0; + int count = 0; RequireRestarter._() { _dirtyModules = SplayTreeSet(_moduleTopologicalCompare); @@ -275,7 +275,7 @@ class RequireRestarter implements Restarter { } Future _reloadModule(String moduleId) { - final completer = Completer(); + final completer = Completer(); final stackTrace = StackTrace.current; requireLoader.forceLoadModule( moduleId.toJS, diff --git a/fixtures/_test/example/scopes/main.dart b/fixtures/_test/example/scopes/main.dart index 4744a2d38..f850e1f71 100644 --- a/fixtures/_test/example/scopes/main.dart +++ b/fixtures/_test/example/scopes/main.dart @@ -74,7 +74,7 @@ void main() async { return '$local: parameter, $another'; // Breakpoint: nestedFunction } - dynamic nestedWithClosure(String banana) { + Function nestedWithClosure(String banana) { return () => '$local + $banana'; } diff --git a/fixtures/_webdev_smoke/web/scopes_main.dart b/fixtures/_webdev_smoke/web/scopes_main.dart index c1a4e0e28..5714445c1 100644 --- a/fixtures/_webdev_smoke/web/scopes_main.dart +++ b/fixtures/_webdev_smoke/web/scopes_main.dart @@ -42,7 +42,7 @@ void main() async { return '$local: parameter, $another'; // Breakpoint: nestedFunction } - dynamic nestedWithClosure(String banana) { + Function nestedWithClosure(String banana) { return () => '$local + $banana'; } diff --git a/frontend_server_client/example/app/main.dart b/frontend_server_client/example/app/main.dart index 4decd86ec..6ee01dd23 100644 --- a/frontend_server_client/example/app/main.dart +++ b/frontend_server_client/example/app/main.dart @@ -8,7 +8,7 @@ Future main() async { print(message); while (!message.contains('goodbye')) { print('waiting for hot reload to change message'); - await Future.delayed(const Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); } print(message); } diff --git a/frontend_server_client/example/vm_client.dart b/frontend_server_client/example/vm_client.dart index 9499a7ce5..b567e98c4 100644 --- a/frontend_server_client/example/vm_client.dart +++ b/frontend_server_client/example/vm_client.dart @@ -38,7 +38,7 @@ void main(List args) async { '--enable-vm-service=0', result.dillOutput!, ]); - final sawHelloWorld = Completer(); + final sawHelloWorld = Completer(); appProcess.stdout .transform(utf8.decoder) .transform(const LineSplitter()) diff --git a/frontend_server_client/lib/src/dartdevc_bootstrap_amd.dart b/frontend_server_client/lib/src/dartdevc_bootstrap_amd.dart index 74c6c228c..cf09e54b9 100644 --- a/frontend_server_client/lib/src/dartdevc_bootstrap_amd.dart +++ b/frontend_server_client/lib/src/dartdevc_bootstrap_amd.dart @@ -41,12 +41,12 @@ document.head.appendChild(requireEl); /// method. /// /// RE: Object.keys usage in app.main: -/// This attaches the main entrypoint and hot reload functionality to the window. -/// The app module will have a single property which contains the actual application -/// code. The property name is based off of the entrypoint that is generated, for example -/// the file `foo/bar/baz.dart` will generate a property named approximately -/// `foo__bar__baz`. Rather than attempt to guess, we assume the first property of -/// this object is the module. +/// This attaches the main entrypoint and hot reload functionality to the +/// window. The app module will have a single property which contains the actual +/// application code. The property name is based off of the entrypoint that is +/// generated, for example the file `foo/bar/baz.dart` will generate a property named approximately +/// `foo__bar__baz`. Rather than attempt to guess, we assume the first property +/// of this object is the module. String generateAmdMainModule({required String entrypoint}) { return '''/* ENTRYPOINT_EXTENTION_MARKER */ // Create the main module loaded below. diff --git a/frontend_server_client/lib/src/dartdevc_frontend_server_client.dart b/frontend_server_client/lib/src/dartdevc_frontend_server_client.dart index f87c85145..81baecff6 100644 --- a/frontend_server_client/lib/src/dartdevc_frontend_server_client.dart +++ b/frontend_server_client/lib/src/dartdevc_frontend_server_client.dart @@ -120,12 +120,12 @@ class DartDevcFrontendServerClient implements FrontendServerClient { } final manifest = jsonDecode(File(result.jsManifestOutput!).readAsStringSync()) - as Map; + as Map; final sourceBytes = File(result.jsSourcesOutput!).readAsBytesSync(); final sourceMapBytes = File(result.jsSourceMapsOutput!).readAsBytesSync(); for (final entry in manifest.entries) { - final metadata = entry.value as Map; + final metadata = entry.value as Map; final sourceOffsets = metadata['code'] as List; _assets[entry.key] = sourceBytes.sublist( sourceOffsets[0] as int, diff --git a/frontend_server_client/lib/src/frontend_server_client.dart b/frontend_server_client/lib/src/frontend_server_client.dart index a2dbd7247..58674ee72 100644 --- a/frontend_server_client/lib/src/frontend_server_client.dart +++ b/frontend_server_client/lib/src/frontend_server_client.dart @@ -227,7 +227,8 @@ class FrontendServerClient { removedSources.add(diffUri); } else { throw StateError( - 'unrecognized diff line, should start with a + or - but got: $line', + 'unrecognized diff line, should start with a + or - but got: ' + '$line', ); } continue; diff --git a/frontend_server_client/test/frontend_server_client_test.dart b/frontend_server_client/test/frontend_server_client_test.dart index 027d77e98..44fc9e27b 100644 --- a/frontend_server_client/test/frontend_server_client_test.dart +++ b/frontend_server_client/test/frontend_server_client_test.dart @@ -330,14 +330,14 @@ Future waitForIsolatesAndResume(VmService vmService) async { var vm = await vmService.getVM(); var isolates = vm.isolates; while (isolates == null || isolates.isEmpty) { - await Future.delayed(const Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); vm = await vmService.getVM(); isolates = vm.isolates; } final isolateRef = isolates.first; var isolate = await vmService.getIsolate(isolateRef.id!); while (isolate.pauseEvent?.kind != EventKind.kPauseStart) { - await Future.delayed(const Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); isolate = await vmService.getIsolate(isolateRef.id!); } await vmService.resume(isolate.id!); diff --git a/frontend_server_common/lib/src/asset_server.dart b/frontend_server_common/lib/src/asset_server.dart index 72d2b2d47..4370c6baa 100644 --- a/frontend_server_common/lib/src/asset_server.dart +++ b/frontend_server_common/lib/src/asset_server.dart @@ -173,7 +173,8 @@ class TestAssetServer implements AssetReader { _files[filePath] = Uint8List.fromList(utf8.encode(contents)); } - /// Update the in-memory asset server with the provided source and manifest files. + /// Update the in-memory asset server with the provided source and manifest + /// files. /// /// Returns a list of updated modules. List write( @@ -191,10 +192,10 @@ class TestAssetServer implements AssetReader { ); for (final filePath in manifest.keys) { final offsets = _castStringKeyedMap(manifest[filePath]); - final codeOffsets = (offsets['code'] as List).cast(); - final sourcemapOffsets = (offsets['sourcemap'] as List) + final codeOffsets = (offsets['code'] as List).cast(); + final sourcemapOffsets = (offsets['sourcemap'] as List) .cast(); - final metadataOffsets = (offsets['metadata'] as List) + final metadataOffsets = (offsets['metadata'] as List) .cast(); if (codeOffsets.length != 2 || sourcemapOffsets.length != 2 || @@ -354,9 +355,9 @@ class TestAssetServer implements AssetReader { } } -/// Given a data structure which is a Map of String to dynamic values, return -/// the same structure (`Map`) with the correct runtime types. -Map _castStringKeyedMap(dynamic untyped) { - final map = untyped as Map; - return map.cast(); +/// Given a data structure which is a Map of String to Object? values, return +/// the same structure (`Map`) with the correct runtime types. +Map _castStringKeyedMap(Object? untyped) { + final map = untyped as Map; + return map.cast(); } diff --git a/frontend_server_common/lib/src/bootstrap.dart b/frontend_server_common/lib/src/bootstrap.dart index 2cd0c5e97..6f2ccc455 100644 --- a/frontend_server_common/lib/src/bootstrap.dart +++ b/frontend_server_common/lib/src/bootstrap.dart @@ -117,12 +117,12 @@ document.head.appendChild(requireEl); /// method. /// /// RE: Object.keys usage in app.main: -/// This attaches the main entrypoint and hot reload functionality to the window. -/// The app module will have a single property which contains the actual application -/// code. The property name is based off of the entrypoint that is generated, for example -/// the file `foo/bar/baz.dart` will generate a property named approximately -/// `foo__bar__baz`. Rather than attempt to guess, we assume the first property of -/// this object is the module. +/// This attaches the main entrypoint and hot reload functionality to the +/// window. The app module will have a single property which contains the actual +/// application code. The property name is based off of the entrypoint that is +/// generated, for example the file `foo/bar/baz.dart` will generate a property +/// named approximately `foo__bar__baz`. Rather than attempt to guess, we assume +/// the first property of this object is the module. String generateMainModule({required String entrypoint}) { return '''/* ENTRYPOINT_EXTENTION_MARKER */ diff --git a/frontend_server_common/lib/src/devfs.dart b/frontend_server_common/lib/src/devfs.dart index 77e955099..89832676a 100644 --- a/frontend_server_common/lib/src/devfs.dart +++ b/frontend_server_common/lib/src/devfs.dart @@ -265,7 +265,7 @@ class WebDevFS { json.decode( utf8.decode(assetServer.getMetadata('$module.metadata').toList()), ) - as Map, + as Map, ); final libraries = metadata.libraries.keys.toList(); moduleToLibrary.add({ @@ -347,7 +347,7 @@ class ProjectFileInvalidator { if (lastCompiled == null) { // Initial load. assert(urisToMonitor.isEmpty); - return InvalidationResult(uris: []); + return const InvalidationResult(uris: []); } final urisToScan = [ diff --git a/frontend_server_common/lib/src/frontend_server_client.dart b/frontend_server_common/lib/src/frontend_server_client.dart index f97d15d92..3417dffba 100644 --- a/frontend_server_common/lib/src/frontend_server_client.dart +++ b/frontend_server_common/lib/src/frontend_server_client.dart @@ -636,7 +636,7 @@ class ResidentCompiler { } /// stop the service normally - Future shutdown() async { + Future shutdown() async { // Server was never successfully created. if (_server == null) { return 0; @@ -645,7 +645,7 @@ class ResidentCompiler { } /// kill the service - Future kill() async { + Future kill() async { if (_server == null) { return 0; } diff --git a/frontend_server_common/pubspec.yaml b/frontend_server_common/pubspec.yaml index 7b3c1520e..050e7edae 100644 --- a/frontend_server_common/pubspec.yaml +++ b/frontend_server_common/pubspec.yaml @@ -11,10 +11,10 @@ dependencies: logging: ^1.0.1 meta: ^1.4.0 mime: ^1.0.0 - shelf: ^1.1.4 package_config: ^2.0.0 path: ^1.8.0 pub_semver: ^2.1.1 + shelf: ^1.1.4 test_common: path: ../test_common diff --git a/test_common/lib/sdk_asset_generator.dart b/test_common/lib/sdk_asset_generator.dart index e5768752d..ea1f06ed0 100644 --- a/test_common/lib/sdk_asset_generator.dart +++ b/test_common/lib/sdk_asset_generator.dart @@ -6,7 +6,7 @@ import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; -import 'package:test_common/test_sdk_layout.dart'; +import 'test_sdk_layout.dart'; /// Generates sdk.js, sdk.map, files. diff --git a/test_common/lib/test_sdk_configuration.dart b/test_common/lib/test_sdk_configuration.dart index c5ddb5d05..2c83e6bdc 100644 --- a/test_common/lib/test_sdk_configuration.dart +++ b/test_common/lib/test_sdk_configuration.dart @@ -8,8 +8,8 @@ import 'package:dwds/expression_compiler.dart'; import 'package:dwds/sdk_configuration.dart'; import 'package:logging/logging.dart'; -import 'package:test_common/sdk_asset_generator.dart'; -import 'package:test_common/test_sdk_layout.dart'; +import 'sdk_asset_generator.dart'; +import 'test_sdk_layout.dart'; /// Implementation for SDK configuration for tests that can generate /// missing assets. diff --git a/test_common/test/sdk_asset_generator_test.dart b/test_common/test/sdk_asset_generator_test.dart index 2f586ae23..783bce15e 100644 --- a/test_common/test/sdk_asset_generator_test.dart +++ b/test_common/test/sdk_asset_generator_test.dart @@ -57,7 +57,8 @@ void main() { }); test( - 'Can generate missing SDK assets and validate SDK configuration for the AMD module system', + 'Can generate missing SDK assets and validate SDK configuration for the' + 'AMD module system', () async { final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); final configuration = TestSdkLayout.createConfiguration(sdkLayout); @@ -70,7 +71,8 @@ void main() { ); await assetGenerator.generateSdkAssets(); - // Make sure SDK configuration and asset generator agree on the file paths. + // Make sure SDK configuration and asset generator agree on the file + // paths. expect(configuration.sdkDirectory, equals(sdkDirectory)); expect(configuration.compilerWorkerPath, equals(compilerWorkerPath)); @@ -87,36 +89,35 @@ void main() { }, ); - test( - 'Can generate missing SDK assets and validate SDK configuration for the DDC module system', - () async { - final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); - final configuration = TestSdkLayout.createConfiguration(sdkLayout); - - final assetGenerator = SdkAssetGenerator( - sdkLayout: sdkLayout, - verbose: true, - canaryFeatures: false, - ddcModuleFormat: ModuleFormat.ddc, - ); - await assetGenerator.generateSdkAssets(); - - // Make sure SDK configuration and asset generator agree on the file paths. - expect(configuration.sdkDirectory, equals(sdkDirectory)); - expect(configuration.compilerWorkerPath, equals(compilerWorkerPath)); - - expect(sdkLayout.ddcJsPath, equals(ddcSdkJsPath)); - expect(sdkLayout.ddcJsMapPath, equals(ddcSdkJsMapPath)); - - // Validate that configuration files exist. - configuration.validateSdkDir(); - configuration.validate(); - - // Validate all assets exist. - expect(sdkLayout.ddcJsPath, _exists); - expect(sdkLayout.ddcJsMapPath, _exists); - }, - ); + test('Can generate missing SDK assets and validate SDK configuration for ' + 'the DDC module system', () async { + final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); + final configuration = TestSdkLayout.createConfiguration(sdkLayout); + + final assetGenerator = SdkAssetGenerator( + sdkLayout: sdkLayout, + verbose: true, + canaryFeatures: false, + ddcModuleFormat: ModuleFormat.ddc, + ); + await assetGenerator.generateSdkAssets(); + + // Make sure SDK configuration and asset generator agree on the file + // paths. + expect(configuration.sdkDirectory, equals(sdkDirectory)); + expect(configuration.compilerWorkerPath, equals(compilerWorkerPath)); + + expect(sdkLayout.ddcJsPath, equals(ddcSdkJsPath)); + expect(sdkLayout.ddcJsMapPath, equals(ddcSdkJsMapPath)); + + // Validate that configuration files exist. + configuration.validateSdkDir(); + configuration.validate(); + + // Validate all assets exist. + expect(sdkLayout.ddcJsPath, _exists); + expect(sdkLayout.ddcJsMapPath, _exists); + }); test( 'Can generate missing SDK assets with canary features enabled', @@ -136,23 +137,21 @@ void main() { }, ); - test( - 'Can generate missing SDK assets with canary features enabled for the DDC module system', - () async { - final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); + test('Can generate missing SDK assets with canary features enabled for the ' + 'DDC module system', () async { + final sdkLayout = TestSdkLayout.createDefault(sdkDirectory); - final assetGenerator = SdkAssetGenerator( - sdkLayout: sdkLayout, - verbose: true, - canaryFeatures: true, - ddcModuleFormat: ModuleFormat.ddc, - ); - await assetGenerator.generateSdkAssets(); + final assetGenerator = SdkAssetGenerator( + sdkLayout: sdkLayout, + verbose: true, + canaryFeatures: true, + ddcModuleFormat: ModuleFormat.ddc, + ); + await assetGenerator.generateSdkAssets(); - final sdk = File(ddcSdkJsPath).readAsStringSync(); - expect(sdk, contains('canary')); - }, - ); + final sdk = File(ddcSdkJsPath).readAsStringSync(); + expect(sdk, contains('canary')); + }); }); } diff --git a/webdev/lib/src/command/daemon_command.dart b/webdev/lib/src/command/daemon_command.dart index e3159c9d8..780d6f9fe 100644 --- a/webdev/lib/src/command/daemon_command.dart +++ b/webdev/lib/src/command/daemon_command.dart @@ -21,16 +21,16 @@ import '../serve/utils.dart'; import 'configuration.dart'; import 'shared.dart'; -Stream> get _stdinCommandStream => stdin +Stream> get _stdinCommandStream => stdin .transform(utf8.decoder) .transform(const LineSplitter()) .where((String line) => line.startsWith('[{') && line.endsWith('}]')) - .map>((String line) { + .map>((String line) { line = line.substring(1, line.length - 1); - return json.decode(line) as Map; + return json.decode(line) as Map; }); -void _stdoutCommandResponse(Map command) { +void _stdoutCommandResponse(Map command) { stdout.writeln('[${json.encode(command)}]'); } @@ -87,7 +87,7 @@ class DaemonCommand extends Command { ProcessSignal.sigint.watch(), // SIGTERM is not supported on Windows. Platform.isWindows - ? const Stream.empty() + ? const Stream.empty() : ProcessSignal.sigterm.watch(), ]).listen((signal) async { cancelCount++; diff --git a/webdev/lib/src/daemon/app_domain.dart b/webdev/lib/src/daemon/app_domain.dart index ec24f8010..edf18e60a 100644 --- a/webdev/lib/src/daemon/app_domain.dart +++ b/webdev/lib/src/daemon/app_domain.dart @@ -146,8 +146,8 @@ class AppDomain extends Domain { _initialize(serverManager); } - Future?> _callServiceExtension( - Map args, + Future?> _callServiceExtension( + Map args, ) async { final appId = getStringArg(args, 'appId', required: true); final appState = _appStates[appId]; @@ -156,8 +156,8 @@ class AppDomain extends Domain { } final methodName = getStringArg(args, 'methodName', required: true)!; final params = args['params'] != null - ? (args['params'] as Map) - : {}; + ? (args['params'] as Map) + : {}; final response = await appState.vmService!.callServiceExtension( methodName, args: params, @@ -165,7 +165,7 @@ class AppDomain extends Domain { return response.json; } - Future> _restart(Map args) async { + Future> _restart(Map args) async { final appId = getStringArg(args, 'appId', required: true); final appState = _appStates[appId]; if (appState == null) { @@ -206,7 +206,7 @@ class AppDomain extends Domain { }; } - Future _stop(Map args) async { + Future _stop(Map args) async { final appId = getStringArg(args, 'appId', required: true); final appState = _appStates[appId]; if (appState == null) { diff --git a/webdev/lib/src/daemon/daemon.dart b/webdev/lib/src/daemon/daemon.dart index ebe37475a..3c9288c72 100644 --- a/webdev/lib/src/daemon/daemon.dart +++ b/webdev/lib/src/daemon/daemon.dart @@ -13,7 +13,7 @@ import 'utilites.dart'; /// Listens for commands, routes them to the corresponding domain and provides /// the result. class Daemon { - Daemon(Stream> commandStream, this._sendCommand) { + Daemon(Stream> commandStream, this._sendCommand) { _commandSubscription = commandStream.listen( _handleRequest, onDone: () { @@ -22,9 +22,9 @@ class Daemon { ); } - late StreamSubscription> _commandSubscription; + late StreamSubscription> _commandSubscription; - final void Function(Map) _sendCommand; + final void Function(Map) _sendCommand; final Completer _onExitCompleter = Completer(); final Map _domainMap = {}; @@ -38,7 +38,7 @@ class Daemon { Future get onExit => _onExitCompleter.future; - void _handleRequest(Map request) { + void _handleRequest(Map request) { // {id, method, params} // [id] is an opaque type to us. @@ -65,10 +65,10 @@ class Daemon { domainValue.handleCommand( name, id, - request['params'] as Map? ?? {}, + request['params'] as Map? ?? {}, ); } catch (error, trace) { - send({ + send({ 'id': id, 'error': toJsonable(error), 'trace': '$trace', @@ -76,7 +76,7 @@ class Daemon { } } - void send(Map map) => _sendCommand(map); + void send(Map map) => _sendCommand(map); void shutdown({Object? error}) { _commandSubscription.cancel(); diff --git a/webdev/lib/src/daemon/daemon_domain.dart b/webdev/lib/src/daemon/daemon_domain.dart index c5e75a4fd..88084d6dc 100644 --- a/webdev/lib/src/daemon/daemon_domain.dart +++ b/webdev/lib/src/daemon/daemon_domain.dart @@ -19,11 +19,11 @@ class DaemonDomain extends Domain { sendEvent('daemon.connected', {'version': protocolVersion, 'pid': pid}); } - Future _version(Map args) { + Future _version(Map args) { return Future.value(protocolVersion); } - Future _shutdown(Map args) { + Future _shutdown(Map args) { // Schedule shutdown after we return the result. Timer.run(daemon.shutdown); return Future.value(); diff --git a/webdev/lib/src/daemon/domain.dart b/webdev/lib/src/daemon/domain.dart index a4607cd7e..222558448 100644 --- a/webdev/lib/src/daemon/domain.dart +++ b/webdev/lib/src/daemon/domain.dart @@ -22,20 +22,20 @@ abstract class Domain { @override String toString() => name; - void handleCommand(String command, dynamic id, Map args) { - Future.sync(() { + void handleCommand(String command, Object? id, Map args) { + Future.sync(() { if (_handlers.containsKey(command)) return _handlers[command]!(args); throw ArgumentError('command not understood: $name.$command'); }) - .then((dynamic result) { + .then((Object? result) { if (result == null) { - _send({'id': id}); + _send({'id': id}); } else { - _send({'id': id, 'result': toJsonable(result)}); + _send({'id': id, 'result': toJsonable(result)}); } }) - .catchError((dynamic error, dynamic trace) { - _send({ + .catchError((Object? error, Object? trace) { + _send({ 'id': id, 'error': toJsonable(error), 'trace': '$trace', @@ -43,15 +43,15 @@ abstract class Domain { }); } - void sendEvent(String name, [dynamic args]) { - final map = {'event': name}; + void sendEvent(String name, [Object? args]) { + final map = {'event': name}; if (args != null) map['params'] = toJsonable(args); _send(map); } - void _send(Map map) => daemon.send(map); + void _send(Map map) => daemon.send(map); void dispose() {} } -typedef CommandHandler = Future Function(Map args); +typedef CommandHandler = Future Function(Map args); diff --git a/webdev/lib/src/daemon/utilites.dart b/webdev/lib/src/daemon/utilites.dart index 31f414a1b..d6d0f8f30 100644 --- a/webdev/lib/src/daemon/utilites.dart +++ b/webdev/lib/src/daemon/utilites.dart @@ -2,12 +2,12 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -dynamic toJsonable(dynamic obj) { +Object? toJsonable(Object? obj) { if (obj is String || obj is int || obj is bool || - obj is Map || - obj is List || + obj is Map || + obj is List || obj == null) { return obj; } @@ -15,7 +15,7 @@ dynamic toJsonable(dynamic obj) { } String? getStringArg( - Map args, + Map args, String name, { bool required = false, }) { @@ -30,7 +30,7 @@ String? getStringArg( } bool? getBoolArg( - Map args, + Map args, String name, { bool required = false, }) { @@ -43,7 +43,7 @@ bool? getBoolArg( } int? getIntArg( - Map args, + Map args, String name, { bool required = false, }) { diff --git a/webdev/lib/src/daemon_client.dart b/webdev/lib/src/daemon_client.dart index c0be0ea71..ea95e83c9 100644 --- a/webdev/lib/src/daemon_client.dart +++ b/webdev/lib/src/daemon_client.dart @@ -15,7 +15,7 @@ import 'util.dart'; Future connectClient( String workingDirectory, List options, - Function(ServerLog) logHandler, + void Function(ServerLog) logHandler, ) => BuildDaemonClient.connect(workingDirectory, [ dartPath, 'run', diff --git a/webdev/lib/src/pubspec.dart b/webdev/lib/src/pubspec.dart index 85a314dce..75bff1975 100644 --- a/webdev/lib/src/pubspec.dart +++ b/webdev/lib/src/pubspec.dart @@ -235,9 +235,10 @@ Future<_PackageInfo> _latestPackageInfo() async { Uri.parse('https://pub.dev/api/packages/webdev'), headers: {HttpHeaders.userAgentHeader: 'webdev $packageVersion'}, ); - final responseObj = json.decode(response.body); + final responseObj = json.decode(response.body) as Map; final pubspec = Pubspec.fromJson( - responseObj['latest']['pubspec'] as Map, + (responseObj['latest']! as Map)['pubspec'] + as Map, ); final buildDaemonDependency = pubspec.dependencies['build_daemon']; // This should never be satisfied. diff --git a/webdev/lib/src/serve/dev_workflow.dart b/webdev/lib/src/serve/dev_workflow.dart index e950620f3..d8f1012ca 100644 --- a/webdev/lib/src/serve/dev_workflow.dart +++ b/webdev/lib/src/serve/dev_workflow.dart @@ -84,6 +84,7 @@ Future _startChrome( } else if (configuration.chromeDebugPort != 0) { return await Chrome.fromExisting(configuration.chromeDebugPort); } + // ignore: avoid_catching_errors } on ChromeError { await serverManager.stop(); await client.close(); @@ -172,7 +173,7 @@ void _registerBuildTargets( /// Connects to the Build Daemon, creates servers, launches Chrome and wires up /// the DevTools. class DevWorkflow { - final _doneCompleter = Completer(); + final _doneCompleter = Completer(); final BuildDaemonClient _client; final Chrome? _chrome; diff --git a/webdev/lib/src/serve/utils.dart b/webdev/lib/src/serve/utils.dart index e6e062a67..0cba304c6 100644 --- a/webdev/lib/src/serve/utils.dart +++ b/webdev/lib/src/serve/utils.dart @@ -83,8 +83,9 @@ Future _removeDeleted(String from, String to) async { } } -/// Returns the absolute file path of the `package_config.json` file in the `.dart_tool` -/// directory, searching recursively from the current directory hierarchy. +/// Returns the absolute file path of the `package_config.json` file in the +/// `.dart_tool` directory, searching recursively from the current directory +/// hierarchy. String? findPackageConfigFilePath() { var candidateDir = Directory(p.current).absolute; diff --git a/webdev/lib/src/util.dart b/webdev/lib/src/util.dart index 47033d546..2845a878c 100644 --- a/webdev/lib/src/util.dart +++ b/webdev/lib/src/util.dart @@ -30,12 +30,12 @@ void serveHttpRequests( final String _sdkDir = (() { // The Dart executable is in "/path/to/sdk/bin/dart", so two levels up is // "/path/to/sdk". - final String dartExecutable = Platform.isWindows + final dartExecutable = Platform.isWindows // Use 'where.exe' to support powershell as well ? (Process.runSync('where.exe', ['dart.exe']).stdout as String) .split(RegExp('(\r\n|\r|\n)')) .first - : Process.runSync('which', ['dart']).stdout; + : Process.runSync('which', ['dart']).stdout as String; final aboveExecutable = p.dirname(p.dirname(dartExecutable)); assert(FileSystemEntity.isFileSync(p.join(aboveExecutable, 'version'))); return aboveExecutable; diff --git a/webdev/pubspec.yaml b/webdev/pubspec.yaml index 94e62e0dd..8eba95c69 100644 --- a/webdev/pubspec.yaml +++ b/webdev/pubspec.yaml @@ -13,8 +13,8 @@ environment: dependencies: args: ^2.3.1 async: ^2.9.0 - build_daemon: ^4.0.0 browser_launcher: ^1.1.0 + build_daemon: ^4.0.0 collection: ^1.15.0 crypto: ^3.0.2 dds: ^4.1.0 @@ -27,13 +27,13 @@ dependencies: meta: ^1.7.0 path: ^1.8.1 pool: ^1.5.0 - pubspec_parse: ^1.2.0 pub_semver: ^2.1.1 + pubspec_parse: ^1.2.0 shelf: ^1.3.0 shelf_proxy: ^1.0.1 shelf_static: ^1.1.0 - stack_trace: ^1.10.0 sse: ^4.1.0 + stack_trace: ^1.10.0 vm_service: ">=14.0.0 <16.0.0" vm_service_interface: 2.0.1 webkit_inspection_protocol: ^1.0.1 diff --git a/webdev/test/chrome_test.dart b/webdev/test/chrome_test.dart index f2940016f..901a4326e 100644 --- a/webdev/test/chrome_test.dart +++ b/webdev/test/chrome_test.dart @@ -243,12 +243,15 @@ String _closeTabUrl(String id) => '/json/close/$id'; Future _evaluateExpression(WipPage page, String expression) async { String? result = ''; while (result == null || result.isEmpty) { - await Future.delayed(const Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); final wipResponse = await page.sendCommand( 'Runtime.evaluate', params: {'expression': expression}, ); - result = wipResponse.json['result']['result']['value'] as String?; + result = + ((wipResponse.json['result']! as Map)['result']! + as Map)['value'] + as String?; } return result; } diff --git a/webdev/test/daemon/app_domain_test.dart b/webdev/test/daemon/app_domain_test.dart index dc09c9fbc..ab52ede63 100644 --- a/webdev/test/daemon/app_domain_test.dart +++ b/webdev/test/daemon/app_domain_test.dart @@ -87,7 +87,7 @@ void main() { if (Platform.isWindows) { // Windows takes a bit longer to run the application and register // the service extension. - await Future.delayed(const Duration(seconds: 5)); + await Future.delayed(const Duration(seconds: 5)); } final extensionCall = '[{"method":"app.callServiceExtension","id":0,' @@ -119,7 +119,8 @@ void main() { webdev.stdout, emitsThrough( startsWith( - '[{"id":0,"result":{"code":1,"message":"hot reload not yet supported', + '[{"id":0,"result":{"code":1,"message":"hot reload not yet ' + 'supported', ), ), ); diff --git a/webdev/test/daemon/utils.dart b/webdev/test/daemon/utils.dart index b760eabc4..e9e1a1c51 100644 --- a/webdev/test/daemon/utils.dart +++ b/webdev/test/daemon/utils.dart @@ -24,8 +24,8 @@ Future waitForAppId(TestProcess webdev) async { var line = await webdev.stdout.next; if (line.startsWith('[{"event":"app.started"')) { line = line.substring(1, line.length - 1); - final message = json.decode(line) as Map; - appId = message['params']['appId'] as String; + final message = json.decode(line) as Map; + appId = (message['params']! as Map)['appId'] as String; break; } } diff --git a/webdev/test/e2e_test.dart b/webdev/test/e2e_test.dart index d703544bb..5ae9cbf11 100644 --- a/webdev/test/e2e_test.dart +++ b/webdev/test/e2e_test.dart @@ -73,17 +73,19 @@ void main() { final webdevYaml = loadYaml(await File('pubspec.yaml').readAsString()) as YamlMap; expect( - smokeYaml['environment']['sdk'], - equals(webdevYaml['environment']['sdk']), + (smokeYaml['environment'] as YamlMap)['sdk'], + equals((webdevYaml['environment'] as YamlMap)['sdk']), ); expect( buildRunnerConstraint.allowsAny( - VersionConstraint.parse(smokeYaml['dev_dependencies']['build_runner']), + VersionConstraint.parse( + (smokeYaml['dev_dependencies'] as YamlMap)['build_runner'] as String, + ), ), true, ); expect( - smokeYaml['dev_dependencies']['build_web_compilers'], + (smokeYaml['dev_dependencies'] as YamlMap)['build_web_compilers'], equals(buildWebCompilersConstraint.toString()), ); }); @@ -339,8 +341,8 @@ void main() { String? wsUri; await expectLater( process.stdout, - emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); + emitsThrough((String message) { + wsUri = getDebugServiceUri(message); return wsUri != null; }), ); @@ -424,8 +426,8 @@ void main() { String? wsUri; await expectLater( process.stdout, - emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); + emitsThrough((String message) { + wsUri = getDebugServiceUri(message); return wsUri != null; }), ); @@ -499,8 +501,8 @@ void main() { String? wsUri; await expectLater( process.stdout, - emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); + emitsThrough((String message) { + wsUri = getDebugServiceUri(message); return wsUri != null; }), ); @@ -580,8 +582,8 @@ void main() { String? wsUri; await expectLater( process.stdout, - emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); + emitsThrough((String message) { + wsUri = getDebugServiceUri(message); return wsUri != null; }), ); @@ -652,8 +654,8 @@ void main() { String? wsUri; await expectLater( process.stdout, - emitsThrough((message) { - wsUri = getDebugServiceUri(message as String); + emitsThrough((String message) { + wsUri = getDebugServiceUri(message); return wsUri != null; }), ); diff --git a/webdev/test/integration_test.dart b/webdev/test/integration_test.dart index 32ace5d80..c19f9ad95 100644 --- a/webdev/test/integration_test.dart +++ b/webdev/test/integration_test.dart @@ -251,7 +251,7 @@ void main() { await d.file('.dart_tool/package_config.json', '').create(); // Ensure there is a noticeable delta in the creation times - await Future.delayed(const Duration(milliseconds: 1100)); + await Future.delayed(const Duration(milliseconds: 1100)); await d.file('pubspec.yaml', ''' name: sample diff --git a/webdev/test/tls_test.dart b/webdev/test/tls_test.dart index d70ea0ead..75e23d35a 100644 --- a/webdev/test/tls_test.dart +++ b/webdev/test/tls_test.dart @@ -65,8 +65,7 @@ void main() { emitsThrough(contains('Built with build_runner')), ); - final client = HttpClient() - ..badCertificateCallback = (_, __, ___) => true; + final client = HttpClient()..badCertificateCallback = (_, _, _) => true; try { final request = await client.getUrl( Uri.parse('https://localhost:$port'), @@ -112,8 +111,7 @@ void main() { 'No non-loopback IPv4 address available, skipping hostname test.', ); } else { - final client = HttpClient() - ..badCertificateCallback = (_, __, ___) => true; + final client = HttpClient()..badCertificateCallback = (_, _, _) => true; try { final request = await client.getUrl( Uri.parse('https://${nonLoopback.address}:$port'), diff --git a/webdev/test/utils_test.dart b/webdev/test/utils_test.dart index 03e37d957..57b25706f 100644 --- a/webdev/test/utils_test.dart +++ b/webdev/test/utils_test.dart @@ -134,7 +134,7 @@ void main() { final fileTo = File(p.join(to.path, '1')); fileTo.writeAsStringSync('contentsTo'); - await Future.delayed(const Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); fileFrom.writeAsStringSync('contentsFrom'); final stats = fileFrom.statSync(); @@ -150,7 +150,7 @@ void main() { final fileTo = File(p.join(to.path, '1')); fileFrom.writeAsStringSync('contentsFrom'); - await Future.delayed(const Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); fileTo.writeAsStringSync('contentsTo'); final stats = fileFrom.statSync(); @@ -176,7 +176,7 @@ void main() { fileTo1.writeAsStringSync('contentsTo1'); fileTo2.writeAsStringSync('contentsTo2'); - await Future.delayed(const Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); fileFrom.writeAsStringSync('contentsFrom'); await updatePath(from.path, to.path); @@ -199,7 +199,7 @@ void main() { final fileTo2 = File(p.join(subDirTo2.path, 'b')); fileFrom.writeAsStringSync('contentsFrom'); - await Future.delayed(const Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); fileTo1.writeAsStringSync('contentsTo1'); fileTo2.writeAsStringSync('contentsTo2');