All files Headers.ts

100% Statements 32/32
100% Branches 14/14
100% Functions 6/6
100% Lines 32/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62  3x 3x                 3x 29x 2x 27x 20x     35x 34x     7x 6x 17x     1x     3x 9x 9x 20x 9x 6x   9x 12x 13x         9x     3x 11x 11x 24x 13x 8x   13x 23x       11x    
import { JSONPrimitive } from '@battis/typescript-tricks';
import { isJSONEntries, isJSONRecord } from './is.js';
import * as String from './String.js';
 
export type ish =
  | Headers
  | HeadersInit
  | Record<string, JSONPrimitive | undefined>
  | [string, JSONPrimitive | undefined][]
  | undefined;
 
export function from(headers?: ish): Headers {
  if (headers instanceof Headers) {
    return headers;
  } else if (isJSONRecord(headers)) {
    return new Headers(
      Object.fromEntries(
        Object.entries(headers)
          .filter(([_, value]) => value !== undefined)
          .map(([key, value]) => [key, String.from(value)])
      )
    );
  } else if (isJSONEntries(headers)) {
    return new Headers(
      headers.map(([key, value]) => [key, String.from(value)])
    );
  }
  return new Headers(headers);
}
 
export function merge(...sources: ish[]): Headers | undefined {
  let headers: Headers | undefined = undefined;
  for (const source of sources) {
    if (source) {
      if (!headers) {
        headers = new Headers();
      }
      for (const [key, value] of from(source).entries()) {
        for (const v of value.split(', ')) {
          headers.set(key, v);
        }
      }
    }
  }
  return headers;
}
 
export function concatenate(...sources: ish[]): Headers | undefined {
  let headers: Headers | undefined = undefined;
  for (const source of sources) {
    if (source) {
      if (!headers) {
        headers = new Headers();
      }
      for (const [key, value] of from(source).entries()) {
        headers.append(key, value);
      }
    }
  }
  return headers;
}