diff --git a/dwds/analysis_options.yaml b/dwds/analysis_options.yaml index 25d27d995..6ace40773 100644 --- a/dwds/analysis_options.yaml +++ b/dwds/analysis_options.yaml @@ -1,4 +1,4 @@ -include: package:analysis_config/analysis_options.yaml +include: package:dart_flutter_team_lints/analysis_options.yaml analyzer: exclude: @@ -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..a5b0f4619 100644 --- a/dwds/debug_extension/web/background.dart +++ b/dwds/debug_extension/web/background.dart @@ -181,7 +181,7 @@ Future _handleRuntimeMessages( }, ); - sendResponse(defaultResponse); + (sendResponse as void Function(Object?))(defaultResponse); } Future _detectNavigationAwayFromDartApp( diff --git a/dwds/debug_extension/web/chrome_api.dart b/dwds/debug_extension/web/chrome_api.dart index f69faea26..9957c362a 100644 --- a/dwds/debug_extension/web/chrome_api.dart +++ b/dwds/debug_extension/web/chrome_api.dart @@ -403,7 +403,10 @@ class NavigationInfo { @JS() @anonymous class Windows { - external dynamic create(WindowInfo? createData, Function(WindowObj) callback); + external dynamic 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..9185ddc93 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'); + final key = getProperty(message as Object, 'key'); + final json = getProperty(message, 'json'); if (key != _ciderDartMessageKey || json is! String) { sendErrorMessageToCider( errorType: CiderErrorType.invalidRequest, diff --git a/dwds/debug_extension/web/copier.dart b/dwds/debug_extension/web/copier.dart index 961a11e2b..08fc9472c 100644 --- a/dwds/debug_extension/web/copier.dart +++ b/dwds/debug_extension/web/copier.dart @@ -30,7 +30,7 @@ void _handleRuntimeMessages( Function sendResponse, ) { interceptMessage( - message: jsRequest, + message: jsRequest is String ? jsRequest : null, expectedType: MessageType.appId, expectedSender: Script.background, expectedRecipient: Script.copier, @@ -38,7 +38,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..5433c9d5d 100644 --- a/dwds/debug_extension/web/cross_extension_communication.dart +++ b/dwds/debug_extension/web/cross_extension_communication.dart @@ -43,9 +43,9 @@ Future handleMessagesFromAngularDartDevTools( await _respondWithEncodedUri(message.tabId, sendResponse); } else if (message.name == 'dwds.startDebugging') { await attachDebugger(message.tabId, trigger: Trigger.angularDartDevTools); - sendResponse(true); + (sendResponse as void Function(Object?))(true); } else { - sendResponse( + (sendResponse as void Function(Object?))( ErrorResponse()..error = 'Unknown message name: ${message.name}', ); } @@ -76,23 +76,23 @@ void _forwardCommandToChromeDebugger( options.method, options.commandParams, allowInterop( - ([result]) => _respondWithChromeResult(result, sendResponse), + ([Object? result]) => _respondWithChromeResult(result, sendResponse), ), ); } catch (e) { - sendResponse(ErrorResponse()..error = '$e'); + (sendResponse as void Function(Object?))(ErrorResponse()..error = '$e'); } } void _respondWithChromeResult(Object? chromeResult, Function sendResponse) { // No result indicates that an error occurred. if (chromeResult == null) { - sendResponse( + (sendResponse as void Function(Object?))( ErrorResponse() ..error = JSON.stringify(chrome.runtime.lastError ?? 'Unknown error.'), ); } else { - sendResponse(chromeResult); + (sendResponse as void Function(Object?))(chromeResult); } } @@ -101,7 +101,7 @@ Future _respondWithEncodedUri(int tabId, Function sendResponse) async { type: StorageObject.encodedUri, tabId: tabId, ); - sendResponse(encodedUri ?? ''); + (sendResponse as void Function(Object?))(encodedUri ?? ''); } void _forwardMessageToAngularDartDevTools(ExternalExtensionMessage message) { @@ -110,7 +110,7 @@ void _forwardMessageToAngularDartDevTools(ExternalExtensionMessage message) { message, // options null, - allowInterop(([result]) => _checkForErrors(result, message.name)), + allowInterop(([Object? result]) => _checkForErrors(result, message.name)), ); } diff --git a/dwds/debug_extension/web/debug_session.dart b/dwds/debug_extension/web/debug_session.dart index 3daf21016..694379f10 100644 --- a/dwds/debug_extension/web/debug_session.dart +++ b/dwds/debug_extension/web/debug_session.dart @@ -278,7 +278,8 @@ Future _onDebuggerEvent( } Future _maybeConnectToDwds(int tabId, Object? params) async { - final context = json.decode(JSON.stringify(params))['context']; + final decoded = json.decode(JSON.stringify(params)) as Map; + final context = decoded['context'] as Map; final contextOrigin = context['origin'] as String?; if (contextOrigin == null) return; if (contextOrigin.contains('chrome-extension:')) return; @@ -449,7 +450,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( diff --git a/dwds/debug_extension/web/detector.dart b/dwds/debug_extension/web/detector.dart index 4c482de26..e6c42e7d1 100644 --- a/dwds/debug_extension/web/detector.dart +++ b/dwds/debug_extension/web/detector.dart @@ -98,11 +98,12 @@ void _detectMultipleDartAppsCallback( bool _isMultipleAppsMutation(dynamic mutation) { final isAttributeMutation = - hasProperty(mutation, 'type') && - getProperty(mutation, 'type') == 'attributes'; + hasProperty(mutation as Object, 'type') && + 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..c9af59012 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 Object; enum Script { background, diff --git a/dwds/debug_extension/web/storage.dart b/dwds/debug_extension/web/storage.dart index 3413f0302..16a339684 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,8 +151,8 @@ void interceptStorageChange({ final isExpected = hasProperty(storageObj, expectedStorageKey); if (!isExpected) return; - final objProp = getProperty(storageObj, expectedStorageKey); - final json = getProperty(objProp, 'newValue') as String?; + final objProp = getProperty(storageObj, expectedStorageKey); + final json = getProperty(objProp as Object, 'newValue') as String?; T? decodedObj; if (json == null || T == String) { decodedObj = json as T?; 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..f259e32d1 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..9c890c772 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/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..38a8de14e 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 { 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..32cef2271 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); diff --git a/dwds/lib/src/debugging/classes.dart b/dwds/lib/src/debugging/classes.dart index eee4fdebf..deeb0e5d1 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]. @@ -94,31 +95,33 @@ class ChromeAppClassHelper { final classDescriptor = _mapify(result.value); final methodRefs = []; final methodDescriptors = _mapify(classDescriptor['methods']); - methodDescriptors.forEach((name, descriptor) { + methodDescriptors.forEach((name, dynamic descriptor) { + final typedDescriptor = descriptor as Map; final methodId = 'methods|$classId|$name'; methodRefs.add( FuncRef( id: methodId, name: name, owner: classRef, - isConst: descriptor['isConst'] as bool? ?? false, - isStatic: descriptor['isStatic'] as bool? ?? false, - implicit: descriptor['isImplicit'] as bool? ?? false, - isAbstract: descriptor['isAbstract'] as bool? ?? false, - isGetter: descriptor['isGetter'] as bool? ?? false, - isSetter: descriptor['isSetter'] as bool? ?? false, + isConst: typedDescriptor['isConst'] as bool? ?? false, + isStatic: typedDescriptor['isStatic'] as bool? ?? false, + implicit: typedDescriptor['isImplicit'] as bool? ?? false, + isAbstract: typedDescriptor['isAbstract'] as bool? ?? false, + isGetter: typedDescriptor['isGetter'] as bool? ?? false, + isSetter: typedDescriptor['isSetter'] as bool? ?? false, ), ); }); final fieldRefs = []; final fieldDescriptors = _mapify(classDescriptor['fields']); - fieldDescriptors.forEach((name, descriptor) { + fieldDescriptors.forEach((name, dynamic descriptor) { + final typedDescriptor = descriptor as Map; final classMetaData = ClassMetaData( runtimeKind: RuntimeObjectKind.type, classRef: classRefFor( - descriptor['classLibraryId'], - descriptor['className'], + typedDescriptor['classLibraryId'], + typedDescriptor['className'], ), ); @@ -132,9 +135,9 @@ class ChromeAppClassHelper { kind: classMetaData.kind, classRef: classMetaData.classRef, ), - isConst: descriptor['isConst'] as bool? ?? false, - isFinal: descriptor['isFinal'] as bool? ?? false, - isStatic: descriptor['isStatic'] as bool? ?? false, + isConst: typedDescriptor['isConst'] as bool? ?? false, + isFinal: typedDescriptor['isFinal'] as bool? ?? false, + isStatic: typedDescriptor['isStatic'] as bool? ?? false, id: createId(), ), ); diff --git a/dwds/lib/src/debugging/dart_runtime_debugger.dart b/dwds/lib/src/debugging/dart_runtime_debugger.dart index a3e24bb7e..41e85ef0d 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; @@ -104,15 +104,18 @@ class DartRuntimeDebugger { return _wrapInIIFE(expression); } - /// Generates a JS expression for retrieving Dart Developer Extension Names. + /// 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', ); } - /// Generates a JS expression for retrieving metadata of classes in a library. + /// Generates a JS expression for retrieving metadata of classes in a + /// library. String getClassesInLibraryJsExpression(String libraryUri) { final expression = _buildExpression( '', @@ -167,12 +170,15 @@ class DartRuntimeDebugger { ); } - /// Generates a JS expression for calling an instance method on an object. + /// Generates a JS expression for calling an instance method on an + /// object. String callInstanceMethodJsExpression(String methodName) { String generateInstanceMethodJsExpression(String functionCall) { return ''' function () { - if (!Object.getPrototypeOf(this)) { return 'Instance of PlainJavaScriptObject'; } + if (!Object.getPrototypeOf(this)) { + return 'Instance of PlainJavaScriptObject'; + } return $functionCall; } '''; @@ -180,10 +186,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 +199,10 @@ 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 +219,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..4c3470bd1 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,9 @@ 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 callFrames = e.params?['callFrames'] as List?; + final frame = callFrames?[0] as Map?; + final location = frame?['location'] as Map?; if (location == null) return null; final scriptId = location['scriptId'] as String?; @@ -368,8 +370,10 @@ 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 callFrames = e.params?['callFrames'] as List?; + final frame = callFrames?[0] as Map?; + final location = frame?['location'] as Map?; + return location?['scriptId'] as String?; } /// The variables visible in a frame in Dart protocol [BoundVariable] form. @@ -421,8 +425,10 @@ class Debugger { // Renders the paused at breakpoint overlay over the application. // void _showPausedOverlay() async { // if (_pausedOverlayVisible) return; - // handleErrorIfPresent(await _remoteDebugger?.sendCommand('DOM.enable')); - // handleErrorIfPresent(await _remoteDebugger?.sendCommand('Overlay.enable')); + // handleErrorIfPresent( + // await _remoteDebugger?.sendCommand('DOM.enable')); + // handleErrorIfPresent( + // await _remoteDebugger?.sendCommand('Overlay.enable')); // handleErrorIfPresent(await _remoteDebugger // ?.sendCommand('Overlay.setPausedInDebuggerMessage', params: { // 'message': 'Paused', @@ -433,7 +439,8 @@ class Debugger { // Removes the paused at breakpoint overlay from the application. // void _hidePausedOverlay() async { // if (!_pausedOverlayVisible) return; - // handleErrorIfPresent(await _remoteDebugger?.sendCommand('Overlay.disable')); + // handleErrorIfPresent( + // await _remoteDebugger?.sendCommand('Overlay.disable')); // _pausedOverlayVisible = false; // } @@ -498,7 +505,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; @@ -757,7 +765,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..8a5aa3f80 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) { + final resultObj = result.result?['result'] as Map?; + if (resultObj?['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 context = e.params?['context'] as Map?; + final id = context?['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..0aa90710b 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..246d07021 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 as String?, 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..bf1e7c077 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'); @@ -519,7 +520,8 @@ class ChromeAppInstanceHelper { count: namedRangeCount, ); final namedElements = - namedInstance?.elements?.map((e) => e.valueAsString) ?? []; + namedInstance?.elements?.map((e) => (e as InstanceRef).valueAsString) ?? + []; return [...positionalElements, ...namedElements]; } 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..cd7674530 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..8f2c08ce9 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,8 @@ class FunctionMetaData { }, ); handleErrorIfPresent(response, evalContents: evalExpression); - final name = response.result?['result']?['value'] as String?; + final result = response.result?['result'] as Map?; + final name = result?['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..56ff614fd 100644 --- a/dwds/lib/src/debugging/metadata/module_metadata.dart +++ b/dwds/lib/src/debugging/metadata/module_metadata.dart @@ -163,8 +163,11 @@ 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)); } } diff --git a/dwds/lib/src/debugging/metadata/provider.dart b/dwds/lib/src/debugging/metadata/provider.dart index 1ebdde882..4cc317624 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 AsyncMemoizer _metadataMemoizer = AsyncMemoizer(); /// Implicitly imported libraries in any DDC component. /// 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/skip_list.dart b/dwds/lib/src/debugging/skip_list.dart index 6256f823c..dfaa048ab 100644 --- a/dwds/lib/src/debugging/skip_list.dart +++ b/dwds/lib/src/debugging/skip_list.dart @@ -2,10 +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/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; 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..a3e7042af 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; diff --git a/dwds/lib/src/dwds_vm_client.dart b/dwds/lib/src/dwds_vm_client.dart index a6426cbd1..6471731db 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,12 @@ 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; } @@ -283,8 +285,11 @@ abstract base class DwdsVmClient< return { 'result': { 'views': [ - for (final isolate in isolates ?? []) - {'id': isolate.id, 'isolate': isolate.toJson()}, + for (final IsolateRef isolate in isolates ?? []) + { + 'id': isolate.id ?? '', + 'isolate': isolate.toJson(), + }, ], }, }; @@ -412,9 +417,9 @@ 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.'); + throw Exception('No context with the running Dart application.'); } Future> _hotRestart( @@ -429,14 +434,11 @@ final class ChromeDwdsVmClient logger.info('Attempting to get execution context ID.'); await tryGetContextId(chromeProxyService); logger.info('Got execution context ID.'); - } on StateError catch (e) { + } on Exception catch (e) { // We couldn't find the execution context. `hotRestart` may have been // triggered in the middle of a full reload. return { - 'error': { - 'code': RPCErrorKind.kInternalError.code, - 'message': e.message, - }, + 'error': {'code': RPCErrorKind.kInternalError.code, 'message': '$e'}, }; } // Start listening for isolate create events before issuing a hot @@ -455,22 +457,23 @@ final class ChromeDwdsVmClient // Generate run id to hot restart all apps loaded into the tab. 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`. - // 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. + // When using the DDC library bundle format, we determine the sources + // that were reloaded during a hot restart and 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. final isDdcLibraryBundle = globalToolConfiguration.loadStrategy is DdcLibraryBundleStrategy; final computedReloadedSrcs = Completer(); 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 diff --git a/dwds/lib/src/handlers/dev_handler.dart b/dwds/lib/src/handlers/dev_handler.dart index 94d9e3201..ad91c774e 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,18 +148,19 @@ class DevHandler { try { injectedConnection.sink.add(jsonEncode(serializers.serialize(request))); successfulSends++; - } on StateError catch (e) { - // The sink has already closed (app is disconnected), or another StateError occurred. + } catch (e, s) { + // The sink has already closed (app is disconnected). _logger.warning( - 'Failed to send request to client, connection likely closed. Error: $e', + 'Failed to send request to client, ' + 'connection likely closed. Error: $e', + e, + s, ); - } catch (e, s) { - // Catch any other potential errors during sending. - _logger.severe('Error sending request to client: $e', e, s); } } _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 +204,9 @@ class DevHandler { 'expression': r'window["$dartAppInstanceId"];', 'contextId': contextId, }); - final evaluatedAppId = result.result?['result']?['value']; + final resultMap = result.result; + final innerResult = resultMap?['result'] as Map?; + final evaluatedAppId = innerResult?['value']; if (evaluatedAppId == appInstanceId) { appTab = tab; executionContext = RemoteDebuggerExecutionContext( @@ -375,7 +379,7 @@ class DevHandler { ), ), ); - } on StateError catch (_) { + } catch (_) { // The sink has already closed (app is disconnected), swallow the // error. } @@ -389,7 +393,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 +446,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 +567,8 @@ 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 +717,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 +810,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 +835,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..d5c566a85 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'; @@ -194,20 +195,34 @@ Future _injectedClientSnippet( final appMetadata = globalToolConfiguration.appMetadata; final debugSettings = globalToolConfiguration.debugSettings; + final reloadedSourcesPathLine = loadStrategy is DdcLibraryBundleStrategy + ? 'window.\$reloadedSourcesPath = ' + '"${loadStrategy.reloadedSourcesUri.toString()}";\n' + : ''; + + final loadClient = loadStrategy.loadClientSnippet(_clientScript); + var injectedBody = 'window.\$dartAppId = "$appId";\n' - 'window.\$dartReloadConfiguration = "${loadStrategy.reloadConfiguration}";\n' - 'window.\$dartModuleStrategy = "${loadStrategy.id}";\n' - 'window.\$loadModuleConfig = ${loadStrategy.loadModuleSnippet};\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.\$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.\$dartEmitDebugEvents = ' + '${debugSettings.emitDebugEvents};\n' + 'window.\$isInternalBuild = ' + '${appMetadata.isInternalBuild};\n' + 'window.\$isFlutterApp = ' + '${buildSettings.isFlutterApp};\n' + '$reloadedSourcesPathLine' + '$loadClient'; 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..c396880e1 100644 --- a/dwds/lib/src/handlers/socket_connections.dart +++ b/dwds/lib/src/handlers/socket_connections.dart @@ -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; @@ -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); diff --git a/dwds/lib/src/loaders/build_runner_require.dart b/dwds/lib/src/loaders/build_runner_require.dart index 459f77d12..5acb77c7c 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'); diff --git a/dwds/lib/src/loaders/ddc.dart b/dwds/lib/src/loaders/ddc.dart index 1ae77faff..dcacfefd4 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; diff --git a/dwds/lib/src/loaders/ddc_library_bundle.dart b/dwds/lib/src/loaders/ddc_library_bundle.dart index 58a0fc949..be683386e 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 { 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..9990af0c8 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 { @@ -112,11 +113,12 @@ class FrontendServerAssetReader implements AssetReader { final sourceInfo = 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; + final start = sourcemap[0] as int; + final end = sourcemap[1] as int; _mapContents[key] = utf8.decode( - sourceContents - .getRange(info['sourcemap'][0] as int, info['sourcemap'][1] as int) - .toList(), + sourceContents.getRange(start, end).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..ce83ee155 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. @@ -90,10 +91,10 @@ class ExtensionDebugger implements RemoteDebugger { 'method': json.decode(message.method), '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: + // Note: package:sse tries to keep the connection alive even after the + // client has been closed. The extension sends an event to notify DWDS + // to close the connection, instead of relying on the done event sent + // when the client is closed. Details: // https://github.com/dart-lang/webdev/pull/1595#issuecomment-1116773378 if (map['method'] == 'DebugExtension.detached') { close(); @@ -174,8 +175,9 @@ class ExtensionDebugger implements RemoteDebugger { ), ), ); - } on StateError catch (error, stackTrace) { - if (error.message.contains('Cannot add event after closing')) { + } on Exception catch (error, stackTrace) { + final message = '$error'; + if (message.contains('Cannot add event after closing')) { _logger.severe('Socket connection closed. Shutting down debugger.'); closeWithError(error); } else { @@ -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(); 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..78f1ade43 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 as Object, 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..82e377d23 100644 --- a/dwds/lib/src/services/chrome/chrome_debug_exception.dart +++ b/dwds/lib/src/services/chrome/chrome_debug_exception.dart @@ -21,7 +21,7 @@ final class ChromeDebugException extends ExceptionDetails implements Exception { this.evalContents, }) : super(exceptionDetails) { final json = exceptionDetails['stackTrace']; - stackTrace = json == null ? null : StackTrace(json); + stackTrace = json == null ? null : StackTrace(json as Map); } @override 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..bf9465834 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 { @@ -1254,7 +1256,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,13 +1273,16 @@ final class ChromeProxyService extends ProxyService { IsolateRef isolateRef, ConsoleAPIEvent event, ) async { - final logObject = event.params?['args'][1] as Map?; + final params = event.params; + final args = params?['args'] as List?; + final logObject = + (args != null && args.length > 1 ? args[1] : null) as Map?; final objectId = logObject?['objectId']; // 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 final logParams = objectId != null - ? await _fetchFullLogParams(objectId, logObject: logObject) + ? await _fetchFullLogParams(objectId as String, logObject: logObject) : _fetchAbbreviatedLogParams(logObject); final logRecord = LogRecord( @@ -1330,7 +1335,9 @@ final class ChromeProxyService extends ProxyService { Map _fetchAbbreviatedLogParams(Map? logObject) { final logParams = {}; - for (final dynamic property in logObject?['preview']?['properties'] ?? []) { + final preview = logObject?['preview'] as Map?; + final properties = preview?['properties'] as List? ?? []; + for (final dynamic property in properties) { if (property is Map && property['name'] != null) { logParams[property['name'] as String] = RemoteObject(property); } diff --git a/dwds/lib/src/services/debug_service.dart b/dwds/lib/src/services/debug_service.dart index 787a277a0..1d04af8f0 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; @@ -21,6 +17,11 @@ import 'package:stream_channel/stream_channel.dart'; import 'package:vm_service/vm_service.dart'; import 'package:vm_service_interface/vm_service_interface.dart'; +import '../config/tool_configuration.dart'; +import '../events.dart'; +import '../utilities/server.dart'; +import 'proxy_service.dart'; + bool _acceptNewConnections = true; final _clientConnections = {}; @@ -37,7 +38,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,7 +165,7 @@ abstract class DebugService { void Function(Map)? onResponse, }) { return _wrapHandler( - webSocketHandler((webSocket, subprotocol) { + webSocketHandler((StreamChannel webSocket, String? subprotocol) { handleConnection( webSocket, proxyService, @@ -180,9 +182,9 @@ abstract class DebugService { return (shelf.Request request) { 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.' - '$_ddsUri.', + 'Cannot connect directly to the VM service as a ' + 'Dart Development Service (DDS) instance has taken control and ' + 'can be found at $_ddsUri.', ); } if (authToken != null && request.url.pathSegments.first != authToken) { @@ -210,8 +212,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 +242,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..63cabc9f2 100644 --- a/dwds/lib/src/services/expression_compiler_service.dart +++ b/dwds/lib/src/services/expression_compiler_service.dart @@ -6,10 +6,11 @@ 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; @@ -107,7 +108,7 @@ class _Compiler { } Future updateDependencies(Map modules) async { - final updateCompleter = Completer(); + final updateCompleter = Completer(); _dependencyUpdate = updateCompleter.future; _logger.info('Updating dependencies...'); diff --git a/dwds/lib/src/services/expression_evaluator.dart b/dwds/lib/src/services/expression_evaluator.dart index b8cb71c37..aa1450559 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..47a9fcf1a 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. @@ -30,9 +31,10 @@ final class DartDevelopmentServiceConnectedEvent extends Event { required super.timestamp, 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.', + '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.', super(kind: 'DartDevelopmentServiceConnected'); final String message; 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..32b8c8283 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); @@ -27,8 +28,9 @@ typedef SendClientRequest = int Function(Object request); 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. +/// This handles the race condition during page refresh where the old +/// connection 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. @@ -212,11 +214,13 @@ final class WebSocketProxyService extends ProxyService { if (isNewConnection) { _activeConnectionCount++; _logger.fine( - 'Adding new connection: $connectionId (total: $_activeConnectionCount)', + 'Adding new connection: $connectionId ' + '(total: $_activeConnectionCount)', ); } else { _logger.fine( - 'Reconnecting existing connection: $connectionId (total: $_activeConnectionCount)', + 'Reconnecting existing connection: $connectionId ' + '(total: $_activeConnectionCount)', ); } @@ -229,10 +233,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 +299,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 + // 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 +319,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 +334,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 +423,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 +445,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 +470,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 +503,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; } @@ -544,7 +560,8 @@ final class WebSocketProxyService extends ProxyService { if (!completer.isCompleted) { completer.completeError( TimeoutException( - 'Hot reload timed out - received ${tracker.responses.length}/$clientCount responses', + 'Hot reload timed out - received ' + '${tracker.responses.length}/$clientCount responses', timeout, ), ); @@ -605,7 +622,8 @@ final class WebSocketProxyService extends ProxyService { if (!completer.isCompleted) { completer.completeError( TimeoutException( - 'Hot restart timed out - received ${tracker.responses.length}/$clientCount responses', + 'Hot restart timed out - received ' + '${tracker.responses.length}/$clientCount responses', timeout, ), ); @@ -660,8 +678,8 @@ final class WebSocketProxyService extends ProxyService { final request = ServiceExtensionRequest.fromArgs( id: requestId, method: method, - // Arguments must be converted to their string representation, otherwise - // we'll encounter a TypeError when trying to cast args to a + // Arguments must be converted to their string representation, + // otherwise we'll encounter a TypeError when trying to cast args to a // Map in the service extension handler. args: args.map( (k, v) => MapEntry( @@ -688,7 +706,8 @@ final class WebSocketProxyService extends ProxyService { if (!completer.isCompleted) { completer.completeError( TimeoutException( - 'Service extension $method timed out - received ${tracker.responses.length}/$clientCount responses', + 'Service extension $method timed out - received ' + '${tracker.responses.length}/$clientCount responses', timeout, ), ); @@ -864,7 +883,8 @@ final class WebSocketProxyService extends ProxyService { ); } - // Return empty stack since we're in WebSocket mode without Chrome debugging + // Return empty stack since we're in WebSocket mode without Chrome + // debugging return vm_service.Stack( frames: [], asyncCausalFrames: [], @@ -873,7 +893,8 @@ final class WebSocketProxyService extends ProxyService { } } -/// Extended ReloadReport that includes additional metadata in JSON output. +/// Extended ReloadReport that includes additional metadata in JSON +/// output. class _ReloadReportWithMetadata extends vm_service.ReloadReport { final List? notices; _ReloadReportWithMetadata({super.success, this.notices}); diff --git a/dwds/lib/src/utilities/dart_uri.dart b/dwds/lib/src/utilities/dart_uri.dart index 066f6f5ed..adbc091f8 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 { @@ -190,7 +191,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/server.dart b/dwds/lib/src/utilities/server.dart index e67dfe355..d9201ec42 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,8 +72,8 @@ 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; @@ -85,8 +86,8 @@ void handleErrorIfPresent(wip.WipResponse? response, {String? evalContents}) { } /// Returns result contained in the response. -/// Throws an [wip.ExceptionDetails] object if `exceptionDetails` is present on the -/// result or the result is null. +/// Throws an [wip.ExceptionDetails] object if `exceptionDetails` is present on +/// the result or the result is null. Map getResultOrHandleError( wip.WipResponse? response, { String? evalContents, @@ -98,5 +99,5 @@ Map getResultOrHandleError( 'text': 'null result from Chrome Devtools', }, evalContents: evalContents); } - return result; + return result as Map; } diff --git a/dwds/lib/src/utilities/shared.dart b/dwds/lib/src/utilities/shared.dart index 1a55bdaf6..f60cf151c 100644 --- a/dwds/lib/src/utilities/shared.dart +++ b/dwds/lib/src/utilities/shared.dart @@ -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..ad6075ac4 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,10 @@ dev_dependencies: build_version: ^2.1.1 build_web_compilers: ^4.4.1 built_value_generator: ^8.4.2 - graphs: ^2.1.0 + dart_flutter_team_lints: any 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..40ebf4669 100644 --- a/dwds/test/common/chrome_proxy_service_common.dart +++ b/dwds/test/common/chrome_proxy_service_common.dart @@ -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 5bb24d459..37e7ec9ac 100644 --- a/dwds/test/dart_uri_test.dart +++ b/dwds/test/dart_uri_test.dart @@ -156,8 +156,8 @@ void main() { final logs = []; void logWriter( - level, - message, { + Object? level, + String message, { String? error, String? loggerName, String? stackTrace, @@ -207,7 +207,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..f6639fbbd 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'}, }); @@ -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..89de333f0 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,131 @@ 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 +174,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 +187,7 @@ void main() { () { setUp(() async { await context.setUp( - debugSettings: TestDebugSettings.noDevToolsLaunch().copyWith( + debugSettings: const TestDebugSettings.noDevToolsLaunch().copyWith( enableDebugExtension: true, ), ); @@ -208,7 +204,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 +215,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..c2e700c9f 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 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,7 +917,8 @@ 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) => 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..4ac9879ea 100644 --- a/dwds/test/execution_context_test.dart +++ b/dwds/test/execution_context_test.dart @@ -144,7 +144,7 @@ class TestExtensionDebugger extends ExtensionDebugger { String command, { 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({ @@ -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..8f2f14012 100644 --- a/dwds/test/expression_evaluator_test.dart +++ b/dwds/test/expression_evaluator_test.dart @@ -133,7 +133,7 @@ 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..3e353ed68 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'}) @@ -51,8 +52,12 @@ void main() async { connection.controllerIncoming.sink.add( jsonEncode(serializers.serialize(extensionResponse)), ); - final response = await resultCompleter.future; - expect(response.result['result']['value'], 3.14); + final response = await resultCompleter.future as WipResponse; + expect( + ((response.result as Map)['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..5aa4be57b 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, @@ -382,7 +382,8 @@ class TestContext { () async => {}, buildSettings, reloadedSourcesUri: Uri.parse( - 'http://localhost:$port/${WebDevFS.reloadedSourcesFileName}', + 'http://localhost:$port/' + '${WebDevFS.reloadedSourcesFileName}', ), ).strategy : FrontendServerDdcStrategyProvider( @@ -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..04768bcf0 100644 --- a/dwds/test/fixtures/debugger_data.dart +++ b/dwds/test/fixtures/debugger_data.dart @@ -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..d1e5ce0c3 100644 --- a/dwds/test/fixtures/fakes.dart +++ b/dwds/test/fixtures/fakes.dart @@ -80,9 +80,10 @@ class FakeChromeAppInspector extends FakeInspector 'Runtime.getProperties', params: {'objectId': objectId, 'ownProperties': true}, ); - final result = response.result?['result']; + final result = response.result?['result'] as List?; + if (result == null) return []; return result - .map((each) => Property(each as Map)) + .map((dynamic each) => Property(each as Map)) .toList(); } @@ -212,9 +213,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 +235,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; @@ -292,16 +294,16 @@ class FakeWebkitDebugger implements WebkitDebugger { 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( @@ -424,7 +426,7 @@ class FakeAssetReader implements AssetReader { String? metadata; final String? _dartSource; final String? _sourceMap; - FakeAssetReader({this.metadata, dartSource, sourceMap}) + FakeAssetReader({this.metadata, String? dartSource, String? sourceMap}) : _dartSource = dartSource, _sourceMap = sourceMap; 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/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_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..e4f857845 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, @@ -96,7 +100,7 @@ void runTests({ final instanceRef = await getInstanceRef(frame, 'record'); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordClass); + expect(await getObject(classId!), matchRecordClass); final stringRef = await getInstanceRef(frame, 'record.toString()'); final stringRefId = stringRef.id!; @@ -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), + {}, + ); }); }); @@ -160,7 +170,7 @@ void runTests({ final instanceRef = await getInstanceRef(frame, 'record'); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordClass); + expect(await getObject(classId!), matchRecordClass); final stringRef = await getInstanceRef(frame, 'record.toString()'); final stringId = stringRef.id!; @@ -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), + {}, + ); }); }); @@ -227,7 +243,7 @@ void runTests({ final instanceRef = await getInstanceRef(frame, 'record'); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordClass); + expect(await getObject(classId!), matchRecordClass); final stringRef = await getInstanceRef(frame, 'record.toString()'); final stringId = stringRef.id!; @@ -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), + {}, + ); }); }); @@ -315,7 +337,7 @@ void runTests({ final instanceRef = await getInstanceRef(frame, 'record'); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordClass); + expect(await getObject(classId!), matchRecordClass); final stringRef = await getInstanceRef(frame, 'record.toString()'); final stringId = stringRef.id!; @@ -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), + {}, + ); }); }); @@ -403,7 +431,7 @@ void runTests({ final instanceRef = await getInstanceRef(frame, 'record'); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordClass); + expect(await getObject(classId!), matchRecordClass); final stringRef = await getInstanceRef(frame, 'record.toString()'); final stringId = stringRef.id!; @@ -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), + {}, + ); }); }); @@ -474,7 +508,7 @@ void runTests({ final instanceRef = await getInstanceRef(frame, 'record'); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordClass); + expect(await getObject(classId!), matchRecordClass); final stringRef = await getInstanceRef(frame, 'record.toString()'); final stringId = stringRef.id!; @@ -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..3d5272891 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) => @@ -97,7 +101,7 @@ void runTests({ expect(await getObject(instanceId), matchRecordTypeInstance(length: 2)); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordTypeClass); + expect(await getObject(classId!), matchRecordTypeClass); }); }); @@ -156,7 +160,7 @@ void runTests({ expect(await getObject(instanceId), matchRecordTypeInstance(length: 3)); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordTypeClass); + expect(await getObject(classId!), matchRecordTypeClass); }); }); @@ -220,7 +224,7 @@ void runTests({ expect(await getObject(instanceId), matchRecordTypeInstance(length: 3)); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordTypeClass); + expect(await getObject(classId!), matchRecordTypeClass); }); }); @@ -285,7 +289,7 @@ void runTests({ expect(await getObject(instanceId), matchRecordTypeInstance(length: 2)); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordTypeClass); + expect(await getObject(classId!), matchRecordTypeClass); }); }); @@ -359,7 +363,7 @@ void runTests({ expect(instance, matchRecordTypeInstance(length: 2)); final classId = instanceRef.classRef!.id; - expect(await getObject(classId), matchRecordTypeClass); + expect(await getObject(classId!), matchRecordTypeClass); }); }); @@ -411,7 +415,7 @@ void runTests({ final instance = await getObject(instanceRef.id!); final typeClassId = instance.classRef!.id; - expect(await getObject(typeClassId), matchRecordTypeClass); + expect(await getObject(typeClassId!), matchRecordTypeClass); final typeStringRef = await getInstanceRef( frame, diff --git a/dwds/test/instances/common/test_inspector.dart b/dwds/test/instances/common/test_inspector.dart index 0dc201e3d..5a33a75f2 100644 --- a/dwds/test/instances/common/test_inspector.dart +++ b/dwds/test/instances/common/test_inspector.dart @@ -272,19 +272,23 @@ class TestInspector { Map _associationsToMap( Iterable associations, ) => Map.fromEntries( - associations.map((e) => MapEntry(e.key.valueAsString, e.value)), + associations.map( + (e) => MapEntry(e.key.valueAsString as String, e.value as InstanceRef), + ), ); 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.fromEntries( fields .where((e) => e != null) - .map((e) => MapEntry(fields.indexOf(e), e!)), + .map((e) => MapEntry(fields.indexOf(e), e as InstanceRef)), ); Matcher matchRecordInstanceRef({required int length}) => isA() @@ -312,16 +316,18 @@ Matcher matchPrimitiveInstance({ .having((e) => e.kind, 'kind', kind) .having(_getValue, 'value', value); -Matcher matchPlainInstance({required libraryId, required String type}) => - isA() - .having((e) => e.kind, 'kind', InstanceKind.kPlainInstance) - .having( - (e) => e.classRef, - 'classRef', - matchClassRef(name: type, libraryId: libraryId), - ); +Matcher matchPlainInstance({ + required dynamic libraryId, + required String type, +}) => isA() + .having((e) => e.kind, 'kind', InstanceKind.kPlainInstance) + .having( + (e) => e.classRef, + 'classRef', + 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)); diff --git a/dwds/test/instances/common/type_inspection_common.dart b/dwds/test/instances/common/type_inspection_common.dart index 46ce1d081..80360e799 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/metadata/class_test.dart b/dwds/test/metadata/class_test.dart index 6bf247cb8..08a12fd60 100644 --- a/dwds/test/metadata/class_test.dart +++ b/dwds/test/metadata/class_test.dart @@ -19,7 +19,7 @@ void main() { var metadata = createMetadata(null); expect(metadata.length, isNull); - metadata = createMetadata({}); + metadata = createMetadata({}); expect(metadata.length, isNull); metadata = createMetadata('{}'); diff --git a/dwds/test/puppeteer/extension_common.dart b/dwds/test/puppeteer/extension_common.dart index 11b28962e..46e4aaa3e 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'; @@ -531,7 +531,7 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { 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)); if (isFlutterApp) { await _tabLeft(chromeDevToolsPage); final inspectorPanelElement = await _getPanelElement( @@ -564,7 +564,7 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { 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) { @@ -630,7 +630,7 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { 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) { @@ -674,7 +674,7 @@ void testAll({required bool isMV3, required bool screenshotsEnabled}) { 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) { @@ -691,7 +691,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, @@ -748,7 +748,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 +872,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 (_) { @@ -952,7 +952,7 @@ Future _fetchStorageObj( worker: worker, backgroundPage: backgroundPage, ); - return storageObj[storageKey]; + return storageObj[storageKey] as String; }); if (T == String) return json as T; return serializers.deserialize(jsonDecode(json)) as T; @@ -1014,7 +1014,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 +1037,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..e2cc34a6d 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 List _backgroundLogs = []; +final List _devToolsLogs = []; +final List _workerLogs = []; Future buildDebugExtension({required bool isMV3}) async { final extensionDir = absolutePath(pathFromDwds: 'debug_extension'); @@ -160,7 +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)); + await Future.delayed(const Duration(seconds: 1)); return; } 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..572dea831 100644 --- a/dwds/test/run_request_test.dart +++ b/dwds/test/run_request_test.dart @@ -45,7 +45,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( diff --git a/dwds/test/utilities_test.dart b/dwds/test/utilities_test.dart index 8b9f42881..58193a2e6 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'); } 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/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_hot_reload/pubspec.yaml b/fixtures/_test_hot_reload/pubspec.yaml index 7a2c88f4a..770f19d00 100644 --- a/fixtures/_test_hot_reload/pubspec.yaml +++ b/fixtures/_test_hot_reload/pubspec.yaml @@ -4,4 +4,4 @@ description: >- A fake package used for testing hot reload. publish_to: none environment: - sdk: ^3.10.0-0.0.dev + sdk: ^3.10.0-0.0.dev \ No newline at end of file diff --git a/frontend_server_common/LICENSE b/frontend_server_common/LICENSE index ed0a3506e..8d29cdcc1 100644 --- a/frontend_server_common/LICENSE +++ b/frontend_server_common/LICENSE @@ -24,4 +24,4 @@ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/frontend_server_common/analysis_options.yaml b/frontend_server_common/analysis_options.yaml index 1167fdd9f..3ca57b1b6 100644 --- a/frontend_server_common/analysis_options.yaml +++ b/frontend_server_common/analysis_options.yaml @@ -1 +1 @@ -include: package:analysis_config/analysis_options.yaml +include: package:analysis_config/analysis_options.yaml \ No newline at end of file diff --git a/frontend_server_common/mono_pkg.yaml b/frontend_server_common/mono_pkg.yaml index 11ffe8363..76fcd2ef8 100644 --- a/frontend_server_common/mono_pkg.yaml +++ b/frontend_server_common/mono_pkg.yaml @@ -4,4 +4,4 @@ stages: - group: - format - analyze: --fatal-infos . - sdk: dev + sdk: dev \ No newline at end of file diff --git a/frontend_server_common/pubspec.yaml b/frontend_server_common/pubspec.yaml index 7b3c1520e..a6dab8067 100644 --- a/frontend_server_common/pubspec.yaml +++ b/frontend_server_common/pubspec.yaml @@ -20,4 +20,4 @@ dependencies: dev_dependencies: analysis_config: - path: ../_analysis_config + path: ../_analysis_config \ No newline at end of file diff --git a/frontend_server_common/pubspec_overrides.yaml b/frontend_server_common/pubspec_overrides.yaml index d3d78b8af..3463d2bbf 100644 --- a/frontend_server_common/pubspec_overrides.yaml +++ b/frontend_server_common/pubspec_overrides.yaml @@ -1,3 +1,3 @@ dependency_overrides: dwds: - path: ../dwds + path: ../dwds \ No newline at end of file