sanitizeImageUrl function

String sanitizeImageUrl(
  1. String url
)

Sanitizes an image URL for RUM attributes (BFSI-safe).

Strips userinfo (basic-auth credentials), the query string, and the fragment so credentials / tokens / PII are never exported. Keeps scheme, host, port, and path. data: URIs collapse to data: so the payload is not echoed. The result is truncated to _maxImageUrlLength.

Implementation

String sanitizeImageUrl(String url) {
  final trimmed = url.trim();
  if (trimmed.isEmpty) {
    return trimmed;
  }
  final uri = Uri.tryParse(trimmed);
  // Protocol-relative URLs (`//host/path`) parse with an empty scheme but
  // still have an authority — including userinfo we must strip.
  if (uri == null || (!uri.hasScheme && !uri.hasAuthority)) {
    return _cap(_stripQueryAndFragment(trimmed));
  }

  // Inline payloads (data:, and anything else without a host) carry no useful
  // endpoint identity and may embed the whole image — report the scheme only.
  if (uri.scheme == 'data') {
    return 'data:';
  }

  final buffer = StringBuffer();
  if (uri.hasScheme) {
    buffer
      ..write(uri.scheme)
      ..write(':');
  }
  if (uri.hasAuthority) {
    // uri.host deliberately, not uri.authority: the latter includes userinfo.
    // Re-bracket IPv6 literals — Uri.host strips them, which yields ambiguous
    // host:port forms like http://::1:8080/a.png.
    final host = uri.host;
    buffer
      ..write('//')
      ..write(host.contains(':') ? '[$host]' : host);
    if (uri.hasPort) {
      buffer
        ..write(':')
        ..write(uri.port);
    }
  }
  buffer.write(uri.path);
  return _cap(buffer.toString());
}