All files / src/class handler.ts

84.85% Statements 28/33
53.85% Branches 7/13
100% Functions 10/10
80.77% Lines 21/26

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 68 69  15x                 72x             15x           109x 109x       40x 40x 56x       40x 40x 40x 56x     40x     40x       16x         32x 16x 16x   16x 16x 16x                    
import { CompiledFile, Resource } from '@/internal'
import { buildInHandlers } from '@/internal'
 
export interface FileGenerator {
  (file: CompiledFile, resource: Readonly<Resource>): Promise<void>
}
export interface PathGenerator {
  (path: string, resource: Readonly<Resource>): Promise<string>
}
 
const identity: PathGenerator = async path => path
 
interface HandlerDuck {
  genFile: FileGenerator
  genPath: PathGenerator
}
 
export class Handler {
  public genFile: FileGenerator
 
  public genPath: PathGenerator
 
  constructor(genFile: FileGenerator, genPath: PathGenerator = identity) {
    this.genFile = genFile
    this.genPath = genPath
  }
 
  public static compose(handlers: Handler[]): Handler {
    const genFile: FileGenerator = async(file, config) => {
      for (const handler of handlers) {
        await handler.genFile(file, config)
      }
    }
 
    const genPath: PathGenerator = async(string, config) => {
      let str = string
      for (const handler of handlers) {
        str = await handler.genPath(str, config)
      }
 
      return str
    }
 
    return new Handler(genFile, genPath)
  }
 
  public static find(name: string): Handler | null {
    Eif (name in buildInHandlers) return buildInHandlers[name]
    return null
  }
 
  public static format(handler: string | HandlerDuck | ((buildIn) => Handler)): Handler {
    if (typeof handler === 'string') {
      const h = Handler.find(handler)
      Eif (h) return h
      else throw new Error(`Cannot find ${handler} handler `)
    } else Eif (typeof handler === 'function') {
      const h = handler(buildInHandlers)
      Eif (h instanceof Handler) return h
    } else if (typeof handler === 'object') {
      return new Handler(handler.genFile, handler.genPath)
    }
 
    throw new TypeError('Cannot format handler')
  }
}
 
export type Handlers = Handler[]