Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions packages/komodo_defi_framework/lib/src/js/js_error_utils.dart
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 packages/komodo_defi_framework/lib/src/js/js_interop_utils.dart
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;
Comment thread
takenagain marked this conversation as resolved.
}
56 changes: 56 additions & 0 deletions packages/komodo_defi_framework/lib/src/js/js_result_mappers.dart
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;
}
Loading
Loading