normalizeWebSocketUrl function
Normalizes a WebSocket URL string and returns a normalized result.
Handles various input formats:
- http/https schemes are converted to ws/wss
- Paths without a scheme get 'ws://' prepended
- Invalid URIs are normalized with spaces removed
Implementation
RealtimeNormalizedUrl normalizeWebSocketUrl(String input) {
final trimmed = input.trim();
if (trimmed.isEmpty) {
throw ArgumentError.value(
input,
'input',
'MongoRealtime requires a non-empty WebSocket URL.',
);
}
final hasScheme = RegExp(r'^[a-zA-Z][a-zA-Z0-9+\-.]*://').hasMatch(trimmed);
final candidate = hasScheme ? trimmed : 'ws://$trimmed';
final uri = Uri.tryParse(candidate);
if (uri == null) {
return RealtimeNormalizedUrl(
url: 'ws://${trimmed.replaceAll(' ', '')}',
warning:
'Could not fully parse "$input" and normalized it to a ws:// URL.',
);
}
final scheme = uri.scheme.toLowerCase();
if (scheme == 'ws' || scheme == 'wss') {
return RealtimeNormalizedUrl(url: uri.toString());
}
if (scheme == 'http' || scheme == 'https') {
final replacement = uri.replace(scheme: scheme == 'https' ? 'wss' : 'ws');
return RealtimeNormalizedUrl(
url: replacement.toString(),
warning: 'Normalized "$input" from $scheme to ${replacement.scheme}.',
);
}
final normalized = uri.replace(scheme: 'ws');
return RealtimeNormalizedUrl(
url: normalized.toString(),
warning:
'MongoRealtime normalized the unsupported "$scheme" scheme in "$input" to ws.',
);
}