cookieHeader method

String? cookieHeader(
  1. Uri requestUri, {
  2. String? callerCookieHeader,
})

Builds a Cookie request header for requestUri.

callerCookieHeader is merged last, so explicitly supplied caller values replace managed values with the same cookie name.

Implementation

String? cookieHeader(Uri requestUri, {String? callerCookieHeader}) {
  _removeExpired();
  final host = requestUri.host.toLowerCase();
  final path = requestUri.path.isEmpty ? '/' : requestUri.path;
  final isSecure = requestUri.scheme == 'https' || requestUri.scheme == 'wss';
  final matching =
      _cookies.values
          .where(
            (cookie) =>
                _domainMatches(
                  host,
                  cookie.domain,
                  hostOnly: cookie.hostOnly,
                ) &&
                _pathMatches(path, cookie.path) &&
                (!cookie.secure || isSecure),
          )
          .toList()
        ..sort((left, right) {
          final byPath = right.path.length.compareTo(left.path.length);
          return byPath != 0
              ? byPath
              : left.creationOrder.compareTo(right.creationOrder);
        });

  final merged = <String, String>{};
  for (final cookie in matching) {
    merged.putIfAbsent(cookie.name, () => cookie.value);
  }
  for (final pair in _parseCookieHeader(callerCookieHeader)) {
    merged[pair.$1] = pair.$2;
  }
  if (merged.isEmpty) {
    return null;
  }
  return merged.entries
      .map((entry) => '${entry.key}=${entry.value}')
      .join('; ');
}