-
Notifications
You must be signed in to change notification settings - Fork 9
fix(wasm-ops): fix example app login by improving JS call error handling #185
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
62 changes: 62 additions & 0 deletions
62
packages/komodo_defi_framework/lib/src/js/js_error_utils.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| /// Utilities for extracting error codes and messages from dartified JS values. | ||
| /// | ||
| /// Provides functions to extract numeric error codes and human-readable messages | ||
| /// from dartified JavaScript error objects, as well as heuristics for common | ||
| /// error patterns. | ||
| library; | ||
|
|
||
| bool _isFiniteNum(num value) => value.isFinite; | ||
|
|
||
| /// Attempts to extract a numeric error code from a dartified JS error/value. | ||
| /// | ||
| /// Supported shapes: | ||
| /// - int or num (finite) | ||
| /// - String containing an integer | ||
| /// - Map with `code` or `result` as int/num/stringified-int | ||
| int? extractNumericCodeFromDartError(dynamic value) { | ||
| if (value is int) return value; | ||
| if (value is num) return _isFiniteNum(value) ? value.toInt() : null; | ||
|
|
||
| if (value is String) { | ||
| final parsed = int.tryParse(value); | ||
| if (parsed != null) return parsed; | ||
| } | ||
|
|
||
| if (value is Map) { | ||
| final dynamic code = value['code'] ?? value['result']; | ||
| if (code is int) return code; | ||
| if (code is num) return _isFiniteNum(code) ? code.toInt() : null; | ||
| if (code is String) { | ||
| final parsed = int.tryParse(code); | ||
| if (parsed != null) return parsed; | ||
| } | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| /// Attempts to extract a human-readable message from a dartified JS error/value. | ||
| /// | ||
| /// Supported shapes: | ||
| /// - String | ||
| /// - Map with `message` or `error` as String | ||
| String? extractMessageFromDartError(dynamic value) { | ||
| if (value is String) return value; | ||
| if (value is Map) { | ||
| final dynamic message = value['message'] ?? value['error']; | ||
| if (message is String && message.isNotEmpty) return message; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| const List<String> _alreadyRunningPatterns = [ | ||
| 'already running', | ||
| 'already_running', | ||
| ]; | ||
|
|
||
| // TODO: generalise to a log/string-based watcher for other KDF errors | ||
| /// Heuristic matcher for common "already running" messages. | ||
| bool messageIndicatesAlreadyRunning(String message) { | ||
| final lower = message.toLowerCase(); | ||
| return _alreadyRunningPatterns.any(lower.contains); | ||
| } |
146 changes: 146 additions & 0 deletions
146
packages/komodo_defi_framework/lib/src/js/js_interop_utils.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| // ignore_for_file: avoid_dynamic_calls | ||
|
|
||
| import 'dart:convert'; | ||
| import 'dart:js_interop' as js_interop; | ||
|
|
||
| import 'package:komodo_defi_types/komodo_defi_type_utils.dart'; | ||
| import 'package:logging/logging.dart'; | ||
|
|
||
| final Logger _jsInteropLogger = Logger('JsInteropUtils'); | ||
|
|
||
| /// Parses a JS interop response into a JsonMap. | ||
| /// | ||
| /// Accepts: | ||
| /// - JSAny/JSObject (will be dartified) | ||
| /// - Map (with non-string keys will be normalized) | ||
| /// - String (JSON encoded) | ||
| /// | ||
| /// Throws a [FormatException] if the response cannot be parsed into a JSON map. | ||
| JsonMap parseJsInteropJson(dynamic jsResponse) { | ||
| try { | ||
| dynamic value = jsResponse; | ||
|
|
||
| // If we received a JS value, convert to Dart first | ||
| if (value is js_interop.JSAny?) { | ||
| value = value?.dartify(); | ||
| } | ||
|
|
||
| if (value is String) { | ||
| final decoded = jsonDecode(value); | ||
| if (decoded is Map) { | ||
| return _deepConvertMap(decoded); | ||
| } | ||
| throw const FormatException('Expected JSON object string'); | ||
| } | ||
|
|
||
| if (value is Map) { | ||
| return _deepConvertMap(value); | ||
| } | ||
|
|
||
| throw FormatException('Unexpected JS response type: ${value.runtimeType}'); | ||
| } catch (e, s) { | ||
| _jsInteropLogger.severe('Error parsing JS interop response', e, s); | ||
| rethrow; | ||
| } | ||
| } | ||
|
|
||
| /// Generic helper that parses a JS response and maps it to a Dart model. | ||
| T parseJsInteropCall<T>(dynamic jsResponse, T Function(JsonMap) fromJson) { | ||
| final map = parseJsInteropJson(jsResponse); | ||
| return fromJson(map); | ||
| } | ||
|
|
||
| // Recursively converts the provided map to JsonMap by stringifying keys and | ||
| // converting nested maps/lists to JSON-friendly structures. | ||
| JsonMap _deepConvertMap(Map<dynamic, dynamic> map) { | ||
| return map.map((key, value) { | ||
| if (value is Map) return MapEntry(key.toString(), _deepConvertMap(value)); | ||
| if (value is List) { | ||
| return MapEntry(key.toString(), _deepConvertList(value)); | ||
| } | ||
| return MapEntry(key.toString(), value); | ||
| }); | ||
| } | ||
|
|
||
| List<dynamic> _deepConvertList(List<dynamic> list) { | ||
| return list.map((value) { | ||
| if (value is Map) return _deepConvertMap(value); | ||
| if (value is List) return _deepConvertList(value); | ||
| return value; | ||
| }).toList(); | ||
| } | ||
|
|
||
| /// Resolves a JS interop value that might be a Promise into a Dart value. | ||
| /// | ||
| /// - If [jsValue] is a JSPromise, it awaits the promise, then dartifies it | ||
| /// - If [jsValue] is not a JSPromise, it is dartified directly | ||
| /// - Returns the dartified dynamic value | ||
| Future<dynamic> resolveJsAnyMaybePromise(js_interop.JSAny? jsValue) async { | ||
| if (jsValue is js_interop.JSPromise) { | ||
| final resolved = await jsValue.toDart; | ||
| return resolved?.dartify(); | ||
| } | ||
| return jsValue?.dartify(); | ||
| } | ||
|
|
||
| /// Generic helper to resolve a JS interop value (maybe a Promise) and map it. | ||
| /// | ||
| /// After resolution and dartification, the provided [mapper] is used to convert | ||
| /// the dynamic result into type [T]. | ||
| Future<T> parseJsInteropMaybePromise<T>( | ||
| js_interop.JSAny? jsValue, [ | ||
| T Function(dynamic dartValue)? mapper, | ||
| ]) async { | ||
| final dartValue = await resolveJsAnyMaybePromise(jsValue); | ||
|
|
||
| // If a mapper was provided, use it | ||
| if (mapper != null) { | ||
| return mapper(dartValue); | ||
| } | ||
|
|
||
| // Allow common primitive/collection types without a mapper | ||
| if (T == dynamic || T == Object) { | ||
| return dartValue as T; | ||
| } | ||
| if (T == int) { | ||
| if (dartValue is int) return dartValue as T; | ||
| if (dartValue is num) return dartValue.toInt() as T; | ||
| if (dartValue is String) { | ||
| final parsed = int.tryParse(dartValue); | ||
| if (parsed != null) return parsed as T; | ||
| } | ||
| } | ||
| if (T == double || T == num) { | ||
| if (dartValue is num) { | ||
| if (T == double) return dartValue.toDouble() as T; | ||
| return dartValue as T; // T == num | ||
| } | ||
| if (dartValue is String) { | ||
| final parsed = double.tryParse(dartValue); | ||
| if (parsed != null) { | ||
| if (T == num) { | ||
| final num n = parsed; | ||
| return n as T; | ||
| } else { | ||
| final double d = parsed; | ||
| return d as T; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if (T == String) { | ||
| if (dartValue is String) return dartValue as T; | ||
| } | ||
| if (T == bool) { | ||
| if (dartValue is bool) return dartValue as T; | ||
| } | ||
| if (T == Map || T == Map<String, dynamic>) { | ||
| if (dartValue is Map) return dartValue as T; | ||
| } | ||
| if (T == List || T == List<dynamic>) { | ||
| if (dartValue is List) return dartValue as T; | ||
| } | ||
|
|
||
| // Fallback: attempt a direct cast; this will surface a clear type error | ||
| return dartValue as T; | ||
| } | ||
56 changes: 56 additions & 0 deletions
56
packages/komodo_defi_framework/lib/src/js/js_result_mappers.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import 'package:komodo_defi_framework/src/operations/kdf_operations_interface.dart'; | ||
| import 'package:logging/logging.dart'; | ||
|
|
||
| final _logger = Logger('JsResultMappers'); | ||
|
|
||
| /// Maps the various possible JS return shapes from `mm2_stop` into [StopStatus]. | ||
| /// | ||
| /// Accepts: | ||
| /// - `null` (treated as OK for backward-compatibility with legacy behavior) | ||
| /// - Numeric codes (int/num) | ||
| /// - String responses like "success", "ok", "already_stopped", or a stringified | ||
| /// integer code | ||
| /// - Objects/Maps that may contain `error`, `result`, or `code` fields | ||
| StopStatus mapJsStopResult(dynamic result) { | ||
| if (result == null) return StopStatus.ok; | ||
|
|
||
| if (result is int) return StopStatus.fromDefaultInt(result); | ||
| if (result is num) return StopStatus.fromDefaultInt(result.toInt()); | ||
|
|
||
| if (result is String) { | ||
| final normalized = result.trim().toLowerCase(); | ||
| if (normalized == 'success' || normalized == 'ok') { | ||
| return StopStatus.ok; | ||
| } | ||
| if (normalized == 'already_stopped' || normalized.contains('already')) { | ||
| return StopStatus.stoppingAlready; | ||
| } | ||
| final maybeCode = int.tryParse(result); | ||
| if (maybeCode != null) return StopStatus.fromDefaultInt(maybeCode); | ||
| return StopStatus.ok; | ||
| } | ||
|
|
||
| if (result is Map) { | ||
| final map = result; | ||
| if (map.containsKey('error') && map['error'] != null) { | ||
| return StopStatus.errorStopping; | ||
| } | ||
| final inner = map['result']; | ||
| if (inner is String) return mapJsStopResult(inner); | ||
| if (inner is num) return StopStatus.fromDefaultInt(inner.toInt()); | ||
|
|
||
| final code = map['code']; | ||
| if (code is num) return StopStatus.fromDefaultInt(code.toInt()); | ||
|
|
||
| // Log unexpected map structure for debugging | ||
| _logger.fine( | ||
| 'Unexpected map structure in stop result, defaulting to ok: $map', | ||
| ); | ||
| return StopStatus.ok; | ||
| } | ||
|
|
||
| _logger.fine( | ||
| 'Unrecognized stop result type ${result.runtimeType}, defaulting to ok', | ||
| ); | ||
| return StopStatus.ok; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.