Welcome to mirror list, hosted at ThFree Co, Russian Federation.

request.js « lib « npm-registry-client « node_modules « npm « deps - github.com/nodejs/node.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1adf57de22ee224e02a0f354d26a25649fd1d2d3 (plain)
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
module.exports = regRequest

var url = require("url")
  , fs = require("graceful-fs")
  , rm = require("rimraf")
  , asyncMap = require("slide").asyncMap
  , Stream = require("stream").Stream
  , request = require("request")

function regRequest (method, where, what, etag, nofollow, cb_) {
  if (typeof cb_ !== "function") cb_ = nofollow, nofollow = false
  if (typeof cb_ !== "function") cb_ = etag, etag = null
  if (typeof cb_ !== "function") cb_ = what, what = null

  // Since there are multiple places where an error could occur,
  // don't let the cb be called more than once.
  var errState = null
  function cb (er) {
    if (errState) return
    if (er) errState = er
    cb_.apply(null, arguments)
  }

  if (where.match(/^\/?favicon.ico/)) {
    return cb(new Error("favicon.ico isn't a package, it's a picture."))
  }

  var registry = this.registry

  var adduserChange = /^\/?-\/user\/org\.couchdb\.user:([^\/]+)\/-rev/
    , adduserNew = /^\/?-\/user\/org\.couchdb\.user:([^\/]+)/
    , authRequired = (what || this.alwaysAuth)
                      && !where.match(adduserNew)
                   || where.match(adduserChange)
                   || method === "DELETE"

  // resolve to a full url on the registry
  if (!where.match(/^https?:\/\//)) {
    this.log.verbose("url raw", where)

    var q = where.split("?")
    where = q.shift()
    q = q.join("?")

    if (where.charAt(0) !== "/") where = "/" + where
    where = "." + where.split("/").map(function (p) {
      p = p.trim()
      if (p.match(/^org.couchdb.user/)) {
        return p.replace(/\//g, encodeURIComponent("/"))
      }
      return encodeURIComponent(p)
    }).join("/")
    if (q) where += "?" + q
    this.log.verbose("url resolving", [registry, where])
    where = url.resolve(registry, where)
    this.log.verbose("url resolved", where)
  }

  var remote = url.parse(where)
    , auth = authRequired && this.auth

  if (authRequired && !auth) {
    return cb(new Error(
      "Cannot insert data into the registry without auth"))
  }

  if (auth) {
    remote.auth = new Buffer(auth, "base64").toString("utf8")
  }

  makeRequest.call(this, method, remote, where, what, etag, nofollow, cb)
}

function makeRequest (method, remote, where, what, etag, nofollow, cb) {
  var opts = { url: remote
             , method: method
             , ca: this.ca
             , strictSSL: this.strictSSL }
    , headers = opts.headers = {}
  if (etag) {
    this.log.verbose("etag", etag)
    headers[method === "GET" ? "if-none-match" : "if-match"] = etag
  }

  headers.accept = "application/json"

  headers["user-agent"] = this.userAgent

  opts.proxy = remote.protocol === "https:"
             ? this.httpsProxy : this.proxy

  // figure out wth 'what' is
  if (what) {
    if (Buffer.isBuffer(what) || typeof what === "string") {
      opts.body = what
      headers["content-type"] = "application/json"
      headers["content-length"] = Buffer.byteLength(what)
    } else if (what instanceof Stream) {
      headers["content-type"] = "application/octet-stream"
      if (what.size) headers["content-length"] = what.size
    } else {
      delete what._etag
      opts.json = what
    }
  }

  if (nofollow) {
    opts.followRedirect = false
  }

  this.log.http(method, remote.href || "/")

  var done = requestDone.call(this, method, where, cb)
  var req = request(opts, done)

  req.on("error", cb)

  if (what && (what instanceof Stream)) {
    what.pipe(req)
  }
}

// cb(er, parsed, raw, response)
function requestDone (method, where, cb) {
  return function (er, response, data) {
    if (er) return cb(er)

    this.log.http(response.statusCode, url.parse(where).href)

    var parsed

    if (Buffer.isBuffer(data)) {
      data = data.toString()
    }

    if (data && typeof data === "string" && response.statusCode !== 304) {
      try {
        parsed = JSON.parse(data)
      } catch (ex) {
        ex.message += "\n" + data
        this.log.verbose("bad json", data)
        this.log.error("registry", "error parsing json")
        return cb(ex, null, data, response)
      }
    } else if (data) {
      parsed = data
      data = JSON.stringify(parsed)
    }

    // expect data with any error codes
    if (!data && response.statusCode >= 400) {
      return cb( response.statusCode + " "
               + require("http").STATUS_CODES[response.statusCode]
               , null, data, response )
    }

    var er = null
    if (parsed && response.headers.etag) {
      parsed._etag = response.headers.etag
    }

    if (parsed && parsed.error && response.statusCode >= 400) {
      var w = url.parse(where).pathname.substr(1)
      if (!w.match(/^-/) && parsed.error === "not_found") {
        w = w.split("/")
        name = w[w.indexOf("_rewrite") + 1]
        er = new Error("404 Not Found: "+name)
        er.code = "E404"
        er.pkgid = name
      } else {
        er = new Error(
          parsed.error + " " + (parsed.reason || "") + ": " + w)
      }
    } else if (method !== "HEAD" && method !== "GET") {
      // invalidate cache
      // This is irrelevant for commands that do etag caching, but
      // ls and view also have a timed cache, so this keeps the user
      // from thinking that it didn't work when it did.
      // Note that failure is an acceptable option here, since the
      // only result will be a stale cache for some helper commands.
      var path = require("path")
        , p = url.parse(where).pathname.split("/")
        , _ = "/"
        , caches = p.map(function (part) {
            return _ = path.join(_, part)
          }).map(function (cache) {
            return path.join(this.cache, cache, ".cache.json")
          }, this)

      // if the method is DELETE, then also remove the thing itself.
      // Note that the search index is probably invalid.  Whatever.
      // That's what you get for deleting stuff.  Don't do that.
      if (method === "DELETE") {
        p = p.slice(0, p.indexOf("-rev"))
        caches.push(path.join(this.cache, p.join("/")))
      }

      asyncMap(caches, rm, function () {})
    }
    return cb(er, parsed, data, response)
  }.bind(this)
}