clerk 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/clerk.js DELETED
@@ -1,2690 +0,0 @@
1
- this["clerk"] =
2
- /******/ (function(modules) { // webpackBootstrap
3
- /******/ // The module cache
4
- /******/ var installedModules = {};
5
- /******/
6
- /******/ // The require function
7
- /******/ function __webpack_require__(moduleId) {
8
- /******/
9
- /******/ // Check if module is in cache
10
- /******/ if(installedModules[moduleId])
11
- /******/ return installedModules[moduleId].exports;
12
- /******/
13
- /******/ // Create a new module (and put it into the cache)
14
- /******/ var module = installedModules[moduleId] = {
15
- /******/ exports: {},
16
- /******/ id: moduleId,
17
- /******/ loaded: false
18
- /******/ };
19
- /******/
20
- /******/ // Execute the module function
21
- /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
22
- /******/
23
- /******/ // Flag the module as loaded
24
- /******/ module.loaded = true;
25
- /******/
26
- /******/ // Return the exports of the module
27
- /******/ return module.exports;
28
- /******/ }
29
- /******/
30
- /******/
31
- /******/ // expose the modules object (__webpack_modules__)
32
- /******/ __webpack_require__.m = modules;
33
- /******/
34
- /******/ // expose the module cache
35
- /******/ __webpack_require__.c = installedModules;
36
- /******/
37
- /******/ // __webpack_public_path__
38
- /******/ __webpack_require__.p = "";
39
- /******/
40
- /******/ // Load entry module and return exports
41
- /******/ return __webpack_require__(0);
42
- /******/ })
43
- /************************************************************************/
44
- /******/ ([
45
- /* 0 */
46
- /***/ function(module, exports, __webpack_require__) {
47
-
48
- "use strict";
49
-
50
- /*!
51
-
52
- clerk - CouchDB client for node and the browser.
53
- Copyright 2012-2015 Michael Phan-Ba
54
-
55
- Licensed under the Apache License, Version 2.0 (the "License");
56
- you may not use this file except in compliance with the License.
57
- You may obtain a copy of the License at
58
-
59
- http://www.apache.org/licenses/LICENSE-2.0
60
-
61
- Unless required by applicable law or agreed to in writing, software
62
- distributed under the License is distributed on an "AS IS" BASIS,
63
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
64
- See the License for the specific language governing permissions and
65
- limitations under the License.
66
-
67
- */
68
-
69
- // Module dependencies.
70
- var request = __webpack_require__(1);
71
-
72
- /**
73
- * Copy properties from sources to target.
74
- *
75
- * @param {Object} target The target object.
76
- * @param {...Object} sources The source object.
77
- * @return {Object} The target object.
78
- * @private
79
- */
80
-
81
- var extend = function (target /* ...sources */) {
82
- var source, key, i = 1;
83
- while (source = arguments[i++]) {
84
- for (key in source) target[key] = source[key];
85
- }
86
- return target;
87
- };
88
-
89
- /**
90
- * Stringify value.
91
- *
92
- * @param {Object} that That value to stringify.
93
- * @return {String} The stringifyed value.
94
- * @private
95
- */
96
-
97
- var asString = function (that) {
98
- return Object.prototype.toString.call(that);
99
- };
100
-
101
- /**
102
- * Check if value is a string.
103
- *
104
- * @param {Object} that That value to check.
105
- * @return {Boolean} `true` if string, `false` otherwise.
106
- * @private
107
- */
108
-
109
- var isString = function (that) {
110
- return asString(that) == "[object String]";
111
- };
112
-
113
- /**
114
- * Check if value is an object.
115
- *
116
- * @param {Object} that That value to check.
117
- * @return {Boolean} `true` if object, `false` otherwise.
118
- * @private
119
- */
120
-
121
- var isObject = function (that) {
122
- return asString(that) == "[object Object]";
123
- };
124
-
125
- /**
126
- * Check if value is an array.
127
- *
128
- * @param {Object} that That value to check.
129
- * @return {Boolean} `true` if array, `false` otherwise.
130
- * @private
131
- */
132
-
133
- var isArray = function (that) {
134
- return asString(that) == "[object Array]";
135
- };
136
-
137
- /**
138
- * Check if value is a function.
139
- *
140
- * @param {Object} that That value to check.
141
- * @return {Boolean} `true` if function, `false` otherwise.
142
- * @private
143
- */
144
-
145
- var isFunction = function (that) {
146
- return asString(that) == "[object Function]";
147
- };
148
-
149
- /**
150
- * Clerk library entry point.
151
- *
152
- * @param {String} uri CouchDB server URI.
153
- * @return {Client|DB} If a URI path is given, returns a `DB`, otherwise
154
- * returns a `Client`.
155
- * @see {@link http://docs.couchdb.org|CouchDB Documentation}
156
- * @see {@link http://guide.couchdb.org/|CouchDB Guide}
157
- * @see {@link http://wiki.apache.org/couchdb/|CouchDB Wiki}
158
- */
159
-
160
- function clerk (uri) {
161
- return clerk.make(uri);
162
- };
163
-
164
- /**
165
- * Library version.
166
- * @type {String}
167
- */
168
-
169
- clerk.version = "0.8.2";
170
-
171
- /**
172
- * Default host.
173
- * @type {String}
174
- */
175
-
176
- clerk.defaultHost = "http://127.0.0.1:5984";
177
-
178
- /**
179
- * Create single CouchDB client.
180
- *
181
- * @param {String} uri Fully qualified URI.
182
- * @return {Client|DB} If `uri` has a path, the last segment of the
183
- * path is used as the database name and a `DB` instance is
184
- * returned. Otherwise, a `Client` instance is returned.
185
- */
186
-
187
- clerk.make = function (uri) {
188
- if (!uri) return new Client(this.defaultHost);
189
-
190
- uri = clerk._parseURI(uri);
191
-
192
- var db = /\/*([^\/]+)\/*$/.exec(uri.path);
193
- if (db) {
194
- uri.path = uri.path.substr(0, db.index);
195
- db = db[1] && decodeURIComponent(db[1]);
196
- }
197
-
198
- // weird way of doing it, but it's more efficient...
199
- if (uri.auth) uri.auth = 'Basic ' + clerk.btoa(uri.auth);
200
-
201
- var client = new clerk.Client(uri.base + uri.path, uri.auth);
202
- return db ? client.db(db) : client;
203
- };
204
-
205
- /**
206
- * Base64-encode a string.
207
- *
208
- * @param {String} str
209
- * @return {String}
210
- */
211
-
212
- clerk.btoa = typeof Buffer != "undefined" ? function (str) {
213
- return new Buffer(str).toString("base64");
214
- } : function (str) {
215
- return btoa(str);
216
- };
217
-
218
- /**
219
- * Parse URI.
220
- *
221
- * The URI is normalized by removing extra `//` in the path.
222
- *
223
- * @param {String} uri Fully qualified URI.
224
- * @return {String} The normalized URI.
225
- * @private
226
- */
227
-
228
- clerk._parseURI = function (uri) {
229
- var match;
230
-
231
- if (uri) {
232
- if (match = /^(https?:\/\/)(?:([^\/@]+)@)?([^\/]+)(.*)\/*$/.exec(uri)) {
233
- return {
234
- base: match[1] + match[3].replace(/\/+/g, "\/"),
235
- path: match[4],
236
- auth: match[2] && decodeURIComponent(match[2])
237
- };
238
- }
239
- }
240
-
241
- return { base: uri || "", path: "" };
242
- };
243
-
244
- /**
245
- * Base prototype for `Client` and `DB`.
246
- * Encapsulates HTTP methods, JSON handling, and response coersion.
247
- *
248
- * @constructor
249
- * @memberof clerk
250
- */
251
-
252
- function Base () {};
253
-
254
- /**
255
- * Service request and parse JSON response.
256
- *
257
- * @param {String} [method=GET] HTTP method.
258
- * @param {String} [path=this.uri] HTTP URI.
259
- * @param {Object} [query] HTTP query options.
260
- * @param {Object} [body] HTTP body.
261
- * @param {Object} [headers] HTTP headers.
262
- * @param {handler} [callback] Callback function.
263
- * @return {Promise} A Promise, if no callback is provided,
264
- * otherwise `null`.
265
- */
266
-
267
- Base.prototype.request = function (/* [method], [path], [query], [body], [headers], [callback] */) {
268
- var args = [].slice.call(arguments);
269
- var callback = isFunction (args[args.length - 1]) && args.pop();
270
-
271
- return this._request({
272
- method: args[0],
273
- path: args[1],
274
- query: args[2],
275
- data: args[3],
276
- headers: args[4],
277
- fn: callback
278
- });
279
- };
280
-
281
- /**
282
- * Internal service request and parse JSON response handler.
283
- *
284
- * @param {String} options
285
- * @param {String} method HTTP method.
286
- * @param {String} path HTTP URI.
287
- * @param {Object} query HTTP query options.
288
- * @param {Object} data HTTP body data.
289
- * @param {Object} headers HTTP headers.
290
- * @param {handler} [callback] Callback function.
291
- * @private
292
- */
293
-
294
- Base.prototype._request = function (options) {
295
- var self = this;
296
-
297
- if (options.method == null) options.method = "GET";
298
- if (options.headers == null) options.headers = {};
299
- if (options.auth == null) options.auth = this.auth;
300
-
301
- options.path = options.path ? "/" + options.path : "";
302
-
303
- // set default headers
304
- if (options.headers["Content-Type"] == null) {
305
- options.headers["Content-Type"] = "application/json";
306
- }
307
- if (options.headers["Accept"] == null) {
308
- options.headers["Accept"] = "application/json";
309
- }
310
- if (this.auth && options.headers["Authorization"] == null) {
311
- options.headers["Authorization"] = this.auth;
312
- }
313
-
314
- options.uri = this.uri + options.path;
315
- options.body = options.data && JSON.stringify(options.data,
316
- /^\/_design/.test(options.path) && this._replacer
317
- ) || "";
318
-
319
- // create promise if no callback given
320
- var promise, req;
321
- if (!options.fn && typeof Promise != "undefined") {
322
- promise = new Promise(function (resolve, reject) {
323
- options.fn = function (err, data, status, headers, res) {
324
- if (err) {
325
- err.body = data;
326
- err.status = status;
327
- err.headers = headers;
328
- err.res = res;
329
- reject(err);
330
- } else {
331
- if (Object.defineProperties) {
332
- Object.defineProperties(data, {
333
- _status: { value: status },
334
- _headers: { value: headers },
335
- _response: { value: res },
336
- });
337
- }
338
- resolve(data);
339
- };
340
- };
341
- });
342
- req = send();
343
- promise.request = req;
344
- promise.abort = function () {
345
- req.abort();
346
- options.fn(new Error("abort"));
347
- return promise;
348
- };
349
- return promise;
350
- }
351
-
352
- send();
353
-
354
- function send () {
355
- // apply response transforms
356
- var g = options._;
357
- var fn = options.fn;
358
- if (fn) {
359
- options.fn = g ? function () {
360
- fn.apply(self, g.apply(self, arguments) || arguments);
361
- } : fn;
362
- }
363
- return self._do(options);
364
- }
365
- };
366
-
367
- /**
368
- * Provider for servicing requests and parsing JSON responses.
369
- *
370
- * @param {String} options
371
- * @param {String} method HTTP method.
372
- * @param {String} uri HTTP URI.
373
- * @param {Object} query HTTP query options.
374
- * @param {Object} body HTTP body.
375
- * @param {Object} headers HTTP headers.
376
- * @param {Object} auth HTTP authentication.
377
- * @param {handler} [callback] Callback function.
378
- * @private
379
- */
380
-
381
- Base.prototype._do = function (options) {
382
- var self = this;
383
- var key, value;
384
- var fn = options.fn;
385
-
386
- // create request
387
- var req = request(options.method, options.uri);
388
-
389
- // query string
390
- if (options.query) {
391
- // ensure query Array values are JSON encoded
392
- for (key in options.query) {
393
- if (typeof(value = options.query[key]) === "object") {
394
- options.query[key] = JSON.stringify(value);
395
- }
396
- }
397
- // set query on request
398
- req.query(options.query);
399
- }
400
-
401
- // set headers
402
- if (options.headers) {
403
- req.set(options.headers);
404
- // if authenticating
405
- if (req.withCredentials && options.headers["Authorization"] != null) {
406
- req.withCredentials();
407
- }
408
- }
409
-
410
- // send body
411
- if (options.body) req.send(options.body);
412
-
413
- // send request
414
- req.end(function (err, res) {
415
- var data;
416
-
417
- if (!err) {
418
- if (!(data = res.body)) { data = res.text; }
419
- else if (data.error) err = self._error(data);
420
- else data = self._response(data);
421
- }
422
-
423
- if (err && fn) {
424
- var response = res || {};
425
- return fn(err, data, response.status, response.header, res);
426
- }
427
-
428
- res.data = data;
429
- if (fn) fn(err || null, data, res.status, res.header, res);
430
- });
431
-
432
- return req;
433
- };
434
-
435
- /**
436
- * Coerce response to normalize access to `_id` and `_rev`.
437
- *
438
- * @param {Object} json The response JSON.
439
- * @return The coerced JSON.
440
- * @private
441
- */
442
-
443
- Base.prototype._response = function (json) {
444
- var data = json.rows || json.results || json.uuids || isArray(json) && json;
445
- var meta = this._meta;
446
- var i = 0, len, item;
447
-
448
- if (data) {
449
- extend(data, json).json = json;
450
- for (len = data.length; i < len; i++) {
451
- item = data[i] = meta(data[i]);
452
- if (item.doc) item.doc = meta(item.doc);
453
- }
454
- } else {
455
- data = meta(json);
456
- }
457
-
458
- return data;
459
- };
460
-
461
- /**
462
- * Make an error out of the response.
463
- *
464
- * @param {Object} json The response JSON.
465
- * @return An `Error` object.
466
- * @private
467
- */
468
-
469
- Base.prototype._error = function (json) {
470
- var err = new Error(json.reason);
471
- err.code = json.error;
472
- return extend(err, json);
473
- };
474
-
475
- /**
476
- * JSON stringify functions. Used for encoding view documents to JSON.
477
- *
478
- * @param {String} key The key to stringify.
479
- * @param {Object} val The value to stringify.
480
- * @return {Object} The stringified function value or the value.
481
- * @private
482
- */
483
-
484
- Base.prototype._replacer = function (key, val) {
485
- return isFunction (val) ? val.toString() : val;
486
- };
487
-
488
- /**
489
- * Coerce documents with prototypical `_id` and `_rev`
490
- * values.
491
- *
492
- * @param {Object} doc The document to coerce.
493
- * @return {Object} The coerced document.
494
- * @private
495
- */
496
-
497
- Base.prototype._meta = function (doc) {
498
- var hasId = !doc._id && doc.id;
499
- var hasRev = !doc._rev && doc.rev;
500
- var proto;
501
-
502
- if (hasId || hasRev) {
503
- proto = function (){};
504
- doc = extend(new proto(), doc);
505
- proto = proto.prototype;
506
- if (hasId) proto._id = doc.id;
507
- if (hasRev) proto._rev = doc.rev;
508
- }
509
-
510
- return doc;
511
- };
512
-
513
- /**
514
- * Parse arguments.
515
- *
516
- * @param {Array} args The arguments.
517
- * @param {Integer} [start] The index from which to start reading arguments.
518
- * @param {Boolean} [withBody] Set to `true` if the request body is given as a
519
- * parameter before HTTP query options.
520
- * @param {Boolean} [notDoc] The request body is not a document.
521
- * @return {Promise} A Promise, if no callback is provided, otherwise `null`.
522
- * @private
523
- */
524
-
525
- Base.prototype._ = function (args, start, withBody, notDoc) {
526
- var self = this, doc, id, rev;
527
-
528
- function request(method, path, options) {
529
- if (!options) options = {};
530
- return self._request({
531
- method: method,
532
- path: path || request.p,
533
- query: options.q || request.q,
534
- data: options.b || request.b,
535
- headers: options.h || request.h,
536
- fn: options.f || request.f,
537
- _: options._ || request._
538
- });
539
- }
540
-
541
- // [id], [doc], [query], [header], [callback]
542
- args = [].slice.call(args, start || 0);
543
-
544
- request.f = isFunction(args[args.length - 1]) && args.pop();
545
- request.p = isString(args[0]) && encodeURI(args.shift());
546
- request.q = args[withBody ? 1 : 0] || {};
547
- request.h = args[withBody ? 2 : 1] || {};
548
-
549
- if (withBody) {
550
- doc = request.b = args[0];
551
- if (!notDoc) {
552
- if (id = request.p || doc._id || doc.id) request.p = id;
553
- if (rev = request.q.rev || doc._rev || doc.rev) request.q.rev = rev;
554
- }
555
- }
556
-
557
- return request;
558
- };
559
-
560
- /**
561
- * Clerk CouchDB client.
562
- *
563
- * @param {String} uri Fully qualified URI.
564
- * @param {String} [auth] Authentication header value.
565
- * @constructor
566
- * @memberof clerk
567
- * @see {@link http://wiki.apache.org/couchdb/Complete_HTTP_API_Reference|CouchDB Wiki}
568
- */
569
-
570
- function Client (uri, auth) {
571
- this.uri = uri;
572
- this._db = {};
573
- this.auth = auth;
574
- };
575
-
576
- Client.prototype = new Base();
577
-
578
- /**
579
- * Select database to manipulate.
580
- *
581
- * @param {String} name DB name.
582
- * @return {DB} DB object.
583
- */
584
-
585
- Client.prototype.db = function (name) {
586
- var db = this._db;
587
- return db[name] || (db[name] = new DB(this, name, this.auth));
588
- };
589
-
590
- /**
591
- * List all databases.
592
- *
593
- * @param {Object} [query] HTTP query options.
594
- * @param {Object} [headers] HTTP headers.
595
- * @param {handler} [callback] Callback function.
596
- * @return {Promise} A Promise, if no callback is provided,
597
- * otherwise `null`.
598
- * @see {@link http://wiki.apache.org/couchdb/HttpGetAllDbs|CouchDB Wiki}
599
- */
600
-
601
- Client.prototype.dbs = function (/* [query], [headers], [callback] */) {
602
- return this._(arguments)("GET", "_all_dbs");
603
- };
604
-
605
- /**
606
- * Get UUIDs.
607
- *
608
- * @param {Integer} [count=1] Number of UUIDs to get.
609
- * @param {Object} [query] HTTP query options.
610
- * @param {Object} [headers] HTTP headers.
611
- * @param {handler} [callback] Callback function.
612
- * @return {Promise} A Promise, if no callback is provided,
613
- * otherwise `null`.
614
- * @see {@link http://wiki.apache.org/couchdb/HttpGetUuids|CouchDB Wiki}
615
- */
616
-
617
- Client.prototype.uuids = function (count /* [query], [headers], [callback] */) {
618
- var request = this._(arguments, +count == count ? 1 : 0);
619
- if (count > 1) request.q.count = count;
620
- return request("GET", "_uuids");
621
- };
622
-
623
- /**
624
- * Get server information.
625
- *
626
- * @param {Object} [query] HTTP query options.
627
- * @param {Object} [headers] HTTP headers.
628
- * @param {handler} [callback] Callback function.
629
- * @return {Promise} A Promise, if no callback is provided,
630
- * otherwise `null`.
631
- * @see {@link http://wiki.apache.org/couchdb/HttpGetRoot|CouchDB Wiki}
632
- */
633
-
634
- Client.prototype.info = function (/* [query], [headers], [callback] */) {
635
- return this._(arguments)("GET");
636
- };
637
-
638
- /**
639
- * Get server stats.
640
- *
641
- * @param {Object} [query] HTTP query options.
642
- * @param {Object} [headers] HTTP headers.
643
- * @param {handler} [callback] Callback function.
644
- * @return {Promise} A Promise, if no callback is provided,
645
- * otherwise `null`.
646
- * @see {@link http://wiki.apache.org/couchdb/HttpGetLog|CouchDB Wiki}
647
- */
648
-
649
- Client.prototype.stats = function (/* [query], [headers], [callback] */) {
650
- return this._(arguments)("GET", "_stats");
651
- };
652
-
653
- /**
654
- * Get tail of the server log file.
655
- *
656
- * @param {Object} [query] Query parameters.
657
- * @param {Integer} [query.bytes] Number of bytes to read.
658
- * @param {Integer} [query.offset] Number of bytes from the end of
659
- * log file to start reading.
660
- * @param {Object} [headers] HTTP headers.
661
- * @param {handler} [callback] Callback function.
662
- * @return {Promise} A Promise, if no callback is provided,
663
- * otherwise `null`.
664
- * @see {@link http://wiki.apache.org/couchdb/HttpGetLog|CouchDB Wiki}
665
- */
666
-
667
- Client.prototype.log = function (/* [query], [headers], [callback] */) {
668
- return this._(arguments)("GET", "_log");
669
- };
670
-
671
- /**
672
- * List running tasks.
673
- *
674
- * @param {Object} [query] HTTP query options.
675
- * @param {Object} [headers] HTTP headers.
676
- * @param {handler} [callback] Callback function.
677
- * @return {Promise} A Promise, if no callback is provided,
678
- * otherwise `null`.
679
- * @see {@link http://wiki.apache.org/couchdb/HttpGetActiveTasks|CouchDB Wiki}
680
- */
681
-
682
- Client.prototype.tasks = function (/* [query], [headers], [callback] */) {
683
- return this._(arguments)("GET", "_active_tasks");
684
- };
685
-
686
- /**
687
- * Get or set configuration values.
688
- *
689
- * @param {String} [key] Configuration section or key.
690
- * @param {String} [value] Configuration value.
691
- * @param {Object} [query] HTTP query options.
692
- * @param {Object} [headers] HTTP headers.
693
- * @param {handler} [callback] Callback function.
694
- * @return {Promise} A Promise, if no callback is provided,
695
- * otherwise `null`.
696
- */
697
-
698
- Client.prototype.config = function (/* [key], [value], [query], [headers], [callback] */) {
699
- var args = [].slice.call(arguments);
700
- var key = isString(args[0]) && args.shift() || "";
701
- var value = isString(args[0]) && args.shift();
702
- var method = isString(value) ? "PUT" : "GET";
703
- return this._(args)(method, "_config/" + key, { b: value });
704
- };
705
-
706
- /**
707
- * Replicate databases.
708
- *
709
- * @param {Object} options Options.
710
- * @param {String} options.source Source database URL or local name.
711
- * @param {String} options.target Target database URL or local name.
712
- * @param {Boolean} [options.cancel] Set to `true` to cancel replication.
713
- * @param {Boolean} [options.continuous] Set to `true` for continuous
714
- * replication.
715
- * @param {Boolean} [options.create_target] Set to `true` to create the
716
- * target database.
717
- * @param {String} [options.filter] Filter name for filtered replication.
718
- * Example: "mydesign/myfilter".
719
- * @param {Object} [options.query] Query parameters for filter.
720
- * @param {String[]} [options.doc_ids] Document IDs to replicate.
721
- * @param {String} [options.proxy] Proxy through which to replicate.
722
- * @param {Object} [query] HTTP query options.
723
- * @param {Object} [headers] HTTP headers.
724
- * @param {handler} [callback] Callback function.
725
- * @return {Promise} A Promise, if no callback is provided,
726
- * otherwise `null`.
727
- * @see {@link http://wiki.apache.org/couchdb/Replication|CouchDB Wiki}
728
- */
729
-
730
- Client.prototype.replicate = function (options /* [query], [headers], [callback] */) {
731
- return this._(arguments, 1)("POST", "_replicate", { b: options });
732
- };
733
-
734
- /**
735
- * Methods for CouchDB database.
736
- *
737
- * @param {Client} client Clerk client.
738
- * @param {String} name DB name.
739
- * @param {String} [auth] Authentication header value.
740
- * @constructor
741
- * @memberof clerk
742
- * @return This object for chaining.
743
- */
744
-
745
- function DB (client, name, auth) {
746
- this.client = client;
747
- this.name = name;
748
- this.uri = client.uri + "/" + encodeURIComponent(name);
749
- this.auth = auth;
750
- };
751
-
752
- DB.prototype = new Base();
753
-
754
- /**
755
- * Create database.
756
- *
757
- * @param {Object} [query] HTTP query options.
758
- * @param {Object} [headers] HTTP headers.
759
- * @param {handler} [callback] Callback function.
760
- * @return {Promise} A Promise, if no callback is provided,
761
- * otherwise `null`.
762
- */
763
-
764
- DB.prototype.create = function (/* [query], [headers], [callback] */) {
765
- return this._(arguments)("PUT");
766
- };
767
-
768
- /**
769
- * Destroy database.
770
- *
771
- * @param {Object} [query] HTTP query options.
772
- * @param {Object} [headers] HTTP headers.
773
- * @param {handler} [callback] Callback function.
774
- * @return {Promise} A Promise, if no callback is provided,
775
- * otherwise `null`.
776
- */
777
-
778
- DB.prototype.destroy = function (/* [query], [headers], [callback] */) {
779
- return this._(arguments)("DELETE");
780
- };
781
-
782
- /**
783
- * Get database info.
784
- *
785
- * @param {Object} [query] HTTP query options.
786
- * @param {Object} [headers] HTTP headers.
787
- * @param {handler} [callback] Callback function.
788
- * @return {Promise} A Promise, if no callback is provided,
789
- * otherwise `null`.
790
- */
791
-
792
- DB.prototype.info = function (/* [query], [headers], callback */) {
793
- return this._(arguments)("GET");
794
- };
795
-
796
- /**
797
- * Check if database exists.
798
- *
799
- * @param {Object} [query] HTTP query options.
800
- * @param {Object} [headers] HTTP headers.
801
- * @param {handler} [callback] Callback function.
802
- * @return {Promise} A Promise, if no callback is provided,
803
- * otherwise `null`.
804
- */
805
-
806
- DB.prototype.exists = function (/* [query], [headers], callback */) {
807
- var request = this._(arguments);
808
- request._ = function (err, body, status, headers, req) {
809
- return [err, status === 200, status, headers, req];
810
- };
811
- return request("HEAD");
812
- };
813
-
814
- /**
815
- * Fetch document.
816
- *
817
- * Set `rev` in `query`.
818
- *
819
- * @param {String} id Document ID.
820
- * @param {Object} [query] HTTP query options.
821
- * @param {Boolean} [query.revs] Fetch list of revisions.
822
- * @param {Boolean} [query.revs_info] Fetch detailed revision information.
823
- * @param {Object} [headers] HTTP headers.
824
- * @param {handler} [callback] Callback function.
825
- * @return {Promise} A Promise, if no callback is provided,
826
- * otherwise `null`.
827
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#GET|CouchDB Wiki}
828
- */
829
-
830
- DB.prototype.get = function (/* [id], [query], [headers], [callback] */) {
831
- return this._(arguments)("GET");
832
- };
833
-
834
- /**
835
- * Get document metadata.
836
- *
837
- * @param {String} id Document ID.
838
- * @param {Object} [query] HTTP query options.
839
- * @param {Object} [headers] HTTP headers.
840
- * @param {handler} [callback] Callback function.
841
- * @return {Promise} A Promise, if no callback is provided,
842
- * otherwise `null`.
843
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#HEAD|CouchDB Wiki}
844
- */
845
-
846
- DB.prototype.head = function (/* [id], [query], [headers], callback */) {
847
- var self = this;
848
- var request = self._(arguments);
849
- request._ = function (err, body, status, headers, res) {
850
- return [err, err ? null : {
851
- _id: request.p,
852
- _rev: headers.etag && JSON.parse(headers.etag),
853
- contentType: headers["content-type"],
854
- contentLength: headers["content-length"]
855
- }, status, headers, res];
856
- };
857
- return request("HEAD");
858
- };
859
-
860
- /**
861
- * Post document(s) to database.
862
- *
863
- * If documents have no ID, a document ID will be automatically generated
864
- * on the server. Attachments are not currently supported.
865
- *
866
- * @param {Object|Object[]} doc Document or array of documents.
867
- * @param {String} [doc._id] Document ID. If set, uses given document ID.
868
- * @param {String} [doc._rev] Document revision. If set, allows update to
869
- * existing document.
870
- * @param {Object} [doc._attachments] Attachments. If given, must be a
871
- * map of filenames to attachment properties.
872
- * @param {String} [doc._attachments[filename]] Attachment filename, as
873
- * hash key.
874
- * @param {String} [doc._attachments[filename].contentType] Attachment
875
- * MIME content type.
876
- * @param {String|Object} [doc._attachments[filename].data] Attachment
877
- * data. Will be Base64 encoded.
878
- * @param {Object} [query] HTTP query options.
879
- * @param {Boolean} [query.batch] Allow server to write document in
880
- * batch mode. Documents will not be written to disk immediately,
881
- * increasing the chances of write failure.
882
- * @param {Boolean} [query.all_or_nothing] For batch updating of
883
- * documents, use all-or-nothing semantics.
884
- * @param {Object} [headers] HTTP headers.
885
- * @param {handler} [callback] Callback function.
886
- * @return {Promise} A Promise, if no callback is provided,
887
- * otherwise `null`.
888
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#POST|CouchDB Wiki}
889
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
890
- */
891
-
892
- DB.prototype.post = function (docs /* [query], [headers], [callback] */) {
893
- var request = this._(arguments, 1);
894
- if (isArray(docs)) {
895
- request.p = "_bulk_docs";
896
- request.b = extend({ docs: docs }, request.q);
897
- request.q = null
898
- } else {
899
- request.b = docs;
900
- }
901
- return request("POST");
902
- };
903
-
904
- /**
905
- * Put document in database.
906
- *
907
- * @param {Object} doc Document data. Requires `_id` and `_rev`.
908
- * @param {String} [options] Options.
909
- * @param {Object} [query] HTTP query options.
910
- * @param {Object} [headers] HTTP headers.
911
- * @param {handler} [callback] Callback function.
912
- * @return {Promise} A Promise, if no callback is provided,
913
- * otherwise `null`.
914
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#PUT|CouchDB Wiki}
915
- */
916
-
917
- DB.prototype.put = function (/* [id], [doc], [query], [headers], [callback] */) {
918
- var request = this._(arguments, 0, 1);
919
- // prevent acidentally creating database
920
- if (!request.p) request.p = request.b._id || request.b.id;
921
- if (!request.p) throw new Error("missing id");
922
- return request("PUT");
923
- };
924
-
925
- /**
926
- * Delete document(s).
927
- *
928
- * @param {Object|Object[]} docs Document or array of documents.
929
- * @param {Object} [query] HTTP query options.
930
- * @param {Object} [headers] HTTP headers.
931
- * @param {handler} [callback] Callback function.
932
- * @return {Promise} A Promise, if no callback is provided,
933
- * otherwise `null`.
934
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#DELETE|CouchDB Wiki}
935
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
936
- */
937
-
938
- DB.prototype.del = function (docs /* [query], [headers], [callback] */) {
939
- if (isArray(docs)) {
940
- var i = 0, len = docs.length, doc;
941
- for (; i < len; i++) {
942
- doc = docs[i], docs[i] = {
943
- _id: doc._id || doc.id,
944
- _rev: doc._rev || doc.rev,
945
- _deleted: true
946
- };
947
- }
948
- return this.post.apply(this, arguments);
949
- } else {
950
- var request = this._(arguments, 0, 1);
951
- // prevent acidentally deleting database
952
- if (!request.p) throw new Error("missing id");
953
- return request("DELETE");
954
- }
955
- };
956
-
957
- /**
958
- * Copy document.
959
- *
960
- * @param {Object} source Source document.
961
- * @param {String} source.id Source document ID.
962
- * @param {String} [source.rev] Source document revision.
963
- * @param {String} [source._id] Source document ID. Alternate key for
964
- * `source.id`.
965
- * @param {String} [source._rev] Source document revision. Alternate key
966
- * for `source.id`.
967
- * @param {Object} target Target document.
968
- * @param {String} target.id Target document ID.
969
- * @param {String} [target.rev] Target document revision.
970
- * @param {String} [target._id] Target document ID. Alternate key for
971
- * `target.id`.
972
- * @param {String} [target._rev] Target document revision. Alternate key
973
- * for `target.id`.
974
- * @param {Object} [query] HTTP query options.
975
- * @param {Object} [headers] HTTP headers.
976
- * @param {handler} [callback] Callback function.
977
- * @return {Promise} A Promise, if no callback is provided,
978
- * otherwise `null`.
979
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#COPY|CouchDB Wiki}
980
- */
981
-
982
- DB.prototype.copy = function (source, target /* [query], [headers], [callback] */) {
983
- var request = this._(arguments, 2);
984
- var sourcePath = encodeURIComponent(source.id || source._id || source);
985
- var targetPath = encodeURIComponent(target.id || target._id || target);
986
- var sourceRev = source.rev || source._rev;
987
- var targetRev = target.rev || target._rev;
988
-
989
- if (sourceRev) request.q.rev = sourceRev;
990
- if (targetRev) targetPath += "?rev=" + encodeURIComponent(targetRev);
991
-
992
- request.h.Destination = targetPath;
993
-
994
- return request("COPY", sourcePath);
995
- };
996
-
997
- /**
998
- * Query all documents by ID.
999
- *
1000
- * @param {Object} [query] HTTP query options.
1001
- * @param {JSON} [query.startkey] Start returning results from this
1002
- * document ID.
1003
- * @param {JSON} [query.endkey] Stop returning results at this document
1004
- * ID.
1005
- * @param {Integer} [query.limit] Limit number of results returned.
1006
- * @param {Boolean} [query.descending=false] Lookup results in reverse
1007
- * order by key, returning documents in descending order by key.
1008
- * @param {Integer} [query.skip] Skip this many records before
1009
- * returning results.
1010
- * @param {Boolean} [query.include_docs=false] Include document source for
1011
- * each result.
1012
- * @param {Boolean} [query.include_end=true] Include `query.endkey`
1013
- * in results.
1014
- * @param {Boolean} [query.update_seq=false] Include sequence value
1015
- * of the database corresponding to the view.
1016
- * @param {Object} [headers] HTTP headers.
1017
- * @param {handler} [callback] Callback function.
1018
- * @return {Promise} A Promise, if no callback is provided,
1019
- * otherwise `null`.
1020
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
1021
- */
1022
-
1023
- DB.prototype.all = function (/* [query], [headers], [callback] */) {
1024
- var request = this._(arguments);
1025
- var body = this._viewOptions(request.q);
1026
- return request(body ? "POST" : "GET", "_all_docs", { b: body });
1027
- };
1028
-
1029
- /**
1030
- * Query a view.
1031
- *
1032
- * @param {String|Object} view View name (e.g. mydesign/myview) or
1033
- * temporary view definition. Using a temporary view is strongly not
1034
- * recommended for production use.
1035
- * @param {Object} [query] HTTP query options.
1036
- * @param {JSON} [query.key] Key to lookup.
1037
- * @param {JSON} [query.startkey] Start returning results from this key.
1038
- * @param {String} [query.startkey_docid] Start returning results
1039
- * from this document ID. Allows pagination with duplicate keys.
1040
- * @param {JSON} [query.endkey] Stop returning results at this key.
1041
- * @param {String} [query.endkey_docid] Stop returning results at
1042
- * this document ID. Allows pagination with duplicate keys.
1043
- * @param {Integer} [query.limit] Limit number of results returned.
1044
- * @param {Boolean|String} [query.stale] Do not refresh view even if
1045
- * stale. For CouchDB versions `1.1.0` and up, set to `update_after` to
1046
- * update view after results are returned.
1047
- * @param {Boolean} [query.descending=false] Lookup results in reverse
1048
- * order by key, returning documents in descending order by key.
1049
- * @param {Integer} [query.skip] Skip this many records before
1050
- * returning results.
1051
- * @param {Boolean|Integer} [query.group=false] Use the reduce function
1052
- * to group results by key. Set to an integer specify `group_level`.
1053
- * @param {Boolean|Integer} [query.reduce=true] Use the reduce function.
1054
- * @param {Boolean} [query.fetch=false] Include document source for
1055
- * each result.
1056
- * @param {Boolean} [query.include_end=true] Include `query.endkey`
1057
- * in results.
1058
- * @param {Boolean} [query.update_seq=false] Include sequence value
1059
- * of the database corresponding to the view.
1060
- * @param {Object} [headers] HTTP headers.
1061
- * @param {handler} [callback] Callback function.
1062
- * @return {Promise} A Promise, if no callback is provided,
1063
- * otherwise `null`.
1064
- * @see {@link http://wiki.apache.org/couchdb/HTTP_view_API|CouchDB Wiki}
1065
- */
1066
-
1067
- DB.prototype.find = function (view /* [query], [headers], [callback] */) {
1068
- var request = this._(arguments, 1), path, body;
1069
-
1070
- if (isString(view)) {
1071
- path = view.split("/", 2);
1072
- path = "_design/" + encodeURIComponent(path[0]) +
1073
- "/_view/" + encodeURIComponent(path[1]);
1074
- } else {
1075
- path = "_temp_view";
1076
- body = view;
1077
- }
1078
-
1079
- body = this._viewOptions(request.q, body);
1080
- return request(body ? "POST" : "GET", path, { b: body });
1081
- };
1082
-
1083
- /**
1084
- * Get database changes.
1085
- *
1086
- * The `feed` option determines how the callback is called:
1087
- *
1088
- * - `normal` calls the callback once.
1089
- * - `longpoll` waits for a response, then calls the callback once.
1090
- * - `continuous` calls the callback each time an update is received.
1091
- * Implemented as the `database#follow()` method.
1092
- *
1093
- * @param {Object} [query] HTTP query options.
1094
- * @param {String} [query.feed="normal"] Type of feed. See comments
1095
- * above.
1096
- * @param {String} [query.filter] Filter updates using this filter.
1097
- * @param {Integer} [query.limit] Maximum number of rows to return.
1098
- * @param {Integer} [query.since=0] Start results from this sequence
1099
- * number.
1100
- * @param {Boolean} [query.include_docs=false] Include documents with
1101
- * results.
1102
- * @param {Integer} [query.timeout=1000] Maximum period in milliseconds
1103
- * to wait for a change before sending a response, even if there are no
1104
- * results.
1105
- * @param {Integer} [query.heartbeat=1000] Period in milliseconds after
1106
- * which an empty line is sent. Applicable only to feed types
1107
- * `longpoll` and `continuous`. Overrides `query.timeout` to keep the
1108
- * feed alive indefinitely.
1109
- * @param {Object} [headers] HTTP headers.
1110
- * @param {handler} [callback] Callback function.
1111
- * @return {Promise} A Promise, if no callback is provided,
1112
- * otherwise `null`.
1113
- * @see {@link http://wiki.apache.org/couchdb/HTTP_database_API#Changes|CouchDB Wiki}
1114
- */
1115
-
1116
- DB.prototype.changes = function (/* [query], [headers], [callback] */) {
1117
- var request = this._(arguments);
1118
- if (request.q.feed != "longpoll") delete request.q.feed;
1119
- return this._changes(request);
1120
- };
1121
-
1122
- /**
1123
- * Follow database changes.
1124
- *
1125
- * @see `#changes()`.
1126
- */
1127
-
1128
- DB.prototype.follow = function (/* [query], [headers], callback */) {
1129
- var self = this;
1130
- var request = this._(arguments);
1131
- var fn = request.f;
1132
-
1133
- if (!fn) return this;
1134
-
1135
- request.q.feed = "longpoll";
1136
- request.f = function (err, body) {
1137
- var args = [].slice.call(arguments);
1138
- var done, i;
1139
- for (i = 0; i < body.length; i++) {
1140
- args[1] = body[i];
1141
- if (done = fn.apply(self, args) === false || err) break;
1142
- }
1143
- if (!done) self._changes(request);
1144
- };
1145
-
1146
- return this._changes(request);
1147
- };
1148
-
1149
- /**
1150
- * Service a changes request.
1151
- *
1152
- * @private
1153
- */
1154
-
1155
- DB.prototype._changes = function (request) {
1156
- return request("GET", "_changes");
1157
- };
1158
-
1159
- /**
1160
- * Update document using server-side handler.
1161
- *
1162
- * @param {String} handler Update handler. Example: mydesign/myhandler
1163
- * @param {String} [id] Document ID.
1164
- * @param {any} data Data.
1165
- * @param {Object} [query] HTTP query options.
1166
- * @param {Object} [headers] Headers.
1167
- * @param {handler} [callback] Callback function.
1168
- * @return {Promise} A Promise, if no callback is provided,
1169
- * otherwise `null`.
1170
- * @see {@link http://wiki.apache.org/couchdb/Document_Update_Handlers|CouchDB Wiki}
1171
- */
1172
-
1173
- DB.prototype.update = function (handler /* [id], [data], [query], [headers], [callback] */) {
1174
- var request = this._(arguments, 1, 1, 1);
1175
- var path = handler.split("/", 2);
1176
-
1177
- path = "_design/" + encodeURIComponent(path[0]) +
1178
- "/_update/" + encodeURIComponent(path[1]);
1179
-
1180
- if (request.p) path += "/" + request.p;
1181
-
1182
- return request("POST", path);
1183
- };
1184
-
1185
- /**
1186
- * Download attachment from document.
1187
- *
1188
- * @param {Object|String} docOrId Document or document ID.
1189
- * @param {String} attachmentName Attachment name.
1190
- * @param {Object} [query] HTTP query options.
1191
- * @param {Object} [headers] HTTP headers.
1192
- * @param {handler} [callback] Callback function.
1193
- * @return {Promise} A Promise, if no callback is provided,
1194
- * otherwise `null`.
1195
- */
1196
-
1197
- DB.prototype.attachment = function (doc, attachmentName /* [query], [headers], [callback] */) {
1198
- var request = this._(arguments, 2);
1199
- var path = encodeURIComponent(doc._id || doc.id || doc) + "/" +
1200
- encodeURIComponent(attachmentName);
1201
- return request("GET", path, options);
1202
- };
1203
-
1204
- /**
1205
- * Upload attachment to document.
1206
- *
1207
- * Set the `Content-Type` header.
1208
- *
1209
- * @param {Object} [doc] Document. Requires `id`. `rev` can be specified
1210
- * here or in `query`.
1211
- * @param {String} attachmentName Attachment name.
1212
- * @param {Object} data Data.
1213
- * @param {Object} [query] HTTP query options.
1214
- * @param {Object} [headers] HTTP headers.
1215
- * @param {handler} [callback] Callback function.
1216
- * @return {Promise} A Promise, if no callback is provided,
1217
- * otherwise `null`.
1218
- */
1219
-
1220
- DB.prototype.attach = function (doc, attachmentName, data /* [query], [headers], [callback] */) {
1221
- var request = this._(arguments, 3);
1222
- request.p = encodeURIComponent(doc._id || doc.id) + "/" +
1223
- encodeURIComponent(attachmentName);
1224
- if (!request.q.rev) request.q.rev = doc._rev || doc.rev;
1225
- request.q.body = data;
1226
- return request("PUT", path);
1227
- };
1228
-
1229
- /**
1230
- * Replicate database.
1231
- *
1232
- * This convenience function sets `options.source` and `options.target` to
1233
- * the selected database name. Either `options.source` or `options.target`
1234
- * must be overridden for a successful replication request.
1235
- *
1236
- * @param {Options} options Options. Accepts all options from
1237
- * `Client.replicate()`.
1238
- * @param {String} [options.source=this.name] Source database URL or
1239
- * local name. Defaults to the selected database name if not given.
1240
- * @param {String} [options.target=this.name] Target database URL or
1241
- * local name. Defaults to the selected database name if not given.
1242
- * @param {Object} [query] HTTP query options.
1243
- * @param {Object} [headers] HTTP headers.
1244
- * @param {handler} [callback] Callback function.
1245
- * @return {Promise} A Promise, if no callback is provided,
1246
- * otherwise `null`.
1247
- */
1248
-
1249
- DB.prototype.replicate = function (options /* [query], [headers], [callback] */) {
1250
- if (!options.source) options.source = this.name;
1251
- if (!options.target) options.target = this.name;
1252
- return this.client.replicate.apply(this.client, arguments);
1253
- };
1254
-
1255
- /**
1256
- * Ensure recent changes are committed to disk.
1257
- *
1258
- * @param {Object} [query] HTTP query options.
1259
- * @param {Object} [headers] HTTP headers.
1260
- * @param {handler} [callback] Callback function.
1261
- * @return {Promise} A Promise, if no callback is provided,
1262
- * otherwise `null`.
1263
- */
1264
-
1265
- DB.prototype.commit = function (/* [query], [headers], [callback] */) {
1266
- return this._(arguments)("POST", "_ensure_full_commit");
1267
- };
1268
-
1269
- /**
1270
- * Purge deleted documents from database.
1271
- *
1272
- * @param {Object} revs Map of document IDs to revisions to be purged.
1273
- * @param {Object} [query] HTTP query options.
1274
- * @param {Object} [headers] HTTP headers.
1275
- * @param {handler} [callback] Callback function.
1276
- * @return {Promise} A Promise, if no callback is provided,
1277
- * otherwise `null`.
1278
- */
1279
-
1280
- DB.prototype.purge = function (revs /* [query], [headers], [callback] */) {
1281
- return this._(arguments, 1)("POST", "_purge", { b: revs });
1282
- };
1283
-
1284
- /**
1285
- * Compact database or design.
1286
- *
1287
- * @param {String} [design] Design name if compacting design indexes.
1288
- * @param {Object} [query] HTTP query options.
1289
- * @param {Object} [headers] HTTP headers.
1290
- * @param {handler} [callback] Callback function.
1291
- * @return {Promise} A Promise, if no callback is provided,
1292
- * otherwise `null`.
1293
- * @see {@link http://wiki.apache.org/couchdb/Compaction|CouchDB Wiki}
1294
- */
1295
-
1296
- DB.prototype.compact = function (/* [design], [query], [headers], [callback] */) {
1297
- var request = this._(arguments);
1298
- return request("POST", "_compact/" + (request.p || ""));
1299
- };
1300
-
1301
- /**
1302
- * Remove unused views.
1303
- *
1304
- * @param {Object} [query] HTTP query options.
1305
- * @param {Object} [headers] HTTP headers.
1306
- * @param {handler} [callback] Callback function.
1307
- * @return {Promise} A Promise, if no callback is provided,
1308
- * otherwise `null`.
1309
- * @see {@link http://wiki.apache.org/couchdb/Compaction|CouchDB Wiki}
1310
- */
1311
-
1312
- DB.prototype.vacuum = function (/* [query], [headers], [callback] */) {
1313
- return this._(arguments)("POST", "_view_cleanup");
1314
- };
1315
-
1316
- /**
1317
- * Parse view options.
1318
- *
1319
- * @param {Object} query The HTTP query options.
1320
- * @param {Object} body The body payload.
1321
- * @param {handler} [callback] Callback function.
1322
- * @return {Object} The body payload.
1323
- * @private
1324
- */
1325
-
1326
- DB.prototype._viewOptions = function (q, body) {
1327
- if (q) {
1328
- if (q.key) q.key = JSON.stringify(q.key);
1329
- if (q.startkey) q.startkey = JSON.stringify(q.startkey);
1330
- if (q.endkey) q.endkey = JSON.stringify(q.endkey);
1331
- if (q.stale && q.stale != "update_after") q.stale = "ok";
1332
- if (q.keys) {
1333
- if (!body) body = {};
1334
- body.keys = q.keys;
1335
- delete q.keys;
1336
- }
1337
- }
1338
- return body;
1339
- };
1340
-
1341
- /**
1342
- * Handle a clerk response.
1343
- *
1344
- * @callback handler
1345
- * @param {Error|null} error Error or `null` on success.
1346
- * @param {Object} data Response data.
1347
- * @param {Integer} status Response status code.
1348
- * @param {Object} headers Response headers.
1349
- * @param {superagent.Response} res Superagent response object.
1350
- */
1351
-
1352
- clerk.Base = Base;
1353
- clerk.Client = Client;
1354
- clerk.DB = DB;
1355
-
1356
- // Export clerk.
1357
- module.exports = clerk;
1358
-
1359
-
1360
- /***/ },
1361
- /* 1 */
1362
- /***/ function(module, exports, __webpack_require__) {
1363
-
1364
- /**
1365
- * Module dependencies.
1366
- */
1367
-
1368
- var Emitter = __webpack_require__(2);
1369
- var reduce = __webpack_require__(3);
1370
-
1371
- /**
1372
- * Root reference for iframes.
1373
- */
1374
-
1375
- var root = 'undefined' == typeof window
1376
- ? (this || self)
1377
- : window;
1378
-
1379
- /**
1380
- * Noop.
1381
- */
1382
-
1383
- function noop(){};
1384
-
1385
- /**
1386
- * Check if `obj` is a host object,
1387
- * we don't want to serialize these :)
1388
- *
1389
- * TODO: future proof, move to compoent land
1390
- *
1391
- * @param {Object} obj
1392
- * @return {Boolean}
1393
- * @api private
1394
- */
1395
-
1396
- function isHost(obj) {
1397
- var str = {}.toString.call(obj);
1398
-
1399
- switch (str) {
1400
- case '[object File]':
1401
- case '[object Blob]':
1402
- case '[object FormData]':
1403
- return true;
1404
- default:
1405
- return false;
1406
- }
1407
- }
1408
-
1409
- /**
1410
- * Determine XHR.
1411
- */
1412
-
1413
- request.getXHR = function () {
1414
- if (root.XMLHttpRequest
1415
- && (!root.location || 'file:' != root.location.protocol
1416
- || !root.ActiveXObject)) {
1417
- return new XMLHttpRequest;
1418
- } else {
1419
- try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
1420
- try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
1421
- try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
1422
- try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
1423
- }
1424
- return false;
1425
- };
1426
-
1427
- /**
1428
- * Removes leading and trailing whitespace, added to support IE.
1429
- *
1430
- * @param {String} s
1431
- * @return {String}
1432
- * @api private
1433
- */
1434
-
1435
- var trim = ''.trim
1436
- ? function(s) { return s.trim(); }
1437
- : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
1438
-
1439
- /**
1440
- * Check if `obj` is an object.
1441
- *
1442
- * @param {Object} obj
1443
- * @return {Boolean}
1444
- * @api private
1445
- */
1446
-
1447
- function isObject(obj) {
1448
- return obj === Object(obj);
1449
- }
1450
-
1451
- /**
1452
- * Serialize the given `obj`.
1453
- *
1454
- * @param {Object} obj
1455
- * @return {String}
1456
- * @api private
1457
- */
1458
-
1459
- function serialize(obj) {
1460
- if (!isObject(obj)) return obj;
1461
- var pairs = [];
1462
- for (var key in obj) {
1463
- if (null != obj[key]) {
1464
- pairs.push(encodeURIComponent(key)
1465
- + '=' + encodeURIComponent(obj[key]));
1466
- }
1467
- }
1468
- return pairs.join('&');
1469
- }
1470
-
1471
- /**
1472
- * Expose serialization method.
1473
- */
1474
-
1475
- request.serializeObject = serialize;
1476
-
1477
- /**
1478
- * Parse the given x-www-form-urlencoded `str`.
1479
- *
1480
- * @param {String} str
1481
- * @return {Object}
1482
- * @api private
1483
- */
1484
-
1485
- function parseString(str) {
1486
- var obj = {};
1487
- var pairs = str.split('&');
1488
- var parts;
1489
- var pair;
1490
-
1491
- for (var i = 0, len = pairs.length; i < len; ++i) {
1492
- pair = pairs[i];
1493
- parts = pair.split('=');
1494
- obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
1495
- }
1496
-
1497
- return obj;
1498
- }
1499
-
1500
- /**
1501
- * Expose parser.
1502
- */
1503
-
1504
- request.parseString = parseString;
1505
-
1506
- /**
1507
- * Default MIME type map.
1508
- *
1509
- * superagent.types.xml = 'application/xml';
1510
- *
1511
- */
1512
-
1513
- request.types = {
1514
- html: 'text/html',
1515
- json: 'application/json',
1516
- xml: 'application/xml',
1517
- urlencoded: 'application/x-www-form-urlencoded',
1518
- 'form': 'application/x-www-form-urlencoded',
1519
- 'form-data': 'application/x-www-form-urlencoded'
1520
- };
1521
-
1522
- /**
1523
- * Default serialization map.
1524
- *
1525
- * superagent.serialize['application/xml'] = function(obj){
1526
- * return 'generated xml here';
1527
- * };
1528
- *
1529
- */
1530
-
1531
- request.serialize = {
1532
- 'application/x-www-form-urlencoded': serialize,
1533
- 'application/json': JSON.stringify
1534
- };
1535
-
1536
- /**
1537
- * Default parsers.
1538
- *
1539
- * superagent.parse['application/xml'] = function(str){
1540
- * return { object parsed from str };
1541
- * };
1542
- *
1543
- */
1544
-
1545
- request.parse = {
1546
- 'application/x-www-form-urlencoded': parseString,
1547
- 'application/json': JSON.parse
1548
- };
1549
-
1550
- /**
1551
- * Parse the given header `str` into
1552
- * an object containing the mapped fields.
1553
- *
1554
- * @param {String} str
1555
- * @return {Object}
1556
- * @api private
1557
- */
1558
-
1559
- function parseHeader(str) {
1560
- var lines = str.split(/\r?\n/);
1561
- var fields = {};
1562
- var index;
1563
- var line;
1564
- var field;
1565
- var val;
1566
-
1567
- lines.pop(); // trailing CRLF
1568
-
1569
- for (var i = 0, len = lines.length; i < len; ++i) {
1570
- line = lines[i];
1571
- index = line.indexOf(':');
1572
- field = line.slice(0, index).toLowerCase();
1573
- val = trim(line.slice(index + 1));
1574
- fields[field] = val;
1575
- }
1576
-
1577
- return fields;
1578
- }
1579
-
1580
- /**
1581
- * Return the mime type for the given `str`.
1582
- *
1583
- * @param {String} str
1584
- * @return {String}
1585
- * @api private
1586
- */
1587
-
1588
- function type(str){
1589
- return str.split(/ *; */).shift();
1590
- };
1591
-
1592
- /**
1593
- * Return header field parameters.
1594
- *
1595
- * @param {String} str
1596
- * @return {Object}
1597
- * @api private
1598
- */
1599
-
1600
- function params(str){
1601
- return reduce(str.split(/ *; */), function(obj, str){
1602
- var parts = str.split(/ *= */)
1603
- , key = parts.shift()
1604
- , val = parts.shift();
1605
-
1606
- if (key && val) obj[key] = val;
1607
- return obj;
1608
- }, {});
1609
- };
1610
-
1611
- /**
1612
- * Initialize a new `Response` with the given `xhr`.
1613
- *
1614
- * - set flags (.ok, .error, etc)
1615
- * - parse header
1616
- *
1617
- * Examples:
1618
- *
1619
- * Aliasing `superagent` as `request` is nice:
1620
- *
1621
- * request = superagent;
1622
- *
1623
- * We can use the promise-like API, or pass callbacks:
1624
- *
1625
- * request.get('/').end(function(res){});
1626
- * request.get('/', function(res){});
1627
- *
1628
- * Sending data can be chained:
1629
- *
1630
- * request
1631
- * .post('/user')
1632
- * .send({ name: 'tj' })
1633
- * .end(function(res){});
1634
- *
1635
- * Or passed to `.send()`:
1636
- *
1637
- * request
1638
- * .post('/user')
1639
- * .send({ name: 'tj' }, function(res){});
1640
- *
1641
- * Or passed to `.post()`:
1642
- *
1643
- * request
1644
- * .post('/user', { name: 'tj' })
1645
- * .end(function(res){});
1646
- *
1647
- * Or further reduced to a single call for simple cases:
1648
- *
1649
- * request
1650
- * .post('/user', { name: 'tj' }, function(res){});
1651
- *
1652
- * @param {XMLHTTPRequest} xhr
1653
- * @param {Object} options
1654
- * @api private
1655
- */
1656
-
1657
- function Response(req, options) {
1658
- options = options || {};
1659
- this.req = req;
1660
- this.xhr = this.req.xhr;
1661
- // responseText is accessible only if responseType is '' or 'text' and on older browsers
1662
- this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')
1663
- ? this.xhr.responseText
1664
- : null;
1665
- this.statusText = this.req.xhr.statusText;
1666
- this.setStatusProperties(this.xhr.status);
1667
- this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
1668
- // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
1669
- // getResponseHeader still works. so we get content-type even if getting
1670
- // other headers fails.
1671
- this.header['content-type'] = this.xhr.getResponseHeader('content-type');
1672
- this.setHeaderProperties(this.header);
1673
- this.body = this.req.method != 'HEAD'
1674
- ? this.parseBody(this.text ? this.text : this.xhr.response)
1675
- : null;
1676
- }
1677
-
1678
- /**
1679
- * Get case-insensitive `field` value.
1680
- *
1681
- * @param {String} field
1682
- * @return {String}
1683
- * @api public
1684
- */
1685
-
1686
- Response.prototype.get = function(field){
1687
- return this.header[field.toLowerCase()];
1688
- };
1689
-
1690
- /**
1691
- * Set header related properties:
1692
- *
1693
- * - `.type` the content type without params
1694
- *
1695
- * A response of "Content-Type: text/plain; charset=utf-8"
1696
- * will provide you with a `.type` of "text/plain".
1697
- *
1698
- * @param {Object} header
1699
- * @api private
1700
- */
1701
-
1702
- Response.prototype.setHeaderProperties = function(header){
1703
- // content-type
1704
- var ct = this.header['content-type'] || '';
1705
- this.type = type(ct);
1706
-
1707
- // params
1708
- var obj = params(ct);
1709
- for (var key in obj) this[key] = obj[key];
1710
- };
1711
-
1712
- /**
1713
- * Parse the given body `str`.
1714
- *
1715
- * Used for auto-parsing of bodies. Parsers
1716
- * are defined on the `superagent.parse` object.
1717
- *
1718
- * @param {String} str
1719
- * @return {Mixed}
1720
- * @api private
1721
- */
1722
-
1723
- Response.prototype.parseBody = function(str){
1724
- var parse = request.parse[this.type];
1725
- return parse && str && (str.length || str instanceof Object)
1726
- ? parse(str)
1727
- : null;
1728
- };
1729
-
1730
- /**
1731
- * Set flags such as `.ok` based on `status`.
1732
- *
1733
- * For example a 2xx response will give you a `.ok` of __true__
1734
- * whereas 5xx will be __false__ and `.error` will be __true__. The
1735
- * `.clientError` and `.serverError` are also available to be more
1736
- * specific, and `.statusType` is the class of error ranging from 1..5
1737
- * sometimes useful for mapping respond colors etc.
1738
- *
1739
- * "sugar" properties are also defined for common cases. Currently providing:
1740
- *
1741
- * - .noContent
1742
- * - .badRequest
1743
- * - .unauthorized
1744
- * - .notAcceptable
1745
- * - .notFound
1746
- *
1747
- * @param {Number} status
1748
- * @api private
1749
- */
1750
-
1751
- Response.prototype.setStatusProperties = function(status){
1752
- // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
1753
- if (status === 1223) {
1754
- status = 204;
1755
- }
1756
-
1757
- var type = status / 100 | 0;
1758
-
1759
- // status / class
1760
- this.status = status;
1761
- this.statusType = type;
1762
-
1763
- // basics
1764
- this.info = 1 == type;
1765
- this.ok = 2 == type;
1766
- this.clientError = 4 == type;
1767
- this.serverError = 5 == type;
1768
- this.error = (4 == type || 5 == type)
1769
- ? this.toError()
1770
- : false;
1771
-
1772
- // sugar
1773
- this.accepted = 202 == status;
1774
- this.noContent = 204 == status;
1775
- this.badRequest = 400 == status;
1776
- this.unauthorized = 401 == status;
1777
- this.notAcceptable = 406 == status;
1778
- this.notFound = 404 == status;
1779
- this.forbidden = 403 == status;
1780
- };
1781
-
1782
- /**
1783
- * Return an `Error` representative of this response.
1784
- *
1785
- * @return {Error}
1786
- * @api public
1787
- */
1788
-
1789
- Response.prototype.toError = function(){
1790
- var req = this.req;
1791
- var method = req.method;
1792
- var url = req.url;
1793
-
1794
- var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
1795
- var err = new Error(msg);
1796
- err.status = this.status;
1797
- err.method = method;
1798
- err.url = url;
1799
-
1800
- return err;
1801
- };
1802
-
1803
- /**
1804
- * Expose `Response`.
1805
- */
1806
-
1807
- request.Response = Response;
1808
-
1809
- /**
1810
- * Initialize a new `Request` with the given `method` and `url`.
1811
- *
1812
- * @param {String} method
1813
- * @param {String} url
1814
- * @api public
1815
- */
1816
-
1817
- function Request(method, url) {
1818
- var self = this;
1819
- Emitter.call(this);
1820
- this._query = this._query || [];
1821
- this.method = method;
1822
- this.url = url;
1823
- this.header = {};
1824
- this._header = {};
1825
- this.on('end', function(){
1826
- var err = null;
1827
- var res = null;
1828
-
1829
- try {
1830
- res = new Response(self);
1831
- } catch(e) {
1832
- err = new Error('Parser is unable to parse the response');
1833
- err.parse = true;
1834
- err.original = e;
1835
- return self.callback(err);
1836
- }
1837
-
1838
- self.emit('response', res);
1839
-
1840
- if (err) {
1841
- return self.callback(err, res);
1842
- }
1843
-
1844
- if (res.status >= 200 && res.status < 300) {
1845
- return self.callback(err, res);
1846
- }
1847
-
1848
- var new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
1849
- new_err.original = err;
1850
- new_err.response = res;
1851
- new_err.status = res.status;
1852
-
1853
- self.callback(err || new_err, res);
1854
- });
1855
- }
1856
-
1857
- /**
1858
- * Mixin `Emitter`.
1859
- */
1860
-
1861
- Emitter(Request.prototype);
1862
-
1863
- /**
1864
- * Allow for extension
1865
- */
1866
-
1867
- Request.prototype.use = function(fn) {
1868
- fn(this);
1869
- return this;
1870
- }
1871
-
1872
- /**
1873
- * Set timeout to `ms`.
1874
- *
1875
- * @param {Number} ms
1876
- * @return {Request} for chaining
1877
- * @api public
1878
- */
1879
-
1880
- Request.prototype.timeout = function(ms){
1881
- this._timeout = ms;
1882
- return this;
1883
- };
1884
-
1885
- /**
1886
- * Clear previous timeout.
1887
- *
1888
- * @return {Request} for chaining
1889
- * @api public
1890
- */
1891
-
1892
- Request.prototype.clearTimeout = function(){
1893
- this._timeout = 0;
1894
- clearTimeout(this._timer);
1895
- return this;
1896
- };
1897
-
1898
- /**
1899
- * Abort the request, and clear potential timeout.
1900
- *
1901
- * @return {Request}
1902
- * @api public
1903
- */
1904
-
1905
- Request.prototype.abort = function(){
1906
- if (this.aborted) return;
1907
- this.aborted = true;
1908
- this.xhr.abort();
1909
- this.clearTimeout();
1910
- this.emit('abort');
1911
- return this;
1912
- };
1913
-
1914
- /**
1915
- * Set header `field` to `val`, or multiple fields with one object.
1916
- *
1917
- * Examples:
1918
- *
1919
- * req.get('/')
1920
- * .set('Accept', 'application/json')
1921
- * .set('X-API-Key', 'foobar')
1922
- * .end(callback);
1923
- *
1924
- * req.get('/')
1925
- * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
1926
- * .end(callback);
1927
- *
1928
- * @param {String|Object} field
1929
- * @param {String} val
1930
- * @return {Request} for chaining
1931
- * @api public
1932
- */
1933
-
1934
- Request.prototype.set = function(field, val){
1935
- if (isObject(field)) {
1936
- for (var key in field) {
1937
- this.set(key, field[key]);
1938
- }
1939
- return this;
1940
- }
1941
- this._header[field.toLowerCase()] = val;
1942
- this.header[field] = val;
1943
- return this;
1944
- };
1945
-
1946
- /**
1947
- * Remove header `field`.
1948
- *
1949
- * Example:
1950
- *
1951
- * req.get('/')
1952
- * .unset('User-Agent')
1953
- * .end(callback);
1954
- *
1955
- * @param {String} field
1956
- * @return {Request} for chaining
1957
- * @api public
1958
- */
1959
-
1960
- Request.prototype.unset = function(field){
1961
- delete this._header[field.toLowerCase()];
1962
- delete this.header[field];
1963
- return this;
1964
- };
1965
-
1966
- /**
1967
- * Get case-insensitive header `field` value.
1968
- *
1969
- * @param {String} field
1970
- * @return {String}
1971
- * @api private
1972
- */
1973
-
1974
- Request.prototype.getHeader = function(field){
1975
- return this._header[field.toLowerCase()];
1976
- };
1977
-
1978
- /**
1979
- * Set Content-Type to `type`, mapping values from `request.types`.
1980
- *
1981
- * Examples:
1982
- *
1983
- * superagent.types.xml = 'application/xml';
1984
- *
1985
- * request.post('/')
1986
- * .type('xml')
1987
- * .send(xmlstring)
1988
- * .end(callback);
1989
- *
1990
- * request.post('/')
1991
- * .type('application/xml')
1992
- * .send(xmlstring)
1993
- * .end(callback);
1994
- *
1995
- * @param {String} type
1996
- * @return {Request} for chaining
1997
- * @api public
1998
- */
1999
-
2000
- Request.prototype.type = function(type){
2001
- this.set('Content-Type', request.types[type] || type);
2002
- return this;
2003
- };
2004
-
2005
- /**
2006
- * Set Accept to `type`, mapping values from `request.types`.
2007
- *
2008
- * Examples:
2009
- *
2010
- * superagent.types.json = 'application/json';
2011
- *
2012
- * request.get('/agent')
2013
- * .accept('json')
2014
- * .end(callback);
2015
- *
2016
- * request.get('/agent')
2017
- * .accept('application/json')
2018
- * .end(callback);
2019
- *
2020
- * @param {String} accept
2021
- * @return {Request} for chaining
2022
- * @api public
2023
- */
2024
-
2025
- Request.prototype.accept = function(type){
2026
- this.set('Accept', request.types[type] || type);
2027
- return this;
2028
- };
2029
-
2030
- /**
2031
- * Set Authorization field value with `user` and `pass`.
2032
- *
2033
- * @param {String} user
2034
- * @param {String} pass
2035
- * @return {Request} for chaining
2036
- * @api public
2037
- */
2038
-
2039
- Request.prototype.auth = function(user, pass){
2040
- var str = btoa(user + ':' + pass);
2041
- this.set('Authorization', 'Basic ' + str);
2042
- return this;
2043
- };
2044
-
2045
- /**
2046
- * Add query-string `val`.
2047
- *
2048
- * Examples:
2049
- *
2050
- * request.get('/shoes')
2051
- * .query('size=10')
2052
- * .query({ color: 'blue' })
2053
- *
2054
- * @param {Object|String} val
2055
- * @return {Request} for chaining
2056
- * @api public
2057
- */
2058
-
2059
- Request.prototype.query = function(val){
2060
- if ('string' != typeof val) val = serialize(val);
2061
- if (val) this._query.push(val);
2062
- return this;
2063
- };
2064
-
2065
- /**
2066
- * Write the field `name` and `val` for "multipart/form-data"
2067
- * request bodies.
2068
- *
2069
- * ``` js
2070
- * request.post('/upload')
2071
- * .field('foo', 'bar')
2072
- * .end(callback);
2073
- * ```
2074
- *
2075
- * @param {String} name
2076
- * @param {String|Blob|File} val
2077
- * @return {Request} for chaining
2078
- * @api public
2079
- */
2080
-
2081
- Request.prototype.field = function(name, val){
2082
- if (!this._formData) this._formData = new root.FormData();
2083
- this._formData.append(name, val);
2084
- return this;
2085
- };
2086
-
2087
- /**
2088
- * Queue the given `file` as an attachment to the specified `field`,
2089
- * with optional `filename`.
2090
- *
2091
- * ``` js
2092
- * request.post('/upload')
2093
- * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
2094
- * .end(callback);
2095
- * ```
2096
- *
2097
- * @param {String} field
2098
- * @param {Blob|File} file
2099
- * @param {String} filename
2100
- * @return {Request} for chaining
2101
- * @api public
2102
- */
2103
-
2104
- Request.prototype.attach = function(field, file, filename){
2105
- if (!this._formData) this._formData = new root.FormData();
2106
- this._formData.append(field, file, filename);
2107
- return this;
2108
- };
2109
-
2110
- /**
2111
- * Send `data`, defaulting the `.type()` to "json" when
2112
- * an object is given.
2113
- *
2114
- * Examples:
2115
- *
2116
- * // querystring
2117
- * request.get('/search')
2118
- * .end(callback)
2119
- *
2120
- * // multiple data "writes"
2121
- * request.get('/search')
2122
- * .send({ search: 'query' })
2123
- * .send({ range: '1..5' })
2124
- * .send({ order: 'desc' })
2125
- * .end(callback)
2126
- *
2127
- * // manual json
2128
- * request.post('/user')
2129
- * .type('json')
2130
- * .send('{"name":"tj"})
2131
- * .end(callback)
2132
- *
2133
- * // auto json
2134
- * request.post('/user')
2135
- * .send({ name: 'tj' })
2136
- * .end(callback)
2137
- *
2138
- * // manual x-www-form-urlencoded
2139
- * request.post('/user')
2140
- * .type('form')
2141
- * .send('name=tj')
2142
- * .end(callback)
2143
- *
2144
- * // auto x-www-form-urlencoded
2145
- * request.post('/user')
2146
- * .type('form')
2147
- * .send({ name: 'tj' })
2148
- * .end(callback)
2149
- *
2150
- * // defaults to x-www-form-urlencoded
2151
- * request.post('/user')
2152
- * .send('name=tobi')
2153
- * .send('species=ferret')
2154
- * .end(callback)
2155
- *
2156
- * @param {String|Object} data
2157
- * @return {Request} for chaining
2158
- * @api public
2159
- */
2160
-
2161
- Request.prototype.send = function(data){
2162
- var obj = isObject(data);
2163
- var type = this.getHeader('Content-Type');
2164
-
2165
- // merge
2166
- if (obj && isObject(this._data)) {
2167
- for (var key in data) {
2168
- this._data[key] = data[key];
2169
- }
2170
- } else if ('string' == typeof data) {
2171
- if (!type) this.type('form');
2172
- type = this.getHeader('Content-Type');
2173
- if ('application/x-www-form-urlencoded' == type) {
2174
- this._data = this._data
2175
- ? this._data + '&' + data
2176
- : data;
2177
- } else {
2178
- this._data = (this._data || '') + data;
2179
- }
2180
- } else {
2181
- this._data = data;
2182
- }
2183
-
2184
- if (!obj || isHost(data)) return this;
2185
- if (!type) this.type('json');
2186
- return this;
2187
- };
2188
-
2189
- /**
2190
- * Invoke the callback with `err` and `res`
2191
- * and handle arity check.
2192
- *
2193
- * @param {Error} err
2194
- * @param {Response} res
2195
- * @api private
2196
- */
2197
-
2198
- Request.prototype.callback = function(err, res){
2199
- var fn = this._callback;
2200
- this.clearTimeout();
2201
- fn(err, res);
2202
- };
2203
-
2204
- /**
2205
- * Invoke callback with x-domain error.
2206
- *
2207
- * @api private
2208
- */
2209
-
2210
- Request.prototype.crossDomainError = function(){
2211
- var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');
2212
- err.crossDomain = true;
2213
- this.callback(err);
2214
- };
2215
-
2216
- /**
2217
- * Invoke callback with timeout error.
2218
- *
2219
- * @api private
2220
- */
2221
-
2222
- Request.prototype.timeoutError = function(){
2223
- var timeout = this._timeout;
2224
- var err = new Error('timeout of ' + timeout + 'ms exceeded');
2225
- err.timeout = timeout;
2226
- this.callback(err);
2227
- };
2228
-
2229
- /**
2230
- * Enable transmission of cookies with x-domain requests.
2231
- *
2232
- * Note that for this to work the origin must not be
2233
- * using "Access-Control-Allow-Origin" with a wildcard,
2234
- * and also must set "Access-Control-Allow-Credentials"
2235
- * to "true".
2236
- *
2237
- * @api public
2238
- */
2239
-
2240
- Request.prototype.withCredentials = function(){
2241
- this._withCredentials = true;
2242
- return this;
2243
- };
2244
-
2245
- /**
2246
- * Initiate request, invoking callback `fn(res)`
2247
- * with an instanceof `Response`.
2248
- *
2249
- * @param {Function} fn
2250
- * @return {Request} for chaining
2251
- * @api public
2252
- */
2253
-
2254
- Request.prototype.end = function(fn){
2255
- var self = this;
2256
- var xhr = this.xhr = request.getXHR();
2257
- var query = this._query.join('&');
2258
- var timeout = this._timeout;
2259
- var data = this._formData || this._data;
2260
-
2261
- // store callback
2262
- this._callback = fn || noop;
2263
-
2264
- // state change
2265
- xhr.onreadystatechange = function(){
2266
- if (4 != xhr.readyState) return;
2267
-
2268
- // In IE9, reads to any property (e.g. status) off of an aborted XHR will
2269
- // result in the error "Could not complete the operation due to error c00c023f"
2270
- var status;
2271
- try { status = xhr.status } catch(e) { status = 0; }
2272
-
2273
- if (0 == status) {
2274
- if (self.timedout) return self.timeoutError();
2275
- if (self.aborted) return;
2276
- return self.crossDomainError();
2277
- }
2278
- self.emit('end');
2279
- };
2280
-
2281
- // progress
2282
- var handleProgress = function(e){
2283
- if (e.total > 0) {
2284
- e.percent = e.loaded / e.total * 100;
2285
- }
2286
- self.emit('progress', e);
2287
- };
2288
- if (this.hasListeners('progress')) {
2289
- xhr.onprogress = handleProgress;
2290
- }
2291
- try {
2292
- if (xhr.upload && this.hasListeners('progress')) {
2293
- xhr.upload.onprogress = handleProgress;
2294
- }
2295
- } catch(e) {
2296
- // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
2297
- // Reported here:
2298
- // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
2299
- }
2300
-
2301
- // timeout
2302
- if (timeout && !this._timer) {
2303
- this._timer = setTimeout(function(){
2304
- self.timedout = true;
2305
- self.abort();
2306
- }, timeout);
2307
- }
2308
-
2309
- // querystring
2310
- if (query) {
2311
- query = request.serializeObject(query);
2312
- this.url += ~this.url.indexOf('?')
2313
- ? '&' + query
2314
- : '?' + query;
2315
- }
2316
-
2317
- // initiate request
2318
- xhr.open(this.method, this.url, true);
2319
-
2320
- // CORS
2321
- if (this._withCredentials) xhr.withCredentials = true;
2322
-
2323
- // body
2324
- if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
2325
- // serialize stuff
2326
- var serialize = request.serialize[this.getHeader('Content-Type')];
2327
- if (serialize) data = serialize(data);
2328
- }
2329
-
2330
- // set header fields
2331
- for (var field in this.header) {
2332
- if (null == this.header[field]) continue;
2333
- xhr.setRequestHeader(field, this.header[field]);
2334
- }
2335
-
2336
- // send stuff
2337
- this.emit('request', this);
2338
- xhr.send(data);
2339
- return this;
2340
- };
2341
-
2342
- /**
2343
- * Expose `Request`.
2344
- */
2345
-
2346
- request.Request = Request;
2347
-
2348
- /**
2349
- * Issue a request:
2350
- *
2351
- * Examples:
2352
- *
2353
- * request('GET', '/users').end(callback)
2354
- * request('/users').end(callback)
2355
- * request('/users', callback)
2356
- *
2357
- * @param {String} method
2358
- * @param {String|Function} url or callback
2359
- * @return {Request}
2360
- * @api public
2361
- */
2362
-
2363
- function request(method, url) {
2364
- // callback
2365
- if ('function' == typeof url) {
2366
- return new Request('GET', method).end(url);
2367
- }
2368
-
2369
- // url first
2370
- if (1 == arguments.length) {
2371
- return new Request('GET', method);
2372
- }
2373
-
2374
- return new Request(method, url);
2375
- }
2376
-
2377
- /**
2378
- * GET `url` with optional callback `fn(res)`.
2379
- *
2380
- * @param {String} url
2381
- * @param {Mixed|Function} data or fn
2382
- * @param {Function} fn
2383
- * @return {Request}
2384
- * @api public
2385
- */
2386
-
2387
- request.get = function(url, data, fn){
2388
- var req = request('GET', url);
2389
- if ('function' == typeof data) fn = data, data = null;
2390
- if (data) req.query(data);
2391
- if (fn) req.end(fn);
2392
- return req;
2393
- };
2394
-
2395
- /**
2396
- * HEAD `url` with optional callback `fn(res)`.
2397
- *
2398
- * @param {String} url
2399
- * @param {Mixed|Function} data or fn
2400
- * @param {Function} fn
2401
- * @return {Request}
2402
- * @api public
2403
- */
2404
-
2405
- request.head = function(url, data, fn){
2406
- var req = request('HEAD', url);
2407
- if ('function' == typeof data) fn = data, data = null;
2408
- if (data) req.send(data);
2409
- if (fn) req.end(fn);
2410
- return req;
2411
- };
2412
-
2413
- /**
2414
- * DELETE `url` with optional callback `fn(res)`.
2415
- *
2416
- * @param {String} url
2417
- * @param {Function} fn
2418
- * @return {Request}
2419
- * @api public
2420
- */
2421
-
2422
- request.del = function(url, fn){
2423
- var req = request('DELETE', url);
2424
- if (fn) req.end(fn);
2425
- return req;
2426
- };
2427
-
2428
- /**
2429
- * PATCH `url` with optional `data` and callback `fn(res)`.
2430
- *
2431
- * @param {String} url
2432
- * @param {Mixed} data
2433
- * @param {Function} fn
2434
- * @return {Request}
2435
- * @api public
2436
- */
2437
-
2438
- request.patch = function(url, data, fn){
2439
- var req = request('PATCH', url);
2440
- if ('function' == typeof data) fn = data, data = null;
2441
- if (data) req.send(data);
2442
- if (fn) req.end(fn);
2443
- return req;
2444
- };
2445
-
2446
- /**
2447
- * POST `url` with optional `data` and callback `fn(res)`.
2448
- *
2449
- * @param {String} url
2450
- * @param {Mixed} data
2451
- * @param {Function} fn
2452
- * @return {Request}
2453
- * @api public
2454
- */
2455
-
2456
- request.post = function(url, data, fn){
2457
- var req = request('POST', url);
2458
- if ('function' == typeof data) fn = data, data = null;
2459
- if (data) req.send(data);
2460
- if (fn) req.end(fn);
2461
- return req;
2462
- };
2463
-
2464
- /**
2465
- * PUT `url` with optional `data` and callback `fn(res)`.
2466
- *
2467
- * @param {String} url
2468
- * @param {Mixed|Function} data or fn
2469
- * @param {Function} fn
2470
- * @return {Request}
2471
- * @api public
2472
- */
2473
-
2474
- request.put = function(url, data, fn){
2475
- var req = request('PUT', url);
2476
- if ('function' == typeof data) fn = data, data = null;
2477
- if (data) req.send(data);
2478
- if (fn) req.end(fn);
2479
- return req;
2480
- };
2481
-
2482
- /**
2483
- * Expose `request`.
2484
- */
2485
-
2486
- module.exports = request;
2487
-
2488
-
2489
- /***/ },
2490
- /* 2 */
2491
- /***/ function(module, exports, __webpack_require__) {
2492
-
2493
-
2494
- /**
2495
- * Expose `Emitter`.
2496
- */
2497
-
2498
- module.exports = Emitter;
2499
-
2500
- /**
2501
- * Initialize a new `Emitter`.
2502
- *
2503
- * @api public
2504
- */
2505
-
2506
- function Emitter(obj) {
2507
- if (obj) return mixin(obj);
2508
- };
2509
-
2510
- /**
2511
- * Mixin the emitter properties.
2512
- *
2513
- * @param {Object} obj
2514
- * @return {Object}
2515
- * @api private
2516
- */
2517
-
2518
- function mixin(obj) {
2519
- for (var key in Emitter.prototype) {
2520
- obj[key] = Emitter.prototype[key];
2521
- }
2522
- return obj;
2523
- }
2524
-
2525
- /**
2526
- * Listen on the given `event` with `fn`.
2527
- *
2528
- * @param {String} event
2529
- * @param {Function} fn
2530
- * @return {Emitter}
2531
- * @api public
2532
- */
2533
-
2534
- Emitter.prototype.on =
2535
- Emitter.prototype.addEventListener = function(event, fn){
2536
- this._callbacks = this._callbacks || {};
2537
- (this._callbacks[event] = this._callbacks[event] || [])
2538
- .push(fn);
2539
- return this;
2540
- };
2541
-
2542
- /**
2543
- * Adds an `event` listener that will be invoked a single
2544
- * time then automatically removed.
2545
- *
2546
- * @param {String} event
2547
- * @param {Function} fn
2548
- * @return {Emitter}
2549
- * @api public
2550
- */
2551
-
2552
- Emitter.prototype.once = function(event, fn){
2553
- var self = this;
2554
- this._callbacks = this._callbacks || {};
2555
-
2556
- function on() {
2557
- self.off(event, on);
2558
- fn.apply(this, arguments);
2559
- }
2560
-
2561
- on.fn = fn;
2562
- this.on(event, on);
2563
- return this;
2564
- };
2565
-
2566
- /**
2567
- * Remove the given callback for `event` or all
2568
- * registered callbacks.
2569
- *
2570
- * @param {String} event
2571
- * @param {Function} fn
2572
- * @return {Emitter}
2573
- * @api public
2574
- */
2575
-
2576
- Emitter.prototype.off =
2577
- Emitter.prototype.removeListener =
2578
- Emitter.prototype.removeAllListeners =
2579
- Emitter.prototype.removeEventListener = function(event, fn){
2580
- this._callbacks = this._callbacks || {};
2581
-
2582
- // all
2583
- if (0 == arguments.length) {
2584
- this._callbacks = {};
2585
- return this;
2586
- }
2587
-
2588
- // specific event
2589
- var callbacks = this._callbacks[event];
2590
- if (!callbacks) return this;
2591
-
2592
- // remove all handlers
2593
- if (1 == arguments.length) {
2594
- delete this._callbacks[event];
2595
- return this;
2596
- }
2597
-
2598
- // remove specific handler
2599
- var cb;
2600
- for (var i = 0; i < callbacks.length; i++) {
2601
- cb = callbacks[i];
2602
- if (cb === fn || cb.fn === fn) {
2603
- callbacks.splice(i, 1);
2604
- break;
2605
- }
2606
- }
2607
- return this;
2608
- };
2609
-
2610
- /**
2611
- * Emit `event` with the given args.
2612
- *
2613
- * @param {String} event
2614
- * @param {Mixed} ...
2615
- * @return {Emitter}
2616
- */
2617
-
2618
- Emitter.prototype.emit = function(event){
2619
- this._callbacks = this._callbacks || {};
2620
- var args = [].slice.call(arguments, 1)
2621
- , callbacks = this._callbacks[event];
2622
-
2623
- if (callbacks) {
2624
- callbacks = callbacks.slice(0);
2625
- for (var i = 0, len = callbacks.length; i < len; ++i) {
2626
- callbacks[i].apply(this, args);
2627
- }
2628
- }
2629
-
2630
- return this;
2631
- };
2632
-
2633
- /**
2634
- * Return array of callbacks for `event`.
2635
- *
2636
- * @param {String} event
2637
- * @return {Array}
2638
- * @api public
2639
- */
2640
-
2641
- Emitter.prototype.listeners = function(event){
2642
- this._callbacks = this._callbacks || {};
2643
- return this._callbacks[event] || [];
2644
- };
2645
-
2646
- /**
2647
- * Check if this emitter has `event` handlers.
2648
- *
2649
- * @param {String} event
2650
- * @return {Boolean}
2651
- * @api public
2652
- */
2653
-
2654
- Emitter.prototype.hasListeners = function(event){
2655
- return !! this.listeners(event).length;
2656
- };
2657
-
2658
-
2659
- /***/ },
2660
- /* 3 */
2661
- /***/ function(module, exports, __webpack_require__) {
2662
-
2663
-
2664
- /**
2665
- * Reduce `arr` with `fn`.
2666
- *
2667
- * @param {Array} arr
2668
- * @param {Function} fn
2669
- * @param {Mixed} initial
2670
- *
2671
- * TODO: combatible error handling?
2672
- */
2673
-
2674
- module.exports = function(arr, fn, initial){
2675
- var idx = 0;
2676
- var len = arr.length;
2677
- var curr = arguments.length == 3
2678
- ? initial
2679
- : arr[idx++];
2680
-
2681
- while (idx < len) {
2682
- curr = fn.call(null, curr, arr[idx], ++idx, arr);
2683
- }
2684
-
2685
- return curr;
2686
- };
2687
-
2688
- /***/ }
2689
- /******/ ]);
2690
- //# sourceMappingURL=clerk.js.map