all files / src/ index.js

100% Statements 63/63
100% Branches 25/25
100% Functions 11/11
100% Lines 63/63
3 statements, 2 branches Ignored     
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184                                                                                                                                                                                                   17×           11×       10×       10×                          
const HTTP = 'http:'
    , HTTPS = 'https:'
    , url = require('url');
 
class HttpResolver {
  constructor(state, href, parent) {
    this.state = state;
    this.href = href;
    this.parent = parent;
    this.uri = url.parse(href);
 
    this._file = null;
  }
 
  set file(val) {
    this._file = val; 
  }
 
  get file() {
    return this._file;
  }
 
  /**
   *  Allows resolver implementations to load file content from a remote 
   *  resource.
   */
  getFileContents(cb) {
    const zlib = require('zlib')
        , http = require('http');
 
    let called = false;
 
    function done(err, buf) {
      /* istanbul ignore next: guard against multiple events firing */
      Iif(called) {
        return; 
      }
      cb(err, buf);
      called = true;
    }
 
    // ensure we are resolved relative to a parent
    this.uri = url.parse(this.getCanonicalPath());
 
    if(!this.uri.protocol) {
      return cb(
        new Error('https resolver attempt to load with no protocol')); 
    }
 
    let pth = this.uri.pathname;
 
    const uri = url.format(this.uri)
        , options = {
            hostname: this.uri.hostname,
            port: this.uri.port,
            path: pth,
            headers: {
              'Accept': 'text/html'
            }
          };
 
    this.getDefaultPort(this.uri.protocol, options);
 
    const req = http.get(options, (res) => {
      // expecting 200 response
      if(res.statusCode !== 200) {
        return done(
          new Error(
            `unexpected status code ${res.statusCode} from ${uri}`));
      }
 
      const contentType = res.headers['content-type']
          , encoding = res.headers['content-encoding'];
 
      let gzip = false;
 
      if(!/text\/html/.test(contentType)) {
        return done(
          new Error(`unexpected content type ${contentType}`)) ;
      }
 
      if(encoding && ~encoding.indexOf('gzip')) {
        gzip = true;
      }
 
      let buf = new Buffer(0);
 
      // consume response body
      res.resume();
 
      res.on('data', (chunk) => {
        buf = Buffer.concat([buf, chunk], buf.length + chunk.length); 
      })
 
      // handle response error
      res.once('error', (err) => {
        /* istanbul ignore next: tough to mock repsonse stream error */
        done(err); 
      });
 
      res.once('end', () => {
        if(gzip) {
          zlib.gunzip(buf, (err, contents) => {
            /* istanbul ignore next: not going to mock zlib deflate error */
            Iif(err) {
              return done(err); 
            }
            done(null, contents); 
          });
        }else{
          done(null, buf); 
        }
      });
    })
 
    // handle request error
    req.once('error', (err) => {
      done(err); 
    })
  }
 
  /**
   *  Allows resolvers for remote protocols to fetch resources from 
   *  the network.
   */
  fetch(cb) {
    cb(); 
  }
 
  /**
   *  Called after fetch has been invoked so that the resolver may return 
   *  a new filesystem path for downloaded content.
   */
  getResolvedPath() {
    return this.getCanonicalPath(); 
  }
 
  /**
   *  Get a canonical path for the URL reference, used to determine if the 
   *  resource has already been processed.
   */
  getCanonicalPath() {
 
    // no scheme with a parent, resolve relative to the parent
    if(!this.uri.protocol && this.parent && this.parent.file) {
      return url.resolve(this.parent.file, this.href);
    }
 
    // TODO: use url.format() ?
 
    // should be an absolute HTTP/HTTPS URL
    return this.href;
  }
 
  getDefaultPort(protocol, options) {
    if(!options.port) {
      if(protocol === HTTP) {
        options.port = 80;
      }else{
        options.port = 443;
      }
    }
    return options;
  }
}
 
HttpResolver.HTTP = HTTP;
HttpResolver.HTTPS = HTTPS;
 
/**
 *  Resolver for the default http:// and https:// protocols.
 */
function http(/*state, conf*/) {
  return function(registry) {
    //console.log('registering resolvers %s', HTTP);
    registry.register(HTTP, HttpResolver);
    registry.register(HTTPS, HttpResolver);
  }
}
 
http.Resolver = HttpResolver;
 
module.exports = http;