* Will parse a baggage header, which is a simple key-value map, into a flat object. * * @param baggageHeader The baggage header to parse. * @returns a flat object containing all the key-value pairs from `baggageHeader`.
(baggageHeader: string)
| 111 | * @returns a flat object containing all the key-value pairs from `baggageHeader`. |
| 112 | */ |
| 113 | function baggageHeaderToObject(baggageHeader: string): Record<string, string> { |
| 114 | return baggageHeader |
| 115 | .split(',') |
| 116 | .map(baggageEntry => { |
| 117 | const eqIdx = baggageEntry.indexOf('='); |
| 118 | if (eqIdx === -1) { |
| 119 | // Likely an invalid entry |
| 120 | return []; |
| 121 | } |
| 122 | const key = baggageEntry.slice(0, eqIdx); |
| 123 | const value = baggageEntry.slice(eqIdx + 1); |
| 124 | return [key, value].map(keyOrValue => { |
| 125 | try { |
| 126 | return decodeURIComponent(keyOrValue.trim()); |
| 127 | } catch { |
| 128 | // We ignore errors here, e.g. if the value cannot be URL decoded. |
| 129 | // This will then be skipped in the next step |
| 130 | return; |
| 131 | } |
| 132 | }); |
| 133 | }) |
| 134 | .reduce<Record<string, string>>((acc, [key, value]) => { |
| 135 | if (key && value) { |
| 136 | acc[key] = value; |
| 137 | } |
| 138 | return acc; |
| 139 | }, {}); |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs. |
no test coverage detected