All files / logger/src options.ts

100% Statements 15/15
100% Branches 10/10
100% Functions 5/5
100% Lines 15/15

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 63 64 65 66 67            70x                     70x         1639x   1057x 3x   1054x   559x   19x   4x                   70x 22416x 53350x                   70x     5605x   11208x            
import { makeConsoleTransport } from './transports.ts';
import type { LoggerOptions } from './types.ts';
 
/**
 * The default options for the logger.
 */
export const DEFAULT_OPTIONS: Required<LoggerOptions> = {
  transports: [],
  tags: [],
};
 
/**
 * Parses the options for the logger.
 *
 * @param options - The options for the logger.
 * @returns The parsed options.
 */
export const parseOptions = (
  options: LoggerOptions | string | undefined,
): LoggerOptions => {
  // The default case catches whatever is not explicitly handled below.
 
  switch (typeof options) {
    case 'object':
      if (!options.transports) {
        return { transports: [makeConsoleTransport()], ...options };
      }
      return options;
    case 'string':
      return { tags: [options], transports: [makeConsoleTransport()] };
    case 'undefined':
      return { transports: [makeConsoleTransport()] };
    default:
      throw new Error('Invalid logger options');
  }
};
 
/**
 * Returns a copy of an array containing only its unique values.
 *
 * @param array - The array to filter.
 * @returns The array, without duplicate values.
 */
export const unique = <Element>(array: Element[]): Element[] => {
  return array.filter(
    (element, index, self) => self.indexOf(element) === index,
  );
};
 
/**
 * Merges multiple logger options into a single options object.
 *
 * @param options - The options to merge.
 * @returns The merged options.
 */
export const mergeOptions = (
  ...options: LoggerOptions[]
): Required<LoggerOptions> =>
  options.reduce<Required<LoggerOptions>>(
    (acc, option) =>
      ({
        transports: unique([...acc.transports, ...(option.transports ?? [])]),
        tags: unique([...acc.tags, ...(option.tags ?? [])]),
      }) as Required<LoggerOptions>,
    DEFAULT_OPTIONS,
  );