11from dataclasses import dataclass
2- import json
32from urllib .parse import urlparse
43from typing import Dict , Mapping , Optional
54import os
65
76from .exceptions import HyperbrowserError
7+ from .header_utils import normalize_headers , parse_headers_env_json
88
99
1010@dataclass
@@ -36,25 +36,10 @@ def __post_init__(self) -> None:
3636 raise HyperbrowserError (
3737 "base_url must start with 'https://' or 'http://' and include a host"
3838 )
39- if self .headers is not None :
40- normalized_headers : Dict [str , str ] = {}
41- for key , value in self .headers .items ():
42- if not isinstance (key , str ) or not isinstance (value , str ):
43- raise HyperbrowserError ("headers must be a mapping of string pairs" )
44- normalized_key = key .strip ()
45- if not normalized_key :
46- raise HyperbrowserError ("header names must not be empty" )
47- if (
48- "\n " in normalized_key
49- or "\r " in normalized_key
50- or "\n " in value
51- or "\r " in value
52- ):
53- raise HyperbrowserError (
54- "headers must not contain newline characters"
55- )
56- normalized_headers [normalized_key ] = value
57- self .headers = normalized_headers
39+ self .headers = normalize_headers (
40+ self .headers ,
41+ mapping_error_message = "headers must be a mapping of string pairs" ,
42+ )
5843
5944 @classmethod
6045 def from_env (cls ) -> "ClientConfig" :
@@ -72,23 +57,4 @@ def from_env(cls) -> "ClientConfig":
7257
7358 @staticmethod
7459 def parse_headers_from_env (raw_headers : Optional [str ]) -> Optional [Dict [str , str ]]:
75- if raw_headers is None or not raw_headers .strip ():
76- return None
77- try :
78- parsed_headers = json .loads (raw_headers )
79- except json .JSONDecodeError as exc :
80- raise HyperbrowserError (
81- "HYPERBROWSER_HEADERS must be valid JSON object"
82- ) from exc
83- if not isinstance (parsed_headers , dict ):
84- raise HyperbrowserError (
85- "HYPERBROWSER_HEADERS must be a JSON object of string pairs"
86- )
87- if any (
88- not isinstance (key , str ) or not isinstance (value , str )
89- for key , value in parsed_headers .items ()
90- ):
91- raise HyperbrowserError (
92- "HYPERBROWSER_HEADERS must be a JSON object of string pairs"
93- )
94- return parsed_headers
60+ return parse_headers_env_json (raw_headers )
0 commit comments