import { Transform, TransformOptions } from 'stream';

interface HeaderHostTransformerOptions extends TransformOptions {
  host?: string;
}

class HeaderHostTransformer extends Transform {
  private host: string;
  private replaced: boolean;

  constructor(opts: HeaderHostTransformerOptions = {}) {
    super(opts);
    this.host = opts.host || 'localhost';
    this.replaced = false;
  }

  _transform(
    data: Buffer | string,
    encoding: string,
    callback: (error?: Error | null, data?: any) => void
  ): void {
    callback(
      null,
      this.replaced // after replacing the first instance of the Host header we just become a regular passthrough
        ? data
        : data.toString().replace(/(\r\n[Hh]ost: )\S+/, (match, $1) => {
            this.replaced = true;
            return $1 + this.host;
          })
    );
  }
}

export default HeaderHostTransformer; 