UNPKG

347 kBJavaScriptView Raw
1// PouchDB 7.0.0
2//
3// (c) 2012-2018 Dale Harvey and the PouchDB team
4// PouchDB may be freely distributed under the Apache license, version 2.0.
5// For all details and documentation:
6// http://pouchdb.com
7(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PouchDB = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
8'use strict';
9
10module.exports = argsArray;
11
12function argsArray(fun) {
13 return function () {
14 var len = arguments.length;
15 if (len) {
16 var args = [];
17 var i = -1;
18 while (++i < len) {
19 args[i] = arguments[i];
20 }
21 return fun.call(this, args);
22 } else {
23 return fun.call(this, []);
24 }
25 };
26}
27},{}],2:[function(_dereq_,module,exports){
28// Copyright Joyent, Inc. and other Node contributors.
29//
30// Permission is hereby granted, free of charge, to any person obtaining a
31// copy of this software and associated documentation files (the
32// "Software"), to deal in the Software without restriction, including
33// without limitation the rights to use, copy, modify, merge, publish,
34// distribute, sublicense, and/or sell copies of the Software, and to permit
35// persons to whom the Software is furnished to do so, subject to the
36// following conditions:
37//
38// The above copyright notice and this permission notice shall be included
39// in all copies or substantial portions of the Software.
40//
41// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
42// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
43// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
44// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
45// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
46// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
47// USE OR OTHER DEALINGS IN THE SOFTWARE.
48
49var objectCreate = Object.create || objectCreatePolyfill
50var objectKeys = Object.keys || objectKeysPolyfill
51var bind = Function.prototype.bind || functionBindPolyfill
52
53function EventEmitter() {
54 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
55 this._events = objectCreate(null);
56 this._eventsCount = 0;
57 }
58
59 this._maxListeners = this._maxListeners || undefined;
60}
61module.exports = EventEmitter;
62
63// Backwards-compat with node 0.10.x
64EventEmitter.EventEmitter = EventEmitter;
65
66EventEmitter.prototype._events = undefined;
67EventEmitter.prototype._maxListeners = undefined;
68
69// By default EventEmitters will print a warning if more than 10 listeners are
70// added to it. This is a useful default which helps finding memory leaks.
71var defaultMaxListeners = 10;
72
73var hasDefineProperty;
74try {
75 var o = {};
76 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
77 hasDefineProperty = o.x === 0;
78} catch (err) { hasDefineProperty = false }
79if (hasDefineProperty) {
80 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
81 enumerable: true,
82 get: function() {
83 return defaultMaxListeners;
84 },
85 set: function(arg) {
86 // check whether the input is a positive number (whose value is zero or
87 // greater and not a NaN).
88 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
89 throw new TypeError('"defaultMaxListeners" must be a positive number');
90 defaultMaxListeners = arg;
91 }
92 });
93} else {
94 EventEmitter.defaultMaxListeners = defaultMaxListeners;
95}
96
97// Obviously not all Emitters should be limited to 10. This function allows
98// that to be increased. Set to zero for unlimited.
99EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
100 if (typeof n !== 'number' || n < 0 || isNaN(n))
101 throw new TypeError('"n" argument must be a positive number');
102 this._maxListeners = n;
103 return this;
104};
105
106function $getMaxListeners(that) {
107 if (that._maxListeners === undefined)
108 return EventEmitter.defaultMaxListeners;
109 return that._maxListeners;
110}
111
112EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
113 return $getMaxListeners(this);
114};
115
116// These standalone emit* functions are used to optimize calling of event
117// handlers for fast cases because emit() itself often has a variable number of
118// arguments and can be deoptimized because of that. These functions always have
119// the same number of arguments and thus do not get deoptimized, so the code
120// inside them can execute faster.
121function emitNone(handler, isFn, self) {
122 if (isFn)
123 handler.call(self);
124 else {
125 var len = handler.length;
126 var listeners = arrayClone(handler, len);
127 for (var i = 0; i < len; ++i)
128 listeners[i].call(self);
129 }
130}
131function emitOne(handler, isFn, self, arg1) {
132 if (isFn)
133 handler.call(self, arg1);
134 else {
135 var len = handler.length;
136 var listeners = arrayClone(handler, len);
137 for (var i = 0; i < len; ++i)
138 listeners[i].call(self, arg1);
139 }
140}
141function emitTwo(handler, isFn, self, arg1, arg2) {
142 if (isFn)
143 handler.call(self, arg1, arg2);
144 else {
145 var len = handler.length;
146 var listeners = arrayClone(handler, len);
147 for (var i = 0; i < len; ++i)
148 listeners[i].call(self, arg1, arg2);
149 }
150}
151function emitThree(handler, isFn, self, arg1, arg2, arg3) {
152 if (isFn)
153 handler.call(self, arg1, arg2, arg3);
154 else {
155 var len = handler.length;
156 var listeners = arrayClone(handler, len);
157 for (var i = 0; i < len; ++i)
158 listeners[i].call(self, arg1, arg2, arg3);
159 }
160}
161
162function emitMany(handler, isFn, self, args) {
163 if (isFn)
164 handler.apply(self, args);
165 else {
166 var len = handler.length;
167 var listeners = arrayClone(handler, len);
168 for (var i = 0; i < len; ++i)
169 listeners[i].apply(self, args);
170 }
171}
172
173EventEmitter.prototype.emit = function emit(type) {
174 var er, handler, len, args, i, events;
175 var doError = (type === 'error');
176
177 events = this._events;
178 if (events)
179 doError = (doError && events.error == null);
180 else if (!doError)
181 return false;
182
183 // If there is no 'error' event listener then throw.
184 if (doError) {
185 if (arguments.length > 1)
186 er = arguments[1];
187 if (er instanceof Error) {
188 throw er; // Unhandled 'error' event
189 } else {
190 // At least give some kind of context to the user
191 var err = new Error('Unhandled "error" event. (' + er + ')');
192 err.context = er;
193 throw err;
194 }
195 return false;
196 }
197
198 handler = events[type];
199
200 if (!handler)
201 return false;
202
203 var isFn = typeof handler === 'function';
204 len = arguments.length;
205 switch (len) {
206 // fast cases
207 case 1:
208 emitNone(handler, isFn, this);
209 break;
210 case 2:
211 emitOne(handler, isFn, this, arguments[1]);
212 break;
213 case 3:
214 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
215 break;
216 case 4:
217 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
218 break;
219 // slower
220 default:
221 args = new Array(len - 1);
222 for (i = 1; i < len; i++)
223 args[i - 1] = arguments[i];
224 emitMany(handler, isFn, this, args);
225 }
226
227 return true;
228};
229
230function _addListener(target, type, listener, prepend) {
231 var m;
232 var events;
233 var existing;
234
235 if (typeof listener !== 'function')
236 throw new TypeError('"listener" argument must be a function');
237
238 events = target._events;
239 if (!events) {
240 events = target._events = objectCreate(null);
241 target._eventsCount = 0;
242 } else {
243 // To avoid recursion in the case that type === "newListener"! Before
244 // adding it to the listeners, first emit "newListener".
245 if (events.newListener) {
246 target.emit('newListener', type,
247 listener.listener ? listener.listener : listener);
248
249 // Re-assign `events` because a newListener handler could have caused the
250 // this._events to be assigned to a new object
251 events = target._events;
252 }
253 existing = events[type];
254 }
255
256 if (!existing) {
257 // Optimize the case of one listener. Don't need the extra array object.
258 existing = events[type] = listener;
259 ++target._eventsCount;
260 } else {
261 if (typeof existing === 'function') {
262 // Adding the second element, need to change to array.
263 existing = events[type] =
264 prepend ? [listener, existing] : [existing, listener];
265 } else {
266 // If we've already got an array, just append.
267 if (prepend) {
268 existing.unshift(listener);
269 } else {
270 existing.push(listener);
271 }
272 }
273
274 // Check for listener leak
275 if (!existing.warned) {
276 m = $getMaxListeners(target);
277 if (m && m > 0 && existing.length > m) {
278 existing.warned = true;
279 var w = new Error('Possible EventEmitter memory leak detected. ' +
280 existing.length + ' "' + String(type) + '" listeners ' +
281 'added. Use emitter.setMaxListeners() to ' +
282 'increase limit.');
283 w.name = 'MaxListenersExceededWarning';
284 w.emitter = target;
285 w.type = type;
286 w.count = existing.length;
287 if (typeof console === 'object' && console.warn) {
288 console.warn('%s: %s', w.name, w.message);
289 }
290 }
291 }
292 }
293
294 return target;
295}
296
297EventEmitter.prototype.addListener = function addListener(type, listener) {
298 return _addListener(this, type, listener, false);
299};
300
301EventEmitter.prototype.on = EventEmitter.prototype.addListener;
302
303EventEmitter.prototype.prependListener =
304 function prependListener(type, listener) {
305 return _addListener(this, type, listener, true);
306 };
307
308function onceWrapper() {
309 if (!this.fired) {
310 this.target.removeListener(this.type, this.wrapFn);
311 this.fired = true;
312 switch (arguments.length) {
313 case 0:
314 return this.listener.call(this.target);
315 case 1:
316 return this.listener.call(this.target, arguments[0]);
317 case 2:
318 return this.listener.call(this.target, arguments[0], arguments[1]);
319 case 3:
320 return this.listener.call(this.target, arguments[0], arguments[1],
321 arguments[2]);
322 default:
323 var args = new Array(arguments.length);
324 for (var i = 0; i < args.length; ++i)
325 args[i] = arguments[i];
326 this.listener.apply(this.target, args);
327 }
328 }
329}
330
331function _onceWrap(target, type, listener) {
332 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
333 var wrapped = bind.call(onceWrapper, state);
334 wrapped.listener = listener;
335 state.wrapFn = wrapped;
336 return wrapped;
337}
338
339EventEmitter.prototype.once = function once(type, listener) {
340 if (typeof listener !== 'function')
341 throw new TypeError('"listener" argument must be a function');
342 this.on(type, _onceWrap(this, type, listener));
343 return this;
344};
345
346EventEmitter.prototype.prependOnceListener =
347 function prependOnceListener(type, listener) {
348 if (typeof listener !== 'function')
349 throw new TypeError('"listener" argument must be a function');
350 this.prependListener(type, _onceWrap(this, type, listener));
351 return this;
352 };
353
354// Emits a 'removeListener' event if and only if the listener was removed.
355EventEmitter.prototype.removeListener =
356 function removeListener(type, listener) {
357 var list, events, position, i, originalListener;
358
359 if (typeof listener !== 'function')
360 throw new TypeError('"listener" argument must be a function');
361
362 events = this._events;
363 if (!events)
364 return this;
365
366 list = events[type];
367 if (!list)
368 return this;
369
370 if (list === listener || list.listener === listener) {
371 if (--this._eventsCount === 0)
372 this._events = objectCreate(null);
373 else {
374 delete events[type];
375 if (events.removeListener)
376 this.emit('removeListener', type, list.listener || listener);
377 }
378 } else if (typeof list !== 'function') {
379 position = -1;
380
381 for (i = list.length - 1; i >= 0; i--) {
382 if (list[i] === listener || list[i].listener === listener) {
383 originalListener = list[i].listener;
384 position = i;
385 break;
386 }
387 }
388
389 if (position < 0)
390 return this;
391
392 if (position === 0)
393 list.shift();
394 else
395 spliceOne(list, position);
396
397 if (list.length === 1)
398 events[type] = list[0];
399
400 if (events.removeListener)
401 this.emit('removeListener', type, originalListener || listener);
402 }
403
404 return this;
405 };
406
407EventEmitter.prototype.removeAllListeners =
408 function removeAllListeners(type) {
409 var listeners, events, i;
410
411 events = this._events;
412 if (!events)
413 return this;
414
415 // not listening for removeListener, no need to emit
416 if (!events.removeListener) {
417 if (arguments.length === 0) {
418 this._events = objectCreate(null);
419 this._eventsCount = 0;
420 } else if (events[type]) {
421 if (--this._eventsCount === 0)
422 this._events = objectCreate(null);
423 else
424 delete events[type];
425 }
426 return this;
427 }
428
429 // emit removeListener for all listeners on all events
430 if (arguments.length === 0) {
431 var keys = objectKeys(events);
432 var key;
433 for (i = 0; i < keys.length; ++i) {
434 key = keys[i];
435 if (key === 'removeListener') continue;
436 this.removeAllListeners(key);
437 }
438 this.removeAllListeners('removeListener');
439 this._events = objectCreate(null);
440 this._eventsCount = 0;
441 return this;
442 }
443
444 listeners = events[type];
445
446 if (typeof listeners === 'function') {
447 this.removeListener(type, listeners);
448 } else if (listeners) {
449 // LIFO order
450 for (i = listeners.length - 1; i >= 0; i--) {
451 this.removeListener(type, listeners[i]);
452 }
453 }
454
455 return this;
456 };
457
458function _listeners(target, type, unwrap) {
459 var events = target._events;
460
461 if (!events)
462 return [];
463
464 var evlistener = events[type];
465 if (!evlistener)
466 return [];
467
468 if (typeof evlistener === 'function')
469 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
470
471 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
472}
473
474EventEmitter.prototype.listeners = function listeners(type) {
475 return _listeners(this, type, true);
476};
477
478EventEmitter.prototype.rawListeners = function rawListeners(type) {
479 return _listeners(this, type, false);
480};
481
482EventEmitter.listenerCount = function(emitter, type) {
483 if (typeof emitter.listenerCount === 'function') {
484 return emitter.listenerCount(type);
485 } else {
486 return listenerCount.call(emitter, type);
487 }
488};
489
490EventEmitter.prototype.listenerCount = listenerCount;
491function listenerCount(type) {
492 var events = this._events;
493
494 if (events) {
495 var evlistener = events[type];
496
497 if (typeof evlistener === 'function') {
498 return 1;
499 } else if (evlistener) {
500 return evlistener.length;
501 }
502 }
503
504 return 0;
505}
506
507EventEmitter.prototype.eventNames = function eventNames() {
508 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
509};
510
511// About 1.5x faster than the two-arg version of Array#splice().
512function spliceOne(list, index) {
513 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
514 list[i] = list[k];
515 list.pop();
516}
517
518function arrayClone(arr, n) {
519 var copy = new Array(n);
520 for (var i = 0; i < n; ++i)
521 copy[i] = arr[i];
522 return copy;
523}
524
525function unwrapListeners(arr) {
526 var ret = new Array(arr.length);
527 for (var i = 0; i < ret.length; ++i) {
528 ret[i] = arr[i].listener || arr[i];
529 }
530 return ret;
531}
532
533function objectCreatePolyfill(proto) {
534 var F = function() {};
535 F.prototype = proto;
536 return new F;
537}
538function objectKeysPolyfill(obj) {
539 var keys = [];
540 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
541 keys.push(k);
542 }
543 return k;
544}
545function functionBindPolyfill(context) {
546 var fn = this;
547 return function () {
548 return fn.apply(context, arguments);
549 };
550}
551
552},{}],3:[function(_dereq_,module,exports){
553(function (global){
554'use strict';
555var Mutation = global.MutationObserver || global.WebKitMutationObserver;
556
557var scheduleDrain;
558
559{
560 if (Mutation) {
561 var called = 0;
562 var observer = new Mutation(nextTick);
563 var element = global.document.createTextNode('');
564 observer.observe(element, {
565 characterData: true
566 });
567 scheduleDrain = function () {
568 element.data = (called = ++called % 2);
569 };
570 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
571 var channel = new global.MessageChannel();
572 channel.port1.onmessage = nextTick;
573 scheduleDrain = function () {
574 channel.port2.postMessage(0);
575 };
576 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
577 scheduleDrain = function () {
578
579 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
580 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
581 var scriptEl = global.document.createElement('script');
582 scriptEl.onreadystatechange = function () {
583 nextTick();
584
585 scriptEl.onreadystatechange = null;
586 scriptEl.parentNode.removeChild(scriptEl);
587 scriptEl = null;
588 };
589 global.document.documentElement.appendChild(scriptEl);
590 };
591 } else {
592 scheduleDrain = function () {
593 setTimeout(nextTick, 0);
594 };
595 }
596}
597
598var draining;
599var queue = [];
600//named nextTick for less confusing stack traces
601function nextTick() {
602 draining = true;
603 var i, oldQueue;
604 var len = queue.length;
605 while (len) {
606 oldQueue = queue;
607 queue = [];
608 i = -1;
609 while (++i < len) {
610 oldQueue[i]();
611 }
612 len = queue.length;
613 }
614 draining = false;
615}
616
617module.exports = immediate;
618function immediate(task) {
619 if (queue.push(task) === 1 && !draining) {
620 scheduleDrain();
621 }
622}
623
624}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
625},{}],4:[function(_dereq_,module,exports){
626if (typeof Object.create === 'function') {
627 // implementation from standard node.js 'util' module
628 module.exports = function inherits(ctor, superCtor) {
629 ctor.super_ = superCtor
630 ctor.prototype = Object.create(superCtor.prototype, {
631 constructor: {
632 value: ctor,
633 enumerable: false,
634 writable: true,
635 configurable: true
636 }
637 });
638 };
639} else {
640 // old school shim for old browsers
641 module.exports = function inherits(ctor, superCtor) {
642 ctor.super_ = superCtor
643 var TempCtor = function () {}
644 TempCtor.prototype = superCtor.prototype
645 ctor.prototype = new TempCtor()
646 ctor.prototype.constructor = ctor
647 }
648}
649
650},{}],5:[function(_dereq_,module,exports){
651// shim for using process in browser
652var process = module.exports = {};
653
654// cached from whatever global is present so that test runners that stub it
655// don't break things. But we need to wrap it in a try catch in case it is
656// wrapped in strict mode code which doesn't define any globals. It's inside a
657// function because try/catches deoptimize in certain engines.
658
659var cachedSetTimeout;
660var cachedClearTimeout;
661
662function defaultSetTimout() {
663 throw new Error('setTimeout has not been defined');
664}
665function defaultClearTimeout () {
666 throw new Error('clearTimeout has not been defined');
667}
668(function () {
669 try {
670 if (typeof setTimeout === 'function') {
671 cachedSetTimeout = setTimeout;
672 } else {
673 cachedSetTimeout = defaultSetTimout;
674 }
675 } catch (e) {
676 cachedSetTimeout = defaultSetTimout;
677 }
678 try {
679 if (typeof clearTimeout === 'function') {
680 cachedClearTimeout = clearTimeout;
681 } else {
682 cachedClearTimeout = defaultClearTimeout;
683 }
684 } catch (e) {
685 cachedClearTimeout = defaultClearTimeout;
686 }
687} ())
688function runTimeout(fun) {
689 if (cachedSetTimeout === setTimeout) {
690 //normal enviroments in sane situations
691 return setTimeout(fun, 0);
692 }
693 // if setTimeout wasn't available but was latter defined
694 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
695 cachedSetTimeout = setTimeout;
696 return setTimeout(fun, 0);
697 }
698 try {
699 // when when somebody has screwed with setTimeout but no I.E. maddness
700 return cachedSetTimeout(fun, 0);
701 } catch(e){
702 try {
703 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
704 return cachedSetTimeout.call(null, fun, 0);
705 } catch(e){
706 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
707 return cachedSetTimeout.call(this, fun, 0);
708 }
709 }
710
711
712}
713function runClearTimeout(marker) {
714 if (cachedClearTimeout === clearTimeout) {
715 //normal enviroments in sane situations
716 return clearTimeout(marker);
717 }
718 // if clearTimeout wasn't available but was latter defined
719 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
720 cachedClearTimeout = clearTimeout;
721 return clearTimeout(marker);
722 }
723 try {
724 // when when somebody has screwed with setTimeout but no I.E. maddness
725 return cachedClearTimeout(marker);
726 } catch (e){
727 try {
728 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
729 return cachedClearTimeout.call(null, marker);
730 } catch (e){
731 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
732 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
733 return cachedClearTimeout.call(this, marker);
734 }
735 }
736
737
738
739}
740var queue = [];
741var draining = false;
742var currentQueue;
743var queueIndex = -1;
744
745function cleanUpNextTick() {
746 if (!draining || !currentQueue) {
747 return;
748 }
749 draining = false;
750 if (currentQueue.length) {
751 queue = currentQueue.concat(queue);
752 } else {
753 queueIndex = -1;
754 }
755 if (queue.length) {
756 drainQueue();
757 }
758}
759
760function drainQueue() {
761 if (draining) {
762 return;
763 }
764 var timeout = runTimeout(cleanUpNextTick);
765 draining = true;
766
767 var len = queue.length;
768 while(len) {
769 currentQueue = queue;
770 queue = [];
771 while (++queueIndex < len) {
772 if (currentQueue) {
773 currentQueue[queueIndex].run();
774 }
775 }
776 queueIndex = -1;
777 len = queue.length;
778 }
779 currentQueue = null;
780 draining = false;
781 runClearTimeout(timeout);
782}
783
784process.nextTick = function (fun) {
785 var args = new Array(arguments.length - 1);
786 if (arguments.length > 1) {
787 for (var i = 1; i < arguments.length; i++) {
788 args[i - 1] = arguments[i];
789 }
790 }
791 queue.push(new Item(fun, args));
792 if (queue.length === 1 && !draining) {
793 runTimeout(drainQueue);
794 }
795};
796
797// v8 likes predictible objects
798function Item(fun, array) {
799 this.fun = fun;
800 this.array = array;
801}
802Item.prototype.run = function () {
803 this.fun.apply(null, this.array);
804};
805process.title = 'browser';
806process.browser = true;
807process.env = {};
808process.argv = [];
809process.version = ''; // empty string to avoid regexp issues
810process.versions = {};
811
812function noop() {}
813
814process.on = noop;
815process.addListener = noop;
816process.once = noop;
817process.off = noop;
818process.removeListener = noop;
819process.removeAllListeners = noop;
820process.emit = noop;
821process.prependListener = noop;
822process.prependOnceListener = noop;
823
824process.listeners = function (name) { return [] }
825
826process.binding = function (name) {
827 throw new Error('process.binding is not supported');
828};
829
830process.cwd = function () { return '/' };
831process.chdir = function (dir) {
832 throw new Error('process.chdir is not supported');
833};
834process.umask = function() { return 0; };
835
836},{}],6:[function(_dereq_,module,exports){
837(function (factory) {
838 if (typeof exports === 'object') {
839 // Node/CommonJS
840 module.exports = factory();
841 } else if (typeof define === 'function' && define.amd) {
842 // AMD
843 define(factory);
844 } else {
845 // Browser globals (with support for web workers)
846 var glob;
847
848 try {
849 glob = window;
850 } catch (e) {
851 glob = self;
852 }
853
854 glob.SparkMD5 = factory();
855 }
856}(function (undefined) {
857
858 'use strict';
859
860 /*
861 * Fastest md5 implementation around (JKM md5).
862 * Credits: Joseph Myers
863 *
864 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
865 * @see http://jsperf.com/md5-shootout/7
866 */
867
868 /* this function is much faster,
869 so if possible we use it. Some IEs
870 are the only ones I know of that
871 need the idiotic second function,
872 generated by an if clause. */
873 var add32 = function (a, b) {
874 return (a + b) & 0xFFFFFFFF;
875 },
876 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
877
878
879 function cmn(q, a, b, x, s, t) {
880 a = add32(add32(a, q), add32(x, t));
881 return add32((a << s) | (a >>> (32 - s)), b);
882 }
883
884 function md5cycle(x, k) {
885 var a = x[0],
886 b = x[1],
887 c = x[2],
888 d = x[3];
889
890 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
891 a = (a << 7 | a >>> 25) + b | 0;
892 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
893 d = (d << 12 | d >>> 20) + a | 0;
894 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
895 c = (c << 17 | c >>> 15) + d | 0;
896 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
897 b = (b << 22 | b >>> 10) + c | 0;
898 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
899 a = (a << 7 | a >>> 25) + b | 0;
900 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
901 d = (d << 12 | d >>> 20) + a | 0;
902 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
903 c = (c << 17 | c >>> 15) + d | 0;
904 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
905 b = (b << 22 | b >>> 10) + c | 0;
906 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
907 a = (a << 7 | a >>> 25) + b | 0;
908 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
909 d = (d << 12 | d >>> 20) + a | 0;
910 c += (d & a | ~d & b) + k[10] - 42063 | 0;
911 c = (c << 17 | c >>> 15) + d | 0;
912 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
913 b = (b << 22 | b >>> 10) + c | 0;
914 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
915 a = (a << 7 | a >>> 25) + b | 0;
916 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
917 d = (d << 12 | d >>> 20) + a | 0;
918 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
919 c = (c << 17 | c >>> 15) + d | 0;
920 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
921 b = (b << 22 | b >>> 10) + c | 0;
922
923 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
924 a = (a << 5 | a >>> 27) + b | 0;
925 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
926 d = (d << 9 | d >>> 23) + a | 0;
927 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
928 c = (c << 14 | c >>> 18) + d | 0;
929 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
930 b = (b << 20 | b >>> 12) + c | 0;
931 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
932 a = (a << 5 | a >>> 27) + b | 0;
933 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
934 d = (d << 9 | d >>> 23) + a | 0;
935 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
936 c = (c << 14 | c >>> 18) + d | 0;
937 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
938 b = (b << 20 | b >>> 12) + c | 0;
939 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
940 a = (a << 5 | a >>> 27) + b | 0;
941 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
942 d = (d << 9 | d >>> 23) + a | 0;
943 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
944 c = (c << 14 | c >>> 18) + d | 0;
945 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
946 b = (b << 20 | b >>> 12) + c | 0;
947 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
948 a = (a << 5 | a >>> 27) + b | 0;
949 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
950 d = (d << 9 | d >>> 23) + a | 0;
951 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
952 c = (c << 14 | c >>> 18) + d | 0;
953 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
954 b = (b << 20 | b >>> 12) + c | 0;
955
956 a += (b ^ c ^ d) + k[5] - 378558 | 0;
957 a = (a << 4 | a >>> 28) + b | 0;
958 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
959 d = (d << 11 | d >>> 21) + a | 0;
960 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
961 c = (c << 16 | c >>> 16) + d | 0;
962 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
963 b = (b << 23 | b >>> 9) + c | 0;
964 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
965 a = (a << 4 | a >>> 28) + b | 0;
966 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
967 d = (d << 11 | d >>> 21) + a | 0;
968 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
969 c = (c << 16 | c >>> 16) + d | 0;
970 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
971 b = (b << 23 | b >>> 9) + c | 0;
972 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
973 a = (a << 4 | a >>> 28) + b | 0;
974 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
975 d = (d << 11 | d >>> 21) + a | 0;
976 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
977 c = (c << 16 | c >>> 16) + d | 0;
978 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
979 b = (b << 23 | b >>> 9) + c | 0;
980 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
981 a = (a << 4 | a >>> 28) + b | 0;
982 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
983 d = (d << 11 | d >>> 21) + a | 0;
984 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
985 c = (c << 16 | c >>> 16) + d | 0;
986 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
987 b = (b << 23 | b >>> 9) + c | 0;
988
989 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
990 a = (a << 6 | a >>> 26) + b | 0;
991 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
992 d = (d << 10 | d >>> 22) + a | 0;
993 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
994 c = (c << 15 | c >>> 17) + d | 0;
995 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
996 b = (b << 21 |b >>> 11) + c | 0;
997 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
998 a = (a << 6 | a >>> 26) + b | 0;
999 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
1000 d = (d << 10 | d >>> 22) + a | 0;
1001 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
1002 c = (c << 15 | c >>> 17) + d | 0;
1003 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
1004 b = (b << 21 |b >>> 11) + c | 0;
1005 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
1006 a = (a << 6 | a >>> 26) + b | 0;
1007 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
1008 d = (d << 10 | d >>> 22) + a | 0;
1009 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
1010 c = (c << 15 | c >>> 17) + d | 0;
1011 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
1012 b = (b << 21 |b >>> 11) + c | 0;
1013 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
1014 a = (a << 6 | a >>> 26) + b | 0;
1015 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
1016 d = (d << 10 | d >>> 22) + a | 0;
1017 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
1018 c = (c << 15 | c >>> 17) + d | 0;
1019 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
1020 b = (b << 21 | b >>> 11) + c | 0;
1021
1022 x[0] = a + x[0] | 0;
1023 x[1] = b + x[1] | 0;
1024 x[2] = c + x[2] | 0;
1025 x[3] = d + x[3] | 0;
1026 }
1027
1028 function md5blk(s) {
1029 var md5blks = [],
1030 i; /* Andy King said do it this way. */
1031
1032 for (i = 0; i < 64; i += 4) {
1033 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
1034 }
1035 return md5blks;
1036 }
1037
1038 function md5blk_array(a) {
1039 var md5blks = [],
1040 i; /* Andy King said do it this way. */
1041
1042 for (i = 0; i < 64; i += 4) {
1043 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
1044 }
1045 return md5blks;
1046 }
1047
1048 function md51(s) {
1049 var n = s.length,
1050 state = [1732584193, -271733879, -1732584194, 271733878],
1051 i,
1052 length,
1053 tail,
1054 tmp,
1055 lo,
1056 hi;
1057
1058 for (i = 64; i <= n; i += 64) {
1059 md5cycle(state, md5blk(s.substring(i - 64, i)));
1060 }
1061 s = s.substring(i - 64);
1062 length = s.length;
1063 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1064 for (i = 0; i < length; i += 1) {
1065 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
1066 }
1067 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1068 if (i > 55) {
1069 md5cycle(state, tail);
1070 for (i = 0; i < 16; i += 1) {
1071 tail[i] = 0;
1072 }
1073 }
1074
1075 // Beware that the final length might not fit in 32 bits so we take care of that
1076 tmp = n * 8;
1077 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1078 lo = parseInt(tmp[2], 16);
1079 hi = parseInt(tmp[1], 16) || 0;
1080
1081 tail[14] = lo;
1082 tail[15] = hi;
1083
1084 md5cycle(state, tail);
1085 return state;
1086 }
1087
1088 function md51_array(a) {
1089 var n = a.length,
1090 state = [1732584193, -271733879, -1732584194, 271733878],
1091 i,
1092 length,
1093 tail,
1094 tmp,
1095 lo,
1096 hi;
1097
1098 for (i = 64; i <= n; i += 64) {
1099 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
1100 }
1101
1102 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
1103 // containing the last element of the parent array if the sub array specified starts
1104 // beyond the length of the parent array - weird.
1105 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
1106 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
1107
1108 length = a.length;
1109 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1110 for (i = 0; i < length; i += 1) {
1111 tail[i >> 2] |= a[i] << ((i % 4) << 3);
1112 }
1113
1114 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1115 if (i > 55) {
1116 md5cycle(state, tail);
1117 for (i = 0; i < 16; i += 1) {
1118 tail[i] = 0;
1119 }
1120 }
1121
1122 // Beware that the final length might not fit in 32 bits so we take care of that
1123 tmp = n * 8;
1124 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1125 lo = parseInt(tmp[2], 16);
1126 hi = parseInt(tmp[1], 16) || 0;
1127
1128 tail[14] = lo;
1129 tail[15] = hi;
1130
1131 md5cycle(state, tail);
1132
1133 return state;
1134 }
1135
1136 function rhex(n) {
1137 var s = '',
1138 j;
1139 for (j = 0; j < 4; j += 1) {
1140 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
1141 }
1142 return s;
1143 }
1144
1145 function hex(x) {
1146 var i;
1147 for (i = 0; i < x.length; i += 1) {
1148 x[i] = rhex(x[i]);
1149 }
1150 return x.join('');
1151 }
1152
1153 // In some cases the fast add32 function cannot be used..
1154 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
1155 add32 = function (x, y) {
1156 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
1157 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
1158 return (msw << 16) | (lsw & 0xFFFF);
1159 };
1160 }
1161
1162 // ---------------------------------------------------
1163
1164 /**
1165 * ArrayBuffer slice polyfill.
1166 *
1167 * @see https://github.com/ttaubert/node-arraybuffer-slice
1168 */
1169
1170 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
1171 (function () {
1172 function clamp(val, length) {
1173 val = (val | 0) || 0;
1174
1175 if (val < 0) {
1176 return Math.max(val + length, 0);
1177 }
1178
1179 return Math.min(val, length);
1180 }
1181
1182 ArrayBuffer.prototype.slice = function (from, to) {
1183 var length = this.byteLength,
1184 begin = clamp(from, length),
1185 end = length,
1186 num,
1187 target,
1188 targetArray,
1189 sourceArray;
1190
1191 if (to !== undefined) {
1192 end = clamp(to, length);
1193 }
1194
1195 if (begin > end) {
1196 return new ArrayBuffer(0);
1197 }
1198
1199 num = end - begin;
1200 target = new ArrayBuffer(num);
1201 targetArray = new Uint8Array(target);
1202
1203 sourceArray = new Uint8Array(this, begin, num);
1204 targetArray.set(sourceArray);
1205
1206 return target;
1207 };
1208 })();
1209 }
1210
1211 // ---------------------------------------------------
1212
1213 /**
1214 * Helpers.
1215 */
1216
1217 function toUtf8(str) {
1218 if (/[\u0080-\uFFFF]/.test(str)) {
1219 str = unescape(encodeURIComponent(str));
1220 }
1221
1222 return str;
1223 }
1224
1225 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
1226 var length = str.length,
1227 buff = new ArrayBuffer(length),
1228 arr = new Uint8Array(buff),
1229 i;
1230
1231 for (i = 0; i < length; i += 1) {
1232 arr[i] = str.charCodeAt(i);
1233 }
1234
1235 return returnUInt8Array ? arr : buff;
1236 }
1237
1238 function arrayBuffer2Utf8Str(buff) {
1239 return String.fromCharCode.apply(null, new Uint8Array(buff));
1240 }
1241
1242 function concatenateArrayBuffers(first, second, returnUInt8Array) {
1243 var result = new Uint8Array(first.byteLength + second.byteLength);
1244
1245 result.set(new Uint8Array(first));
1246 result.set(new Uint8Array(second), first.byteLength);
1247
1248 return returnUInt8Array ? result : result.buffer;
1249 }
1250
1251 function hexToBinaryString(hex) {
1252 var bytes = [],
1253 length = hex.length,
1254 x;
1255
1256 for (x = 0; x < length - 1; x += 2) {
1257 bytes.push(parseInt(hex.substr(x, 2), 16));
1258 }
1259
1260 return String.fromCharCode.apply(String, bytes);
1261 }
1262
1263 // ---------------------------------------------------
1264
1265 /**
1266 * SparkMD5 OOP implementation.
1267 *
1268 * Use this class to perform an incremental md5, otherwise use the
1269 * static methods instead.
1270 */
1271
1272 function SparkMD5() {
1273 // call reset to init the instance
1274 this.reset();
1275 }
1276
1277 /**
1278 * Appends a string.
1279 * A conversion will be applied if an utf8 string is detected.
1280 *
1281 * @param {String} str The string to be appended
1282 *
1283 * @return {SparkMD5} The instance itself
1284 */
1285 SparkMD5.prototype.append = function (str) {
1286 // Converts the string to utf8 bytes if necessary
1287 // Then append as binary
1288 this.appendBinary(toUtf8(str));
1289
1290 return this;
1291 };
1292
1293 /**
1294 * Appends a binary string.
1295 *
1296 * @param {String} contents The binary string to be appended
1297 *
1298 * @return {SparkMD5} The instance itself
1299 */
1300 SparkMD5.prototype.appendBinary = function (contents) {
1301 this._buff += contents;
1302 this._length += contents.length;
1303
1304 var length = this._buff.length,
1305 i;
1306
1307 for (i = 64; i <= length; i += 64) {
1308 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
1309 }
1310
1311 this._buff = this._buff.substring(i - 64);
1312
1313 return this;
1314 };
1315
1316 /**
1317 * Finishes the incremental computation, reseting the internal state and
1318 * returning the result.
1319 *
1320 * @param {Boolean} raw True to get the raw string, false to get the hex string
1321 *
1322 * @return {String} The result
1323 */
1324 SparkMD5.prototype.end = function (raw) {
1325 var buff = this._buff,
1326 length = buff.length,
1327 i,
1328 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1329 ret;
1330
1331 for (i = 0; i < length; i += 1) {
1332 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
1333 }
1334
1335 this._finish(tail, length);
1336 ret = hex(this._hash);
1337
1338 if (raw) {
1339 ret = hexToBinaryString(ret);
1340 }
1341
1342 this.reset();
1343
1344 return ret;
1345 };
1346
1347 /**
1348 * Resets the internal state of the computation.
1349 *
1350 * @return {SparkMD5} The instance itself
1351 */
1352 SparkMD5.prototype.reset = function () {
1353 this._buff = '';
1354 this._length = 0;
1355 this._hash = [1732584193, -271733879, -1732584194, 271733878];
1356
1357 return this;
1358 };
1359
1360 /**
1361 * Gets the internal state of the computation.
1362 *
1363 * @return {Object} The state
1364 */
1365 SparkMD5.prototype.getState = function () {
1366 return {
1367 buff: this._buff,
1368 length: this._length,
1369 hash: this._hash
1370 };
1371 };
1372
1373 /**
1374 * Gets the internal state of the computation.
1375 *
1376 * @param {Object} state The state
1377 *
1378 * @return {SparkMD5} The instance itself
1379 */
1380 SparkMD5.prototype.setState = function (state) {
1381 this._buff = state.buff;
1382 this._length = state.length;
1383 this._hash = state.hash;
1384
1385 return this;
1386 };
1387
1388 /**
1389 * Releases memory used by the incremental buffer and other additional
1390 * resources. If you plan to use the instance again, use reset instead.
1391 */
1392 SparkMD5.prototype.destroy = function () {
1393 delete this._hash;
1394 delete this._buff;
1395 delete this._length;
1396 };
1397
1398 /**
1399 * Finish the final calculation based on the tail.
1400 *
1401 * @param {Array} tail The tail (will be modified)
1402 * @param {Number} length The length of the remaining buffer
1403 */
1404 SparkMD5.prototype._finish = function (tail, length) {
1405 var i = length,
1406 tmp,
1407 lo,
1408 hi;
1409
1410 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1411 if (i > 55) {
1412 md5cycle(this._hash, tail);
1413 for (i = 0; i < 16; i += 1) {
1414 tail[i] = 0;
1415 }
1416 }
1417
1418 // Do the final computation based on the tail and length
1419 // Beware that the final length may not fit in 32 bits so we take care of that
1420 tmp = this._length * 8;
1421 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1422 lo = parseInt(tmp[2], 16);
1423 hi = parseInt(tmp[1], 16) || 0;
1424
1425 tail[14] = lo;
1426 tail[15] = hi;
1427 md5cycle(this._hash, tail);
1428 };
1429
1430 /**
1431 * Performs the md5 hash on a string.
1432 * A conversion will be applied if utf8 string is detected.
1433 *
1434 * @param {String} str The string
1435 * @param {Boolean} raw True to get the raw string, false to get the hex string
1436 *
1437 * @return {String} The result
1438 */
1439 SparkMD5.hash = function (str, raw) {
1440 // Converts the string to utf8 bytes if necessary
1441 // Then compute it using the binary function
1442 return SparkMD5.hashBinary(toUtf8(str), raw);
1443 };
1444
1445 /**
1446 * Performs the md5 hash on a binary string.
1447 *
1448 * @param {String} content The binary string
1449 * @param {Boolean} raw True to get the raw string, false to get the hex string
1450 *
1451 * @return {String} The result
1452 */
1453 SparkMD5.hashBinary = function (content, raw) {
1454 var hash = md51(content),
1455 ret = hex(hash);
1456
1457 return raw ? hexToBinaryString(ret) : ret;
1458 };
1459
1460 // ---------------------------------------------------
1461
1462 /**
1463 * SparkMD5 OOP implementation for array buffers.
1464 *
1465 * Use this class to perform an incremental md5 ONLY for array buffers.
1466 */
1467 SparkMD5.ArrayBuffer = function () {
1468 // call reset to init the instance
1469 this.reset();
1470 };
1471
1472 /**
1473 * Appends an array buffer.
1474 *
1475 * @param {ArrayBuffer} arr The array to be appended
1476 *
1477 * @return {SparkMD5.ArrayBuffer} The instance itself
1478 */
1479 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
1480 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
1481 length = buff.length,
1482 i;
1483
1484 this._length += arr.byteLength;
1485
1486 for (i = 64; i <= length; i += 64) {
1487 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
1488 }
1489
1490 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
1491
1492 return this;
1493 };
1494
1495 /**
1496 * Finishes the incremental computation, reseting the internal state and
1497 * returning the result.
1498 *
1499 * @param {Boolean} raw True to get the raw string, false to get the hex string
1500 *
1501 * @return {String} The result
1502 */
1503 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
1504 var buff = this._buff,
1505 length = buff.length,
1506 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1507 i,
1508 ret;
1509
1510 for (i = 0; i < length; i += 1) {
1511 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
1512 }
1513
1514 this._finish(tail, length);
1515 ret = hex(this._hash);
1516
1517 if (raw) {
1518 ret = hexToBinaryString(ret);
1519 }
1520
1521 this.reset();
1522
1523 return ret;
1524 };
1525
1526 /**
1527 * Resets the internal state of the computation.
1528 *
1529 * @return {SparkMD5.ArrayBuffer} The instance itself
1530 */
1531 SparkMD5.ArrayBuffer.prototype.reset = function () {
1532 this._buff = new Uint8Array(0);
1533 this._length = 0;
1534 this._hash = [1732584193, -271733879, -1732584194, 271733878];
1535
1536 return this;
1537 };
1538
1539 /**
1540 * Gets the internal state of the computation.
1541 *
1542 * @return {Object} The state
1543 */
1544 SparkMD5.ArrayBuffer.prototype.getState = function () {
1545 var state = SparkMD5.prototype.getState.call(this);
1546
1547 // Convert buffer to a string
1548 state.buff = arrayBuffer2Utf8Str(state.buff);
1549
1550 return state;
1551 };
1552
1553 /**
1554 * Gets the internal state of the computation.
1555 *
1556 * @param {Object} state The state
1557 *
1558 * @return {SparkMD5.ArrayBuffer} The instance itself
1559 */
1560 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
1561 // Convert string to buffer
1562 state.buff = utf8Str2ArrayBuffer(state.buff, true);
1563
1564 return SparkMD5.prototype.setState.call(this, state);
1565 };
1566
1567 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
1568
1569 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
1570
1571 /**
1572 * Performs the md5 hash on an array buffer.
1573 *
1574 * @param {ArrayBuffer} arr The array buffer
1575 * @param {Boolean} raw True to get the raw string, false to get the hex one
1576 *
1577 * @return {String} The result
1578 */
1579 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
1580 var hash = md51_array(new Uint8Array(arr)),
1581 ret = hex(hash);
1582
1583 return raw ? hexToBinaryString(ret) : ret;
1584 };
1585
1586 return SparkMD5;
1587}));
1588
1589},{}],7:[function(_dereq_,module,exports){
1590var v1 = _dereq_(10);
1591var v4 = _dereq_(11);
1592
1593var uuid = v4;
1594uuid.v1 = v1;
1595uuid.v4 = v4;
1596
1597module.exports = uuid;
1598
1599},{"10":10,"11":11}],8:[function(_dereq_,module,exports){
1600/**
1601 * Convert array of 16 byte values to UUID string format of the form:
1602 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1603 */
1604var byteToHex = [];
1605for (var i = 0; i < 256; ++i) {
1606 byteToHex[i] = (i + 0x100).toString(16).substr(1);
1607}
1608
1609function bytesToUuid(buf, offset) {
1610 var i = offset || 0;
1611 var bth = byteToHex;
1612 return bth[buf[i++]] + bth[buf[i++]] +
1613 bth[buf[i++]] + bth[buf[i++]] + '-' +
1614 bth[buf[i++]] + bth[buf[i++]] + '-' +
1615 bth[buf[i++]] + bth[buf[i++]] + '-' +
1616 bth[buf[i++]] + bth[buf[i++]] + '-' +
1617 bth[buf[i++]] + bth[buf[i++]] +
1618 bth[buf[i++]] + bth[buf[i++]] +
1619 bth[buf[i++]] + bth[buf[i++]];
1620}
1621
1622module.exports = bytesToUuid;
1623
1624},{}],9:[function(_dereq_,module,exports){
1625// Unique ID creation requires a high quality random # generator. In the
1626// browser this is a little complicated due to unknown quality of Math.random()
1627// and inconsistent support for the `crypto` API. We do the best we can via
1628// feature-detection
1629
1630// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
1631var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||
1632 (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));
1633if (getRandomValues) {
1634 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
1635 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
1636
1637 module.exports = function whatwgRNG() {
1638 getRandomValues(rnds8);
1639 return rnds8;
1640 };
1641} else {
1642 // Math.random()-based (RNG)
1643 //
1644 // If all else fails, use Math.random(). It's fast, but is of unspecified
1645 // quality.
1646 var rnds = new Array(16);
1647
1648 module.exports = function mathRNG() {
1649 for (var i = 0, r; i < 16; i++) {
1650 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
1651 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
1652 }
1653
1654 return rnds;
1655 };
1656}
1657
1658},{}],10:[function(_dereq_,module,exports){
1659var rng = _dereq_(9);
1660var bytesToUuid = _dereq_(8);
1661
1662// **`v1()` - Generate time-based UUID**
1663//
1664// Inspired by https://github.com/LiosK/UUID.js
1665// and http://docs.python.org/library/uuid.html
1666
1667var _nodeId;
1668var _clockseq;
1669
1670// Previous uuid creation time
1671var _lastMSecs = 0;
1672var _lastNSecs = 0;
1673
1674// See https://github.com/broofa/node-uuid for API details
1675function v1(options, buf, offset) {
1676 var i = buf && offset || 0;
1677 var b = buf || [];
1678
1679 options = options || {};
1680 var node = options.node || _nodeId;
1681 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
1682
1683 // node and clockseq need to be initialized to random values if they're not
1684 // specified. We do this lazily to minimize issues related to insufficient
1685 // system entropy. See #189
1686 if (node == null || clockseq == null) {
1687 var seedBytes = rng();
1688 if (node == null) {
1689 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
1690 node = _nodeId = [
1691 seedBytes[0] | 0x01,
1692 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
1693 ];
1694 }
1695 if (clockseq == null) {
1696 // Per 4.2.2, randomize (14 bit) clockseq
1697 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
1698 }
1699 }
1700
1701 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
1702 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
1703 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
1704 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
1705 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
1706
1707 // Per 4.2.1.2, use count of uuid's generated during the current clock
1708 // cycle to simulate higher resolution clock
1709 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
1710
1711 // Time since last uuid creation (in msecs)
1712 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
1713
1714 // Per 4.2.1.2, Bump clockseq on clock regression
1715 if (dt < 0 && options.clockseq === undefined) {
1716 clockseq = clockseq + 1 & 0x3fff;
1717 }
1718
1719 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
1720 // time interval
1721 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
1722 nsecs = 0;
1723 }
1724
1725 // Per 4.2.1.2 Throw error if too many uuids are requested
1726 if (nsecs >= 10000) {
1727 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
1728 }
1729
1730 _lastMSecs = msecs;
1731 _lastNSecs = nsecs;
1732 _clockseq = clockseq;
1733
1734 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
1735 msecs += 12219292800000;
1736
1737 // `time_low`
1738 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
1739 b[i++] = tl >>> 24 & 0xff;
1740 b[i++] = tl >>> 16 & 0xff;
1741 b[i++] = tl >>> 8 & 0xff;
1742 b[i++] = tl & 0xff;
1743
1744 // `time_mid`
1745 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
1746 b[i++] = tmh >>> 8 & 0xff;
1747 b[i++] = tmh & 0xff;
1748
1749 // `time_high_and_version`
1750 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
1751 b[i++] = tmh >>> 16 & 0xff;
1752
1753 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
1754 b[i++] = clockseq >>> 8 | 0x80;
1755
1756 // `clock_seq_low`
1757 b[i++] = clockseq & 0xff;
1758
1759 // `node`
1760 for (var n = 0; n < 6; ++n) {
1761 b[i + n] = node[n];
1762 }
1763
1764 return buf ? buf : bytesToUuid(b);
1765}
1766
1767module.exports = v1;
1768
1769},{"8":8,"9":9}],11:[function(_dereq_,module,exports){
1770var rng = _dereq_(9);
1771var bytesToUuid = _dereq_(8);
1772
1773function v4(options, buf, offset) {
1774 var i = buf && offset || 0;
1775
1776 if (typeof(options) == 'string') {
1777 buf = options === 'binary' ? new Array(16) : null;
1778 options = null;
1779 }
1780 options = options || {};
1781
1782 var rnds = options.random || (options.rng || rng)();
1783
1784 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1785 rnds[6] = (rnds[6] & 0x0f) | 0x40;
1786 rnds[8] = (rnds[8] & 0x3f) | 0x80;
1787
1788 // Copy bytes to buffer, if provided
1789 if (buf) {
1790 for (var ii = 0; ii < 16; ++ii) {
1791 buf[i + ii] = rnds[ii];
1792 }
1793 }
1794
1795 return buf || bytesToUuid(rnds);
1796}
1797
1798module.exports = v4;
1799
1800},{"8":8,"9":9}],12:[function(_dereq_,module,exports){
1801'use strict';
1802
1803/**
1804 * Stringify/parse functions that don't operate
1805 * recursively, so they avoid call stack exceeded
1806 * errors.
1807 */
1808exports.stringify = function stringify(input) {
1809 var queue = [];
1810 queue.push({obj: input});
1811
1812 var res = '';
1813 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
1814 while ((next = queue.pop())) {
1815 obj = next.obj;
1816 prefix = next.prefix || '';
1817 val = next.val || '';
1818 res += prefix;
1819 if (val) {
1820 res += val;
1821 } else if (typeof obj !== 'object') {
1822 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
1823 } else if (obj === null) {
1824 res += 'null';
1825 } else if (Array.isArray(obj)) {
1826 queue.push({val: ']'});
1827 for (i = obj.length - 1; i >= 0; i--) {
1828 arrayPrefix = i === 0 ? '' : ',';
1829 queue.push({obj: obj[i], prefix: arrayPrefix});
1830 }
1831 queue.push({val: '['});
1832 } else { // object
1833 keys = [];
1834 for (k in obj) {
1835 if (obj.hasOwnProperty(k)) {
1836 keys.push(k);
1837 }
1838 }
1839 queue.push({val: '}'});
1840 for (i = keys.length - 1; i >= 0; i--) {
1841 key = keys[i];
1842 value = obj[key];
1843 objPrefix = (i > 0 ? ',' : '');
1844 objPrefix += JSON.stringify(key) + ':';
1845 queue.push({obj: value, prefix: objPrefix});
1846 }
1847 queue.push({val: '{'});
1848 }
1849 }
1850 return res;
1851};
1852
1853// Convenience function for the parse function.
1854// This pop function is basically copied from
1855// pouchCollate.parseIndexableString
1856function pop(obj, stack, metaStack) {
1857 var lastMetaElement = metaStack[metaStack.length - 1];
1858 if (obj === lastMetaElement.element) {
1859 // popping a meta-element, e.g. an object whose value is another object
1860 metaStack.pop();
1861 lastMetaElement = metaStack[metaStack.length - 1];
1862 }
1863 var element = lastMetaElement.element;
1864 var lastElementIndex = lastMetaElement.index;
1865 if (Array.isArray(element)) {
1866 element.push(obj);
1867 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
1868 var key = stack.pop();
1869 element[key] = obj;
1870 } else {
1871 stack.push(obj); // obj with key only
1872 }
1873}
1874
1875exports.parse = function (str) {
1876 var stack = [];
1877 var metaStack = []; // stack for arrays and objects
1878 var i = 0;
1879 var collationIndex,parsedNum,numChar;
1880 var parsedString,lastCh,numConsecutiveSlashes,ch;
1881 var arrayElement, objElement;
1882 while (true) {
1883 collationIndex = str[i++];
1884 if (collationIndex === '}' ||
1885 collationIndex === ']' ||
1886 typeof collationIndex === 'undefined') {
1887 if (stack.length === 1) {
1888 return stack.pop();
1889 } else {
1890 pop(stack.pop(), stack, metaStack);
1891 continue;
1892 }
1893 }
1894 switch (collationIndex) {
1895 case ' ':
1896 case '\t':
1897 case '\n':
1898 case ':':
1899 case ',':
1900 break;
1901 case 'n':
1902 i += 3; // 'ull'
1903 pop(null, stack, metaStack);
1904 break;
1905 case 't':
1906 i += 3; // 'rue'
1907 pop(true, stack, metaStack);
1908 break;
1909 case 'f':
1910 i += 4; // 'alse'
1911 pop(false, stack, metaStack);
1912 break;
1913 case '0':
1914 case '1':
1915 case '2':
1916 case '3':
1917 case '4':
1918 case '5':
1919 case '6':
1920 case '7':
1921 case '8':
1922 case '9':
1923 case '-':
1924 parsedNum = '';
1925 i--;
1926 while (true) {
1927 numChar = str[i++];
1928 if (/[\d\.\-e\+]/.test(numChar)) {
1929 parsedNum += numChar;
1930 } else {
1931 i--;
1932 break;
1933 }
1934 }
1935 pop(parseFloat(parsedNum), stack, metaStack);
1936 break;
1937 case '"':
1938 parsedString = '';
1939 lastCh = void 0;
1940 numConsecutiveSlashes = 0;
1941 while (true) {
1942 ch = str[i++];
1943 if (ch !== '"' || (lastCh === '\\' &&
1944 numConsecutiveSlashes % 2 === 1)) {
1945 parsedString += ch;
1946 lastCh = ch;
1947 if (lastCh === '\\') {
1948 numConsecutiveSlashes++;
1949 } else {
1950 numConsecutiveSlashes = 0;
1951 }
1952 } else {
1953 break;
1954 }
1955 }
1956 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
1957 break;
1958 case '[':
1959 arrayElement = { element: [], index: stack.length };
1960 stack.push(arrayElement.element);
1961 metaStack.push(arrayElement);
1962 break;
1963 case '{':
1964 objElement = { element: {}, index: stack.length };
1965 stack.push(objElement.element);
1966 metaStack.push(objElement);
1967 break;
1968 default:
1969 throw new Error(
1970 'unexpectedly reached end of input: ' + collationIndex);
1971 }
1972 }
1973};
1974
1975},{}],13:[function(_dereq_,module,exports){
1976(function (process,global){
1977'use strict';
1978
1979function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
1980
1981var getArguments = _interopDefault(_dereq_(1));
1982var nextTick = _interopDefault(_dereq_(3));
1983var events = _dereq_(2);
1984var inherits = _interopDefault(_dereq_(4));
1985var Md5 = _interopDefault(_dereq_(6));
1986var uuidV4 = _interopDefault(_dereq_(7));
1987var vuvuzela = _interopDefault(_dereq_(12));
1988
1989function isBinaryObject(object) {
1990 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
1991 (typeof Blob !== 'undefined' && object instanceof Blob);
1992}
1993
1994function cloneArrayBuffer(buff) {
1995 if (typeof buff.slice === 'function') {
1996 return buff.slice(0);
1997 }
1998 // IE10-11 slice() polyfill
1999 var target = new ArrayBuffer(buff.byteLength);
2000 var targetArray = new Uint8Array(target);
2001 var sourceArray = new Uint8Array(buff);
2002 targetArray.set(sourceArray);
2003 return target;
2004}
2005
2006function cloneBinaryObject(object) {
2007 if (object instanceof ArrayBuffer) {
2008 return cloneArrayBuffer(object);
2009 }
2010 var size = object.size;
2011 var type = object.type;
2012 // Blob
2013 if (typeof object.slice === 'function') {
2014 return object.slice(0, size, type);
2015 }
2016 // PhantomJS slice() replacement
2017 return object.webkitSlice(0, size, type);
2018}
2019
2020// most of this is borrowed from lodash.isPlainObject:
2021// https://github.com/fis-components/lodash.isplainobject/
2022// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
2023
2024var funcToString = Function.prototype.toString;
2025var objectCtorString = funcToString.call(Object);
2026
2027function isPlainObject(value) {
2028 var proto = Object.getPrototypeOf(value);
2029 /* istanbul ignore if */
2030 if (proto === null) { // not sure when this happens, but I guess it can
2031 return true;
2032 }
2033 var Ctor = proto.constructor;
2034 return (typeof Ctor == 'function' &&
2035 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
2036}
2037
2038function clone(object) {
2039 var newObject;
2040 var i;
2041 var len;
2042
2043 if (!object || typeof object !== 'object') {
2044 return object;
2045 }
2046
2047 if (Array.isArray(object)) {
2048 newObject = [];
2049 for (i = 0, len = object.length; i < len; i++) {
2050 newObject[i] = clone(object[i]);
2051 }
2052 return newObject;
2053 }
2054
2055 // special case: to avoid inconsistencies between IndexedDB
2056 // and other backends, we automatically stringify Dates
2057 if (object instanceof Date) {
2058 return object.toISOString();
2059 }
2060
2061 if (isBinaryObject(object)) {
2062 return cloneBinaryObject(object);
2063 }
2064
2065 if (!isPlainObject(object)) {
2066 return object; // don't clone objects like Workers
2067 }
2068
2069 newObject = {};
2070 for (i in object) {
2071 /* istanbul ignore else */
2072 if (Object.prototype.hasOwnProperty.call(object, i)) {
2073 var value = clone(object[i]);
2074 if (typeof value !== 'undefined') {
2075 newObject[i] = value;
2076 }
2077 }
2078 }
2079 return newObject;
2080}
2081
2082function once(fun) {
2083 var called = false;
2084 return getArguments(function (args) {
2085 /* istanbul ignore if */
2086 if (called) {
2087 // this is a smoke test and should never actually happen
2088 throw new Error('once called more than once');
2089 } else {
2090 called = true;
2091 fun.apply(this, args);
2092 }
2093 });
2094}
2095
2096function toPromise(func) {
2097 //create the function we will be returning
2098 return getArguments(function (args) {
2099 // Clone arguments
2100 args = clone(args);
2101 var self = this;
2102 // if the last argument is a function, assume its a callback
2103 var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
2104 var promise = new Promise(function (fulfill, reject) {
2105 var resp;
2106 try {
2107 var callback = once(function (err, mesg) {
2108 if (err) {
2109 reject(err);
2110 } else {
2111 fulfill(mesg);
2112 }
2113 });
2114 // create a callback for this invocation
2115 // apply the function in the orig context
2116 args.push(callback);
2117 resp = func.apply(self, args);
2118 if (resp && typeof resp.then === 'function') {
2119 fulfill(resp);
2120 }
2121 } catch (e) {
2122 reject(e);
2123 }
2124 });
2125 // if there is a callback, call it back
2126 if (usedCB) {
2127 promise.then(function (result) {
2128 usedCB(null, result);
2129 }, usedCB);
2130 }
2131 return promise;
2132 });
2133}
2134
2135function logApiCall(self, name, args) {
2136 /* istanbul ignore if */
2137 if (self.constructor.listeners('debug').length) {
2138 var logArgs = ['api', self.name, name];
2139 for (var i = 0; i < args.length - 1; i++) {
2140 logArgs.push(args[i]);
2141 }
2142 self.constructor.emit('debug', logArgs);
2143
2144 // override the callback itself to log the response
2145 var origCallback = args[args.length - 1];
2146 args[args.length - 1] = function (err, res) {
2147 var responseArgs = ['api', self.name, name];
2148 responseArgs = responseArgs.concat(
2149 err ? ['error', err] : ['success', res]
2150 );
2151 self.constructor.emit('debug', responseArgs);
2152 origCallback(err, res);
2153 };
2154 }
2155}
2156
2157function adapterFun(name, callback) {
2158 return toPromise(getArguments(function (args) {
2159 if (this._closed) {
2160 return Promise.reject(new Error('database is closed'));
2161 }
2162 if (this._destroyed) {
2163 return Promise.reject(new Error('database is destroyed'));
2164 }
2165 var self = this;
2166 logApiCall(self, name, args);
2167 if (!this.taskqueue.isReady) {
2168 return new Promise(function (fulfill, reject) {
2169 self.taskqueue.addTask(function (failed) {
2170 if (failed) {
2171 reject(failed);
2172 } else {
2173 fulfill(self[name].apply(self, args));
2174 }
2175 });
2176 });
2177 }
2178 return callback.apply(this, args);
2179 }));
2180}
2181
2182function mangle(key) {
2183 return '$' + key;
2184}
2185function unmangle(key) {
2186 return key.substring(1);
2187}
2188function Map$1() {
2189 this._store = {};
2190}
2191Map$1.prototype.get = function (key) {
2192 var mangled = mangle(key);
2193 return this._store[mangled];
2194};
2195Map$1.prototype.set = function (key, value) {
2196 var mangled = mangle(key);
2197 this._store[mangled] = value;
2198 return true;
2199};
2200Map$1.prototype.has = function (key) {
2201 var mangled = mangle(key);
2202 return mangled in this._store;
2203};
2204Map$1.prototype["delete"] = function (key) {
2205 var mangled = mangle(key);
2206 var res = mangled in this._store;
2207 delete this._store[mangled];
2208 return res;
2209};
2210Map$1.prototype.forEach = function (cb) {
2211 var keys = Object.keys(this._store);
2212 for (var i = 0, len = keys.length; i < len; i++) {
2213 var key = keys[i];
2214 var value = this._store[key];
2215 key = unmangle(key);
2216 cb(value, key);
2217 }
2218};
2219Object.defineProperty(Map$1.prototype, 'size', {
2220 get: function () {
2221 return Object.keys(this._store).length;
2222 }
2223});
2224
2225function Set$1(array) {
2226 this._store = new Map$1();
2227
2228 // init with an array
2229 if (array && Array.isArray(array)) {
2230 for (var i = 0, len = array.length; i < len; i++) {
2231 this.add(array[i]);
2232 }
2233 }
2234}
2235Set$1.prototype.add = function (key) {
2236 return this._store.set(key, true);
2237};
2238Set$1.prototype.has = function (key) {
2239 return this._store.has(key);
2240};
2241Set$1.prototype.forEach = function (cb) {
2242 this._store.forEach(function (value, key) {
2243 cb(key);
2244 });
2245};
2246Object.defineProperty(Set$1.prototype, 'size', {
2247 get: function () {
2248 return this._store.size;
2249 }
2250});
2251
2252/* global Map,Set,Symbol */
2253// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
2254// incomplete Map/Set implementations which would otherwise cause our tests to fail.
2255// Notably they fail in IE11 and iOS 8.4, which this prevents.
2256function supportsMapAndSet() {
2257 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
2258 return false;
2259 }
2260 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
2261 return prop && 'get' in prop && Map[Symbol.species] === Map;
2262}
2263
2264// based on https://github.com/montagejs/collections
2265
2266var ExportedSet;
2267var ExportedMap;
2268
2269{
2270 if (supportsMapAndSet()) { // prefer built-in Map/Set
2271 ExportedSet = Set;
2272 ExportedMap = Map;
2273 } else { // fall back to our polyfill
2274 ExportedSet = Set$1;
2275 ExportedMap = Map$1;
2276 }
2277}
2278
2279// like underscore/lodash _.pick()
2280function pick(obj, arr) {
2281 var res = {};
2282 for (var i = 0, len = arr.length; i < len; i++) {
2283 var prop = arr[i];
2284 if (prop in obj) {
2285 res[prop] = obj[prop];
2286 }
2287 }
2288 return res;
2289}
2290
2291// Most browsers throttle concurrent requests at 6, so it's silly
2292// to shim _bulk_get by trying to launch potentially hundreds of requests
2293// and then letting the majority time out. We can handle this ourselves.
2294var MAX_NUM_CONCURRENT_REQUESTS = 6;
2295
2296function identityFunction(x) {
2297 return x;
2298}
2299
2300function formatResultForOpenRevsGet(result) {
2301 return [{
2302 ok: result
2303 }];
2304}
2305
2306// shim for P/CouchDB adapters that don't directly implement _bulk_get
2307function bulkGet(db, opts, callback) {
2308 var requests = opts.docs;
2309
2310 // consolidate into one request per doc if possible
2311 var requestsById = new ExportedMap();
2312 requests.forEach(function (request) {
2313 if (requestsById.has(request.id)) {
2314 requestsById.get(request.id).push(request);
2315 } else {
2316 requestsById.set(request.id, [request]);
2317 }
2318 });
2319
2320 var numDocs = requestsById.size;
2321 var numDone = 0;
2322 var perDocResults = new Array(numDocs);
2323
2324 function collapseResultsAndFinish() {
2325 var results = [];
2326 perDocResults.forEach(function (res) {
2327 res.docs.forEach(function (info) {
2328 results.push({
2329 id: res.id,
2330 docs: [info]
2331 });
2332 });
2333 });
2334 callback(null, {results: results});
2335 }
2336
2337 function checkDone() {
2338 if (++numDone === numDocs) {
2339 collapseResultsAndFinish();
2340 }
2341 }
2342
2343 function gotResult(docIndex, id, docs) {
2344 perDocResults[docIndex] = {id: id, docs: docs};
2345 checkDone();
2346 }
2347
2348 var allRequests = [];
2349 requestsById.forEach(function (value, key) {
2350 allRequests.push(key);
2351 });
2352
2353 var i = 0;
2354
2355 function nextBatch() {
2356
2357 if (i >= allRequests.length) {
2358 return;
2359 }
2360
2361 var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
2362 var batch = allRequests.slice(i, upTo);
2363 processBatch(batch, i);
2364 i += batch.length;
2365 }
2366
2367 function processBatch(batch, offset) {
2368 batch.forEach(function (docId, j) {
2369 var docIdx = offset + j;
2370 var docRequests = requestsById.get(docId);
2371
2372 // just use the first request as the "template"
2373 // TODO: The _bulk_get API allows for more subtle use cases than this,
2374 // but for now it is unlikely that there will be a mix of different
2375 // "atts_since" or "attachments" in the same request, since it's just
2376 // replicate.js that is using this for the moment.
2377 // Also, atts_since is aspirational, since we don't support it yet.
2378 var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
2379 docOpts.open_revs = docRequests.map(function (request) {
2380 // rev is optional, open_revs disallowed
2381 return request.rev;
2382 });
2383
2384 // remove falsey / undefined revisions
2385 docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
2386
2387 var formatResult = identityFunction;
2388
2389 if (docOpts.open_revs.length === 0) {
2390 delete docOpts.open_revs;
2391
2392 // when fetching only the "winning" leaf,
2393 // transform the result so it looks like an open_revs
2394 // request
2395 formatResult = formatResultForOpenRevsGet;
2396 }
2397
2398 // globally-supplied options
2399 ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {
2400 if (param in opts) {
2401 docOpts[param] = opts[param];
2402 }
2403 });
2404 db.get(docId, docOpts, function (err, res) {
2405 var result;
2406 /* istanbul ignore if */
2407 if (err) {
2408 result = [{error: err}];
2409 } else {
2410 result = formatResult(res);
2411 }
2412 gotResult(docIdx, docId, result);
2413 nextBatch();
2414 });
2415 });
2416 }
2417
2418 nextBatch();
2419
2420}
2421
2422var hasLocal;
2423
2424try {
2425 localStorage.setItem('_pouch_check_localstorage', 1);
2426 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
2427} catch (e) {
2428 hasLocal = false;
2429}
2430
2431function hasLocalStorage() {
2432 return hasLocal;
2433}
2434
2435// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
2436
2437inherits(Changes, events.EventEmitter);
2438
2439/* istanbul ignore next */
2440function attachBrowserEvents(self) {
2441 if (hasLocalStorage()) {
2442 addEventListener("storage", function (e) {
2443 self.emit(e.key);
2444 });
2445 }
2446}
2447
2448function Changes() {
2449 events.EventEmitter.call(this);
2450 this._listeners = {};
2451
2452 attachBrowserEvents(this);
2453}
2454Changes.prototype.addListener = function (dbName, id, db, opts) {
2455 /* istanbul ignore if */
2456 if (this._listeners[id]) {
2457 return;
2458 }
2459 var self = this;
2460 var inprogress = false;
2461 function eventFunction() {
2462 /* istanbul ignore if */
2463 if (!self._listeners[id]) {
2464 return;
2465 }
2466 if (inprogress) {
2467 inprogress = 'waiting';
2468 return;
2469 }
2470 inprogress = true;
2471 var changesOpts = pick(opts, [
2472 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
2473 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
2474 ]);
2475
2476 /* istanbul ignore next */
2477 function onError() {
2478 inprogress = false;
2479 }
2480
2481 db.changes(changesOpts).on('change', function (c) {
2482 if (c.seq > opts.since && !opts.cancelled) {
2483 opts.since = c.seq;
2484 opts.onChange(c);
2485 }
2486 }).on('complete', function () {
2487 if (inprogress === 'waiting') {
2488 nextTick(eventFunction);
2489 }
2490 inprogress = false;
2491 }).on('error', onError);
2492 }
2493 this._listeners[id] = eventFunction;
2494 this.on(dbName, eventFunction);
2495};
2496
2497Changes.prototype.removeListener = function (dbName, id) {
2498 /* istanbul ignore if */
2499 if (!(id in this._listeners)) {
2500 return;
2501 }
2502 events.EventEmitter.prototype.removeListener.call(this, dbName,
2503 this._listeners[id]);
2504 delete this._listeners[id];
2505};
2506
2507
2508/* istanbul ignore next */
2509Changes.prototype.notifyLocalWindows = function (dbName) {
2510 //do a useless change on a storage thing
2511 //in order to get other windows's listeners to activate
2512 if (hasLocalStorage()) {
2513 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
2514 }
2515};
2516
2517Changes.prototype.notify = function (dbName) {
2518 this.emit(dbName);
2519 this.notifyLocalWindows(dbName);
2520};
2521
2522function guardedConsole(method) {
2523 /* istanbul ignore else */
2524 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
2525 var args = Array.prototype.slice.call(arguments, 1);
2526 console[method].apply(console, args);
2527 }
2528}
2529
2530function randomNumber(min, max) {
2531 var maxTimeout = 600000; // Hard-coded default of 10 minutes
2532 min = parseInt(min, 10) || 0;
2533 max = parseInt(max, 10);
2534 if (max !== max || max <= min) {
2535 max = (min || 1) << 1; //doubling
2536 } else {
2537 max = max + 1;
2538 }
2539 // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout
2540 if (max > maxTimeout) {
2541 min = maxTimeout >> 1; // divide by two
2542 max = maxTimeout;
2543 }
2544 var ratio = Math.random();
2545 var range = max - min;
2546
2547 return ~~(range * ratio + min); // ~~ coerces to an int, but fast.
2548}
2549
2550function defaultBackOff(min) {
2551 var max = 0;
2552 if (!min) {
2553 max = 2000;
2554 }
2555 return randomNumber(min, max);
2556}
2557
2558// designed to give info to browser users, who are disturbed
2559// when they see http errors in the console
2560function explainError(status, str) {
2561 guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);
2562}
2563
2564var assign;
2565{
2566 if (typeof Object.assign === 'function') {
2567 assign = Object.assign;
2568 } else {
2569 // lite Object.assign polyfill based on
2570 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
2571 assign = function (target) {
2572 var to = Object(target);
2573
2574 for (var index = 1; index < arguments.length; index++) {
2575 var nextSource = arguments[index];
2576
2577 if (nextSource != null) { // Skip over if undefined or null
2578 for (var nextKey in nextSource) {
2579 // Avoid bugs when hasOwnProperty is shadowed
2580 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
2581 to[nextKey] = nextSource[nextKey];
2582 }
2583 }
2584 }
2585 }
2586 return to;
2587 };
2588 }
2589}
2590
2591var $inject_Object_assign = assign;
2592
2593inherits(PouchError, Error);
2594
2595function PouchError(status, error, reason) {
2596 Error.call(this, reason);
2597 this.status = status;
2598 this.name = error;
2599 this.message = reason;
2600 this.error = true;
2601}
2602
2603PouchError.prototype.toString = function () {
2604 return JSON.stringify({
2605 status: this.status,
2606 name: this.name,
2607 message: this.message,
2608 reason: this.reason
2609 });
2610};
2611
2612var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
2613var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
2614var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
2615var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
2616var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
2617var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
2618var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
2619var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
2620var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
2621var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
2622var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
2623var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
2624var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
2625var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
2626var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
2627var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
2628var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
2629var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
2630var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
2631var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
2632var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
2633var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
2634var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
2635var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
2636
2637function createError(error, reason) {
2638 function CustomPouchError(reason) {
2639 // inherit error properties from our parent error manually
2640 // so as to allow proper JSON parsing.
2641 /* jshint ignore:start */
2642 for (var p in error) {
2643 if (typeof error[p] !== 'function') {
2644 this[p] = error[p];
2645 }
2646 }
2647 /* jshint ignore:end */
2648 if (reason !== undefined) {
2649 this.reason = reason;
2650 }
2651 }
2652 CustomPouchError.prototype = PouchError.prototype;
2653 return new CustomPouchError(reason);
2654}
2655
2656function generateErrorFromResponse(err) {
2657
2658 if (typeof err !== 'object') {
2659 var data = err;
2660 err = UNKNOWN_ERROR;
2661 err.data = data;
2662 }
2663
2664 if ('error' in err && err.error === 'conflict') {
2665 err.name = 'conflict';
2666 err.status = 409;
2667 }
2668
2669 if (!('name' in err)) {
2670 err.name = err.error || 'unknown';
2671 }
2672
2673 if (!('status' in err)) {
2674 err.status = 500;
2675 }
2676
2677 if (!('message' in err)) {
2678 err.message = err.message || err.reason;
2679 }
2680
2681 return err;
2682}
2683
2684function tryFilter(filter, doc, req) {
2685 try {
2686 return !filter(doc, req);
2687 } catch (err) {
2688 var msg = 'Filter function threw: ' + err.toString();
2689 return createError(BAD_REQUEST, msg);
2690 }
2691}
2692
2693function filterChange(opts) {
2694 var req = {};
2695 var hasFilter = opts.filter && typeof opts.filter === 'function';
2696 req.query = opts.query_params;
2697
2698 return function filter(change) {
2699 if (!change.doc) {
2700 // CSG sends events on the changes feed that don't have documents,
2701 // this hack makes a whole lot of existing code robust.
2702 change.doc = {};
2703 }
2704
2705 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
2706
2707 if (typeof filterReturn === 'object') {
2708 return filterReturn;
2709 }
2710
2711 if (filterReturn) {
2712 return false;
2713 }
2714
2715 if (!opts.include_docs) {
2716 delete change.doc;
2717 } else if (!opts.attachments) {
2718 for (var att in change.doc._attachments) {
2719 /* istanbul ignore else */
2720 if (change.doc._attachments.hasOwnProperty(att)) {
2721 change.doc._attachments[att].stub = true;
2722 }
2723 }
2724 }
2725 return true;
2726 };
2727}
2728
2729function flatten(arrs) {
2730 var res = [];
2731 for (var i = 0, len = arrs.length; i < len; i++) {
2732 res = res.concat(arrs[i]);
2733 }
2734 return res;
2735}
2736
2737// shim for Function.prototype.name,
2738
2739// Determine id an ID is valid
2740// - invalid IDs begin with an underescore that does not begin '_design' or
2741// '_local'
2742// - any other string value is a valid id
2743// Returns the specific error object for each case
2744function invalidIdError(id) {
2745 var err;
2746 if (!id) {
2747 err = createError(MISSING_ID);
2748 } else if (typeof id !== 'string') {
2749 err = createError(INVALID_ID);
2750 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
2751 err = createError(RESERVED_ID);
2752 }
2753 if (err) {
2754 throw err;
2755 }
2756}
2757
2758// Checks if a PouchDB object is "remote" or not. This is
2759
2760function isRemote(db) {
2761 if (typeof db._remote === 'boolean') {
2762 return db._remote;
2763 }
2764 /* istanbul ignore next */
2765 if (typeof db.type === 'function') {
2766 guardedConsole('warn',
2767 'db.type() is deprecated and will be removed in ' +
2768 'a future version of PouchDB');
2769 return db.type() === 'http';
2770 }
2771 /* istanbul ignore next */
2772 return false;
2773}
2774
2775function listenerCount(ee, type) {
2776 return 'listenerCount' in ee ? ee.listenerCount(type) :
2777 events.EventEmitter.listenerCount(ee, type);
2778}
2779
2780function parseDesignDocFunctionName(s) {
2781 if (!s) {
2782 return null;
2783 }
2784 var parts = s.split('/');
2785 if (parts.length === 2) {
2786 return parts;
2787 }
2788 if (parts.length === 1) {
2789 return [s, s];
2790 }
2791 return null;
2792}
2793
2794function normalizeDesignDocFunctionName(s) {
2795 var normalized = parseDesignDocFunctionName(s);
2796 return normalized ? normalized.join('/') : null;
2797}
2798
2799// originally parseUri 1.2.2, now patched by us
2800// (c) Steven Levithan <stevenlevithan.com>
2801// MIT License
2802var keys = ["source", "protocol", "authority", "userInfo", "user", "password",
2803 "host", "port", "relative", "path", "directory", "file", "query", "anchor"];
2804var qName ="queryKey";
2805var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g;
2806
2807// use the "loose" parser
2808/* eslint maxlen: 0, no-useless-escape: 0 */
2809var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
2810
2811function parseUri(str) {
2812 var m = parser.exec(str);
2813 var uri = {};
2814 var i = 14;
2815
2816 while (i--) {
2817 var key = keys[i];
2818 var value = m[i] || "";
2819 var encoded = ['user', 'password'].indexOf(key) !== -1;
2820 uri[key] = encoded ? decodeURIComponent(value) : value;
2821 }
2822
2823 uri[qName] = {};
2824 uri[keys[12]].replace(qParser, function ($0, $1, $2) {
2825 if ($1) {
2826 uri[qName][$1] = $2;
2827 }
2828 });
2829
2830 return uri;
2831}
2832
2833// Based on https://github.com/alexdavid/scope-eval v0.0.3
2834// (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js)
2835// This is basically just a wrapper around new Function()
2836
2837function scopeEval(source, scope) {
2838 var keys = [];
2839 var values = [];
2840 for (var key in scope) {
2841 if (scope.hasOwnProperty(key)) {
2842 keys.push(key);
2843 values.push(scope[key]);
2844 }
2845 }
2846 keys.push(source);
2847 return Function.apply(null, keys).apply(null, values);
2848}
2849
2850// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
2851// the diffFun tells us what delta to apply to the doc. it either returns
2852// the doc, or false if it doesn't need to do an update after all
2853function upsert(db, docId, diffFun) {
2854 return new Promise(function (fulfill, reject) {
2855 db.get(docId, function (err, doc) {
2856 if (err) {
2857 /* istanbul ignore next */
2858 if (err.status !== 404) {
2859 return reject(err);
2860 }
2861 doc = {};
2862 }
2863
2864 // the user might change the _rev, so save it for posterity
2865 var docRev = doc._rev;
2866 var newDoc = diffFun(doc);
2867
2868 if (!newDoc) {
2869 // if the diffFun returns falsy, we short-circuit as
2870 // an optimization
2871 return fulfill({updated: false, rev: docRev});
2872 }
2873
2874 // users aren't allowed to modify these values,
2875 // so reset them here
2876 newDoc._id = docId;
2877 newDoc._rev = docRev;
2878 fulfill(tryAndPut(db, newDoc, diffFun));
2879 });
2880 });
2881}
2882
2883function tryAndPut(db, doc, diffFun) {
2884 return db.put(doc).then(function (res) {
2885 return {
2886 updated: true,
2887 rev: res.rev
2888 };
2889 }, function (err) {
2890 /* istanbul ignore next */
2891 if (err.status !== 409) {
2892 throw err;
2893 }
2894 return upsert(db, doc._id, diffFun);
2895 });
2896}
2897
2898var thisAtob = function (str) {
2899 return atob(str);
2900};
2901
2902var thisBtoa = function (str) {
2903 return btoa(str);
2904};
2905
2906// Abstracts constructing a Blob object, so it also works in older
2907// browsers that don't support the native Blob constructor (e.g.
2908// old QtWebKit versions, Android < 4.4).
2909function createBlob(parts, properties) {
2910 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
2911 parts = parts || [];
2912 properties = properties || {};
2913 try {
2914 return new Blob(parts, properties);
2915 } catch (e) {
2916 if (e.name !== "TypeError") {
2917 throw e;
2918 }
2919 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
2920 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
2921 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
2922 WebKitBlobBuilder;
2923 var builder = new Builder();
2924 for (var i = 0; i < parts.length; i += 1) {
2925 builder.append(parts[i]);
2926 }
2927 return builder.getBlob(properties.type);
2928 }
2929}
2930
2931// From http://stackoverflow.com/questions/14967647/ (continues on next line)
2932// encode-decode-image-with-base64-breaks-image (2013-04-21)
2933function binaryStringToArrayBuffer(bin) {
2934 var length = bin.length;
2935 var buf = new ArrayBuffer(length);
2936 var arr = new Uint8Array(buf);
2937 for (var i = 0; i < length; i++) {
2938 arr[i] = bin.charCodeAt(i);
2939 }
2940 return buf;
2941}
2942
2943function binStringToBluffer(binString, type) {
2944 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
2945}
2946
2947function b64ToBluffer(b64, type) {
2948 return binStringToBluffer(thisAtob(b64), type);
2949}
2950
2951//Can't find original post, but this is close
2952//http://stackoverflow.com/questions/6965107/ (continues on next line)
2953//converting-between-strings-and-arraybuffers
2954function arrayBufferToBinaryString(buffer) {
2955 var binary = '';
2956 var bytes = new Uint8Array(buffer);
2957 var length = bytes.byteLength;
2958 for (var i = 0; i < length; i++) {
2959 binary += String.fromCharCode(bytes[i]);
2960 }
2961 return binary;
2962}
2963
2964// shim for browsers that don't support it
2965function readAsBinaryString(blob, callback) {
2966 var reader = new FileReader();
2967 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
2968 reader.onloadend = function (e) {
2969 var result = e.target.result || '';
2970 if (hasBinaryString) {
2971 return callback(result);
2972 }
2973 callback(arrayBufferToBinaryString(result));
2974 };
2975 if (hasBinaryString) {
2976 reader.readAsBinaryString(blob);
2977 } else {
2978 reader.readAsArrayBuffer(blob);
2979 }
2980}
2981
2982function blobToBinaryString(blobOrBuffer, callback) {
2983 readAsBinaryString(blobOrBuffer, function (bin) {
2984 callback(bin);
2985 });
2986}
2987
2988function blobToBase64(blobOrBuffer, callback) {
2989 blobToBinaryString(blobOrBuffer, function (base64) {
2990 callback(thisBtoa(base64));
2991 });
2992}
2993
2994// simplified API. universal browser support is assumed
2995function readAsArrayBuffer(blob, callback) {
2996 var reader = new FileReader();
2997 reader.onloadend = function (e) {
2998 var result = e.target.result || new ArrayBuffer(0);
2999 callback(result);
3000 };
3001 reader.readAsArrayBuffer(blob);
3002}
3003
3004// this is not used in the browser
3005
3006var setImmediateShim = global.setImmediate || global.setTimeout;
3007var MD5_CHUNK_SIZE = 32768;
3008
3009function rawToBase64(raw) {
3010 return thisBtoa(raw);
3011}
3012
3013function sliceBlob(blob, start, end) {
3014 if (blob.webkitSlice) {
3015 return blob.webkitSlice(start, end);
3016 }
3017 return blob.slice(start, end);
3018}
3019
3020function appendBlob(buffer, blob, start, end, callback) {
3021 if (start > 0 || end < blob.size) {
3022 // only slice blob if we really need to
3023 blob = sliceBlob(blob, start, end);
3024 }
3025 readAsArrayBuffer(blob, function (arrayBuffer) {
3026 buffer.append(arrayBuffer);
3027 callback();
3028 });
3029}
3030
3031function appendString(buffer, string, start, end, callback) {
3032 if (start > 0 || end < string.length) {
3033 // only create a substring if we really need to
3034 string = string.substring(start, end);
3035 }
3036 buffer.appendBinary(string);
3037 callback();
3038}
3039
3040function binaryMd5(data, callback) {
3041 var inputIsString = typeof data === 'string';
3042 var len = inputIsString ? data.length : data.size;
3043 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
3044 var chunks = Math.ceil(len / chunkSize);
3045 var currentChunk = 0;
3046 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
3047
3048 var append = inputIsString ? appendString : appendBlob;
3049
3050 function next() {
3051 setImmediateShim(loadNextChunk);
3052 }
3053
3054 function done() {
3055 var raw = buffer.end(true);
3056 var base64 = rawToBase64(raw);
3057 callback(base64);
3058 buffer.destroy();
3059 }
3060
3061 function loadNextChunk() {
3062 var start = currentChunk * chunkSize;
3063 var end = start + chunkSize;
3064 currentChunk++;
3065 if (currentChunk < chunks) {
3066 append(buffer, data, start, end, next);
3067 } else {
3068 append(buffer, data, start, end, done);
3069 }
3070 }
3071 loadNextChunk();
3072}
3073
3074function stringMd5(string) {
3075 return Md5.hash(string);
3076}
3077
3078function rev$$1(doc, deterministic_revs) {
3079 var clonedDoc = clone(doc);
3080 if (!deterministic_revs) {
3081 return uuidV4.v4().replace(/-/g, '').toLowerCase();
3082 }
3083
3084 delete clonedDoc._rev_tree;
3085 return stringMd5(JSON.stringify(clonedDoc));
3086}
3087
3088var uuid = uuidV4.v4;
3089
3090// We fetch all leafs of the revision tree, and sort them based on tree length
3091// and whether they were deleted, undeleted documents with the longest revision
3092// tree (most edits) win
3093// The final sort algorithm is slightly documented in a sidebar here:
3094// http://guide.couchdb.org/draft/conflicts.html
3095function winningRev(metadata) {
3096 var winningId;
3097 var winningPos;
3098 var winningDeleted;
3099 var toVisit = metadata.rev_tree.slice();
3100 var node;
3101 while ((node = toVisit.pop())) {
3102 var tree = node.ids;
3103 var branches = tree[2];
3104 var pos = node.pos;
3105 if (branches.length) { // non-leaf
3106 for (var i = 0, len = branches.length; i < len; i++) {
3107 toVisit.push({pos: pos + 1, ids: branches[i]});
3108 }
3109 continue;
3110 }
3111 var deleted = !!tree[1].deleted;
3112 var id = tree[0];
3113 // sort by deleted, then pos, then id
3114 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
3115 winningPos !== pos ? winningPos < pos : winningId < id)) {
3116 winningId = id;
3117 winningPos = pos;
3118 winningDeleted = deleted;
3119 }
3120 }
3121
3122 return winningPos + '-' + winningId;
3123}
3124
3125// Pretty much all below can be combined into a higher order function to
3126// traverse revisions
3127// The return value from the callback will be passed as context to all
3128// children of that node
3129function traverseRevTree(revs, callback) {
3130 var toVisit = revs.slice();
3131
3132 var node;
3133 while ((node = toVisit.pop())) {
3134 var pos = node.pos;
3135 var tree = node.ids;
3136 var branches = tree[2];
3137 var newCtx =
3138 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
3139 for (var i = 0, len = branches.length; i < len; i++) {
3140 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
3141 }
3142 }
3143}
3144
3145function sortByPos(a, b) {
3146 return a.pos - b.pos;
3147}
3148
3149function collectLeaves(revs) {
3150 var leaves = [];
3151 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
3152 if (isLeaf) {
3153 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
3154 }
3155 });
3156 leaves.sort(sortByPos).reverse();
3157 for (var i = 0, len = leaves.length; i < len; i++) {
3158 delete leaves[i].pos;
3159 }
3160 return leaves;
3161}
3162
3163// returns revs of all conflicts that is leaves such that
3164// 1. are not deleted and
3165// 2. are different than winning revision
3166function collectConflicts(metadata) {
3167 var win = winningRev(metadata);
3168 var leaves = collectLeaves(metadata.rev_tree);
3169 var conflicts = [];
3170 for (var i = 0, len = leaves.length; i < len; i++) {
3171 var leaf = leaves[i];
3172 if (leaf.rev !== win && !leaf.opts.deleted) {
3173 conflicts.push(leaf.rev);
3174 }
3175 }
3176 return conflicts;
3177}
3178
3179// compact a tree by marking its non-leafs as missing,
3180// and return a list of revs to delete
3181function compactTree(metadata) {
3182 var revs = [];
3183 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
3184 revHash, ctx, opts) {
3185 if (opts.status === 'available' && !isLeaf) {
3186 revs.push(pos + '-' + revHash);
3187 opts.status = 'missing';
3188 }
3189 });
3190 return revs;
3191}
3192
3193// build up a list of all the paths to the leafs in this revision tree
3194function rootToLeaf(revs) {
3195 var paths = [];
3196 var toVisit = revs.slice();
3197 var node;
3198 while ((node = toVisit.pop())) {
3199 var pos = node.pos;
3200 var tree = node.ids;
3201 var id = tree[0];
3202 var opts = tree[1];
3203 var branches = tree[2];
3204 var isLeaf = branches.length === 0;
3205
3206 var history = node.history ? node.history.slice() : [];
3207 history.push({id: id, opts: opts});
3208 if (isLeaf) {
3209 paths.push({pos: (pos + 1 - history.length), ids: history});
3210 }
3211 for (var i = 0, len = branches.length; i < len; i++) {
3212 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
3213 }
3214 }
3215 return paths.reverse();
3216}
3217
3218// for a better overview of what this is doing, read:
3219
3220function sortByPos$1(a, b) {
3221 return a.pos - b.pos;
3222}
3223
3224// classic binary search
3225function binarySearch(arr, item, comparator) {
3226 var low = 0;
3227 var high = arr.length;
3228 var mid;
3229 while (low < high) {
3230 mid = (low + high) >>> 1;
3231 if (comparator(arr[mid], item) < 0) {
3232 low = mid + 1;
3233 } else {
3234 high = mid;
3235 }
3236 }
3237 return low;
3238}
3239
3240// assuming the arr is sorted, insert the item in the proper place
3241function insertSorted(arr, item, comparator) {
3242 var idx = binarySearch(arr, item, comparator);
3243 arr.splice(idx, 0, item);
3244}
3245
3246// Turn a path as a flat array into a tree with a single branch.
3247// If any should be stemmed from the beginning of the array, that's passed
3248// in as the second argument
3249function pathToTree(path, numStemmed) {
3250 var root;
3251 var leaf;
3252 for (var i = numStemmed, len = path.length; i < len; i++) {
3253 var node = path[i];
3254 var currentLeaf = [node.id, node.opts, []];
3255 if (leaf) {
3256 leaf[2].push(currentLeaf);
3257 leaf = currentLeaf;
3258 } else {
3259 root = leaf = currentLeaf;
3260 }
3261 }
3262 return root;
3263}
3264
3265// compare the IDs of two trees
3266function compareTree(a, b) {
3267 return a[0] < b[0] ? -1 : 1;
3268}
3269
3270// Merge two trees together
3271// The roots of tree1 and tree2 must be the same revision
3272function mergeTree(in_tree1, in_tree2) {
3273 var queue = [{tree1: in_tree1, tree2: in_tree2}];
3274 var conflicts = false;
3275 while (queue.length > 0) {
3276 var item = queue.pop();
3277 var tree1 = item.tree1;
3278 var tree2 = item.tree2;
3279
3280 if (tree1[1].status || tree2[1].status) {
3281 tree1[1].status =
3282 (tree1[1].status === 'available' ||
3283 tree2[1].status === 'available') ? 'available' : 'missing';
3284 }
3285
3286 for (var i = 0; i < tree2[2].length; i++) {
3287 if (!tree1[2][0]) {
3288 conflicts = 'new_leaf';
3289 tree1[2][0] = tree2[2][i];
3290 continue;
3291 }
3292
3293 var merged = false;
3294 for (var j = 0; j < tree1[2].length; j++) {
3295 if (tree1[2][j][0] === tree2[2][i][0]) {
3296 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
3297 merged = true;
3298 }
3299 }
3300 if (!merged) {
3301 conflicts = 'new_branch';
3302 insertSorted(tree1[2], tree2[2][i], compareTree);
3303 }
3304 }
3305 }
3306 return {conflicts: conflicts, tree: in_tree1};
3307}
3308
3309function doMerge(tree, path, dontExpand) {
3310 var restree = [];
3311 var conflicts = false;
3312 var merged = false;
3313 var res;
3314
3315 if (!tree.length) {
3316 return {tree: [path], conflicts: 'new_leaf'};
3317 }
3318
3319 for (var i = 0, len = tree.length; i < len; i++) {
3320 var branch = tree[i];
3321 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
3322 // Paths start at the same position and have the same root, so they need
3323 // merged
3324 res = mergeTree(branch.ids, path.ids);
3325 restree.push({pos: branch.pos, ids: res.tree});
3326 conflicts = conflicts || res.conflicts;
3327 merged = true;
3328 } else if (dontExpand !== true) {
3329 // The paths start at a different position, take the earliest path and
3330 // traverse up until it as at the same point from root as the path we
3331 // want to merge. If the keys match we return the longer path with the
3332 // other merged After stemming we dont want to expand the trees
3333
3334 var t1 = branch.pos < path.pos ? branch : path;
3335 var t2 = branch.pos < path.pos ? path : branch;
3336 var diff = t2.pos - t1.pos;
3337
3338 var candidateParents = [];
3339
3340 var trees = [];
3341 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
3342 while (trees.length > 0) {
3343 var item = trees.pop();
3344 if (item.diff === 0) {
3345 if (item.ids[0] === t2.ids[0]) {
3346 candidateParents.push(item);
3347 }
3348 continue;
3349 }
3350 var elements = item.ids[2];
3351 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
3352 trees.push({
3353 ids: elements[j],
3354 diff: item.diff - 1,
3355 parent: item.ids,
3356 parentIdx: j
3357 });
3358 }
3359 }
3360
3361 var el = candidateParents[0];
3362
3363 if (!el) {
3364 restree.push(branch);
3365 } else {
3366 res = mergeTree(el.ids, t2.ids);
3367 el.parent[2][el.parentIdx] = res.tree;
3368 restree.push({pos: t1.pos, ids: t1.ids});
3369 conflicts = conflicts || res.conflicts;
3370 merged = true;
3371 }
3372 } else {
3373 restree.push(branch);
3374 }
3375 }
3376
3377 // We didnt find
3378 if (!merged) {
3379 restree.push(path);
3380 }
3381
3382 restree.sort(sortByPos$1);
3383
3384 return {
3385 tree: restree,
3386 conflicts: conflicts || 'internal_node'
3387 };
3388}
3389
3390// To ensure we dont grow the revision tree infinitely, we stem old revisions
3391function stem(tree, depth) {
3392 // First we break out the tree into a complete list of root to leaf paths
3393 var paths = rootToLeaf(tree);
3394 var stemmedRevs;
3395
3396 var result;
3397 for (var i = 0, len = paths.length; i < len; i++) {
3398 // Then for each path, we cut off the start of the path based on the
3399 // `depth` to stem to, and generate a new set of flat trees
3400 var path = paths[i];
3401 var stemmed = path.ids;
3402 var node;
3403 if (stemmed.length > depth) {
3404 // only do the stemming work if we actually need to stem
3405 if (!stemmedRevs) {
3406 stemmedRevs = {}; // avoid allocating this object unnecessarily
3407 }
3408 var numStemmed = stemmed.length - depth;
3409 node = {
3410 pos: path.pos + numStemmed,
3411 ids: pathToTree(stemmed, numStemmed)
3412 };
3413
3414 for (var s = 0; s < numStemmed; s++) {
3415 var rev = (path.pos + s) + '-' + stemmed[s].id;
3416 stemmedRevs[rev] = true;
3417 }
3418 } else { // no need to actually stem
3419 node = {
3420 pos: path.pos,
3421 ids: pathToTree(stemmed, 0)
3422 };
3423 }
3424
3425 // Then we remerge all those flat trees together, ensuring that we dont
3426 // connect trees that would go beyond the depth limit
3427 if (result) {
3428 result = doMerge(result, node, true).tree;
3429 } else {
3430 result = [node];
3431 }
3432 }
3433
3434 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
3435 if (stemmedRevs) {
3436 traverseRevTree(result, function (isLeaf, pos, revHash) {
3437 // some revisions may have been removed in a branch but not in another
3438 delete stemmedRevs[pos + '-' + revHash];
3439 });
3440 }
3441
3442 return {
3443 tree: result,
3444 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
3445 };
3446}
3447
3448function merge(tree, path, depth) {
3449 var newTree = doMerge(tree, path);
3450 var stemmed = stem(newTree.tree, depth);
3451 return {
3452 tree: stemmed.tree,
3453 stemmedRevs: stemmed.revs,
3454 conflicts: newTree.conflicts
3455 };
3456}
3457
3458// return true if a rev exists in the rev tree, false otherwise
3459function revExists(revs, rev) {
3460 var toVisit = revs.slice();
3461 var splitRev = rev.split('-');
3462 var targetPos = parseInt(splitRev[0], 10);
3463 var targetId = splitRev[1];
3464
3465 var node;
3466 while ((node = toVisit.pop())) {
3467 if (node.pos === targetPos && node.ids[0] === targetId) {
3468 return true;
3469 }
3470 var branches = node.ids[2];
3471 for (var i = 0, len = branches.length; i < len; i++) {
3472 toVisit.push({pos: node.pos + 1, ids: branches[i]});
3473 }
3474 }
3475 return false;
3476}
3477
3478function getTrees(node) {
3479 return node.ids;
3480}
3481
3482// check if a specific revision of a doc has been deleted
3483// - metadata: the metadata object from the doc store
3484// - rev: (optional) the revision to check. defaults to winning revision
3485function isDeleted(metadata, rev) {
3486 if (!rev) {
3487 rev = winningRev(metadata);
3488 }
3489 var id = rev.substring(rev.indexOf('-') + 1);
3490 var toVisit = metadata.rev_tree.map(getTrees);
3491
3492 var tree;
3493 while ((tree = toVisit.pop())) {
3494 if (tree[0] === id) {
3495 return !!tree[1].deleted;
3496 }
3497 toVisit = toVisit.concat(tree[2]);
3498 }
3499}
3500
3501function isLocalId(id) {
3502 return (/^_local/).test(id);
3503}
3504
3505// returns the current leaf node for a given revision
3506function latest(rev, metadata) {
3507 var toVisit = metadata.rev_tree.slice();
3508 var node;
3509 while ((node = toVisit.pop())) {
3510 var pos = node.pos;
3511 var tree = node.ids;
3512 var id = tree[0];
3513 var opts = tree[1];
3514 var branches = tree[2];
3515 var isLeaf = branches.length === 0;
3516
3517 var history = node.history ? node.history.slice() : [];
3518 history.push({id: id, pos: pos, opts: opts});
3519
3520 if (isLeaf) {
3521 for (var i = 0, len = history.length; i < len; i++) {
3522 var historyNode = history[i];
3523 var historyRev = historyNode.pos + '-' + historyNode.id;
3524
3525 if (historyRev === rev) {
3526 // return the rev of this leaf
3527 return pos + '-' + id;
3528 }
3529 }
3530 }
3531
3532 for (var j = 0, l = branches.length; j < l; j++) {
3533 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
3534 }
3535 }
3536
3537 /* istanbul ignore next */
3538 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
3539}
3540
3541inherits(Changes$1, events.EventEmitter);
3542
3543function tryCatchInChangeListener(self, change, pending, lastSeq) {
3544 // isolate try/catches to avoid V8 deoptimizations
3545 try {
3546 self.emit('change', change, pending, lastSeq);
3547 } catch (e) {
3548 guardedConsole('error', 'Error in .on("change", function):', e);
3549 }
3550}
3551
3552function Changes$1(db, opts, callback) {
3553 events.EventEmitter.call(this);
3554 var self = this;
3555 this.db = db;
3556 opts = opts ? clone(opts) : {};
3557 var complete = opts.complete = once(function (err, resp) {
3558 if (err) {
3559 if (listenerCount(self, 'error') > 0) {
3560 self.emit('error', err);
3561 }
3562 } else {
3563 self.emit('complete', resp);
3564 }
3565 self.removeAllListeners();
3566 db.removeListener('destroyed', onDestroy);
3567 });
3568 if (callback) {
3569 self.on('complete', function (resp) {
3570 callback(null, resp);
3571 });
3572 self.on('error', callback);
3573 }
3574 function onDestroy() {
3575 self.cancel();
3576 }
3577 db.once('destroyed', onDestroy);
3578
3579 opts.onChange = function (change, pending, lastSeq) {
3580 /* istanbul ignore if */
3581 if (self.isCancelled) {
3582 return;
3583 }
3584 tryCatchInChangeListener(self, change, pending, lastSeq);
3585 };
3586
3587 var promise = new Promise(function (fulfill, reject) {
3588 opts.complete = function (err, res) {
3589 if (err) {
3590 reject(err);
3591 } else {
3592 fulfill(res);
3593 }
3594 };
3595 });
3596 self.once('cancel', function () {
3597 db.removeListener('destroyed', onDestroy);
3598 opts.complete(null, {status: 'cancelled'});
3599 });
3600 this.then = promise.then.bind(promise);
3601 this['catch'] = promise['catch'].bind(promise);
3602 this.then(function (result) {
3603 complete(null, result);
3604 }, complete);
3605
3606
3607
3608 if (!db.taskqueue.isReady) {
3609 db.taskqueue.addTask(function (failed) {
3610 if (failed) {
3611 opts.complete(failed);
3612 } else if (self.isCancelled) {
3613 self.emit('cancel');
3614 } else {
3615 self.validateChanges(opts);
3616 }
3617 });
3618 } else {
3619 self.validateChanges(opts);
3620 }
3621}
3622Changes$1.prototype.cancel = function () {
3623 this.isCancelled = true;
3624 if (this.db.taskqueue.isReady) {
3625 this.emit('cancel');
3626 }
3627};
3628function processChange(doc, metadata, opts) {
3629 var changeList = [{rev: doc._rev}];
3630 if (opts.style === 'all_docs') {
3631 changeList = collectLeaves(metadata.rev_tree)
3632 .map(function (x) { return {rev: x.rev}; });
3633 }
3634 var change = {
3635 id: metadata.id,
3636 changes: changeList,
3637 doc: doc
3638 };
3639
3640 if (isDeleted(metadata, doc._rev)) {
3641 change.deleted = true;
3642 }
3643 if (opts.conflicts) {
3644 change.doc._conflicts = collectConflicts(metadata);
3645 if (!change.doc._conflicts.length) {
3646 delete change.doc._conflicts;
3647 }
3648 }
3649 return change;
3650}
3651
3652Changes$1.prototype.validateChanges = function (opts) {
3653 var callback = opts.complete;
3654 var self = this;
3655
3656 /* istanbul ignore else */
3657 if (PouchDB._changesFilterPlugin) {
3658 PouchDB._changesFilterPlugin.validate(opts, function (err) {
3659 if (err) {
3660 return callback(err);
3661 }
3662 self.doChanges(opts);
3663 });
3664 } else {
3665 self.doChanges(opts);
3666 }
3667};
3668
3669Changes$1.prototype.doChanges = function (opts) {
3670 var self = this;
3671 var callback = opts.complete;
3672
3673 opts = clone(opts);
3674 if ('live' in opts && !('continuous' in opts)) {
3675 opts.continuous = opts.live;
3676 }
3677 opts.processChange = processChange;
3678
3679 if (opts.since === 'latest') {
3680 opts.since = 'now';
3681 }
3682 if (!opts.since) {
3683 opts.since = 0;
3684 }
3685 if (opts.since === 'now') {
3686 this.db.info().then(function (info) {
3687 /* istanbul ignore if */
3688 if (self.isCancelled) {
3689 callback(null, {status: 'cancelled'});
3690 return;
3691 }
3692 opts.since = info.update_seq;
3693 self.doChanges(opts);
3694 }, callback);
3695 return;
3696 }
3697
3698 /* istanbul ignore else */
3699 if (PouchDB._changesFilterPlugin) {
3700 PouchDB._changesFilterPlugin.normalize(opts);
3701 if (PouchDB._changesFilterPlugin.shouldFilter(this, opts)) {
3702 return PouchDB._changesFilterPlugin.filter(this, opts);
3703 }
3704 } else {
3705 ['doc_ids', 'filter', 'selector', 'view'].forEach(function (key) {
3706 if (key in opts) {
3707 guardedConsole('warn',
3708 'The "' + key + '" option was passed in to changes/replicate, ' +
3709 'but pouchdb-changes-filter plugin is not installed, so it ' +
3710 'was ignored. Please install the plugin to enable filtering.'
3711 );
3712 }
3713 });
3714 }
3715
3716 if (!('descending' in opts)) {
3717 opts.descending = false;
3718 }
3719
3720 // 0 and 1 should return 1 document
3721 opts.limit = opts.limit === 0 ? 1 : opts.limit;
3722 opts.complete = callback;
3723 var newPromise = this.db._changes(opts);
3724 /* istanbul ignore else */
3725 if (newPromise && typeof newPromise.cancel === 'function') {
3726 var cancel = self.cancel;
3727 self.cancel = getArguments(function (args) {
3728 newPromise.cancel();
3729 cancel.apply(this, args);
3730 });
3731 }
3732};
3733
3734/*
3735 * A generic pouch adapter
3736 */
3737
3738function compare(left, right) {
3739 return left < right ? -1 : left > right ? 1 : 0;
3740}
3741
3742// Wrapper for functions that call the bulkdocs api with a single doc,
3743// if the first result is an error, return an error
3744function yankError(callback, docId) {
3745 return function (err, results) {
3746 if (err || (results[0] && results[0].error)) {
3747 err = err || results[0];
3748 err.docId = docId;
3749 callback(err);
3750 } else {
3751 callback(null, results.length ? results[0] : results);
3752 }
3753 };
3754}
3755
3756// clean docs given to us by the user
3757function cleanDocs(docs) {
3758 for (var i = 0; i < docs.length; i++) {
3759 var doc = docs[i];
3760 if (doc._deleted) {
3761 delete doc._attachments; // ignore atts for deleted docs
3762 } else if (doc._attachments) {
3763 // filter out extraneous keys from _attachments
3764 var atts = Object.keys(doc._attachments);
3765 for (var j = 0; j < atts.length; j++) {
3766 var att = atts[j];
3767 doc._attachments[att] = pick(doc._attachments[att],
3768 ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
3769 }
3770 }
3771 }
3772}
3773
3774// compare two docs, first by _id then by _rev
3775function compareByIdThenRev(a, b) {
3776 var idCompare = compare(a._id, b._id);
3777 if (idCompare !== 0) {
3778 return idCompare;
3779 }
3780 var aStart = a._revisions ? a._revisions.start : 0;
3781 var bStart = b._revisions ? b._revisions.start : 0;
3782 return compare(aStart, bStart);
3783}
3784
3785// for every node in a revision tree computes its distance from the closest
3786// leaf
3787function computeHeight(revs) {
3788 var height = {};
3789 var edges = [];
3790 traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
3791 var rev = pos + "-" + id;
3792 if (isLeaf) {
3793 height[rev] = 0;
3794 }
3795 if (prnt !== undefined) {
3796 edges.push({from: prnt, to: rev});
3797 }
3798 return rev;
3799 });
3800
3801 edges.reverse();
3802 edges.forEach(function (edge) {
3803 if (height[edge.from] === undefined) {
3804 height[edge.from] = 1 + height[edge.to];
3805 } else {
3806 height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
3807 }
3808 });
3809 return height;
3810}
3811
3812function allDocsKeysParse(opts) {
3813 var keys = ('limit' in opts) ?
3814 opts.keys.slice(opts.skip, opts.limit + opts.skip) :
3815 (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;
3816 opts.keys = keys;
3817 opts.skip = 0;
3818 delete opts.limit;
3819 if (opts.descending) {
3820 keys.reverse();
3821 opts.descending = false;
3822 }
3823}
3824
3825// all compaction is done in a queue, to avoid attaching
3826// too many listeners at once
3827function doNextCompaction(self) {
3828 var task = self._compactionQueue[0];
3829 var opts = task.opts;
3830 var callback = task.callback;
3831 self.get('_local/compaction')["catch"](function () {
3832 return false;
3833 }).then(function (doc) {
3834 if (doc && doc.last_seq) {
3835 opts.last_seq = doc.last_seq;
3836 }
3837 self._compact(opts, function (err, res) {
3838 /* istanbul ignore if */
3839 if (err) {
3840 callback(err);
3841 } else {
3842 callback(null, res);
3843 }
3844 nextTick(function () {
3845 self._compactionQueue.shift();
3846 if (self._compactionQueue.length) {
3847 doNextCompaction(self);
3848 }
3849 });
3850 });
3851 });
3852}
3853
3854function attachmentNameError(name) {
3855 if (name.charAt(0) === '_') {
3856 return name + ' is not a valid attachment name, attachment ' +
3857 'names cannot start with \'_\'';
3858 }
3859 return false;
3860}
3861
3862inherits(AbstractPouchDB, events.EventEmitter);
3863
3864function AbstractPouchDB() {
3865 events.EventEmitter.call(this);
3866
3867 // re-bind prototyped methods
3868 for (var p in AbstractPouchDB.prototype) {
3869 if (typeof this[p] === 'function') {
3870 this[p] = this[p].bind(this);
3871 }
3872 }
3873}
3874
3875AbstractPouchDB.prototype.post =
3876 adapterFun('post', function (doc, opts, callback) {
3877 if (typeof opts === 'function') {
3878 callback = opts;
3879 opts = {};
3880 }
3881 if (typeof doc !== 'object' || Array.isArray(doc)) {
3882 return callback(createError(NOT_AN_OBJECT));
3883 }
3884 this.bulkDocs({docs: [doc]}, opts, yankError(callback, doc._id));
3885});
3886
3887AbstractPouchDB.prototype.put = adapterFun('put', function (doc, opts, cb) {
3888 if (typeof opts === 'function') {
3889 cb = opts;
3890 opts = {};
3891 }
3892 if (typeof doc !== 'object' || Array.isArray(doc)) {
3893 return cb(createError(NOT_AN_OBJECT));
3894 }
3895 invalidIdError(doc._id);
3896 if (isLocalId(doc._id) && typeof this._putLocal === 'function') {
3897 if (doc._deleted) {
3898 return this._removeLocal(doc, cb);
3899 } else {
3900 return this._putLocal(doc, cb);
3901 }
3902 }
3903 var self = this;
3904 if (opts.force && doc._rev) {
3905 transformForceOptionToNewEditsOption();
3906 putDoc(function (err) {
3907 var result = err ? null : {ok: true, id: doc._id, rev: doc._rev};
3908 cb(err, result);
3909 });
3910 } else {
3911 putDoc(cb);
3912 }
3913
3914 function transformForceOptionToNewEditsOption() {
3915 var parts = doc._rev.split('-');
3916 var oldRevId = parts[1];
3917 var oldRevNum = parseInt(parts[0], 10);
3918
3919 var newRevNum = oldRevNum + 1;
3920 var newRevId = rev$$1();
3921
3922 doc._revisions = {
3923 start: newRevNum,
3924 ids: [newRevId, oldRevId]
3925 };
3926 doc._rev = newRevNum + '-' + newRevId;
3927 opts.new_edits = false;
3928 }
3929 function putDoc(next) {
3930 if (typeof self._put === 'function' && opts.new_edits !== false) {
3931 self._put(doc, opts, next);
3932 } else {
3933 self.bulkDocs({docs: [doc]}, opts, yankError(next, doc._id));
3934 }
3935 }
3936});
3937
3938AbstractPouchDB.prototype.putAttachment =
3939 adapterFun('putAttachment', function (docId, attachmentId, rev,
3940 blob, type) {
3941 var api = this;
3942 if (typeof type === 'function') {
3943 type = blob;
3944 blob = rev;
3945 rev = null;
3946 }
3947 // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267
3948 /* istanbul ignore if */
3949 if (typeof type === 'undefined') {
3950 type = blob;
3951 blob = rev;
3952 rev = null;
3953 }
3954 if (!type) {
3955 guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');
3956 }
3957
3958 function createAttachment(doc) {
3959 var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;
3960 doc._attachments = doc._attachments || {};
3961 doc._attachments[attachmentId] = {
3962 content_type: type,
3963 data: blob,
3964 revpos: ++prevrevpos
3965 };
3966 return api.put(doc);
3967 }
3968
3969 return api.get(docId).then(function (doc) {
3970 if (doc._rev !== rev) {
3971 throw createError(REV_CONFLICT);
3972 }
3973
3974 return createAttachment(doc);
3975 }, function (err) {
3976 // create new doc
3977 /* istanbul ignore else */
3978 if (err.reason === MISSING_DOC.message) {
3979 return createAttachment({_id: docId});
3980 } else {
3981 throw err;
3982 }
3983 });
3984});
3985
3986AbstractPouchDB.prototype.removeAttachment =
3987 adapterFun('removeAttachment', function (docId, attachmentId, rev,
3988 callback) {
3989 var self = this;
3990 self.get(docId, function (err, obj) {
3991 /* istanbul ignore if */
3992 if (err) {
3993 callback(err);
3994 return;
3995 }
3996 if (obj._rev !== rev) {
3997 callback(createError(REV_CONFLICT));
3998 return;
3999 }
4000 /* istanbul ignore if */
4001 if (!obj._attachments) {
4002 return callback();
4003 }
4004 delete obj._attachments[attachmentId];
4005 if (Object.keys(obj._attachments).length === 0) {
4006 delete obj._attachments;
4007 }
4008 self.put(obj, callback);
4009 });
4010});
4011
4012AbstractPouchDB.prototype.remove =
4013 adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
4014 var doc;
4015 if (typeof optsOrRev === 'string') {
4016 // id, rev, opts, callback style
4017 doc = {
4018 _id: docOrId,
4019 _rev: optsOrRev
4020 };
4021 if (typeof opts === 'function') {
4022 callback = opts;
4023 opts = {};
4024 }
4025 } else {
4026 // doc, opts, callback style
4027 doc = docOrId;
4028 if (typeof optsOrRev === 'function') {
4029 callback = optsOrRev;
4030 opts = {};
4031 } else {
4032 callback = opts;
4033 opts = optsOrRev;
4034 }
4035 }
4036 opts = opts || {};
4037 opts.was_delete = true;
4038 var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};
4039 newDoc._deleted = true;
4040 if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {
4041 return this._removeLocal(doc, callback);
4042 }
4043 this.bulkDocs({docs: [newDoc]}, opts, yankError(callback, newDoc._id));
4044});
4045
4046AbstractPouchDB.prototype.revsDiff =
4047 adapterFun('revsDiff', function (req, opts, callback) {
4048 if (typeof opts === 'function') {
4049 callback = opts;
4050 opts = {};
4051 }
4052 var ids = Object.keys(req);
4053
4054 if (!ids.length) {
4055 return callback(null, {});
4056 }
4057
4058 var count = 0;
4059 var missing = new ExportedMap();
4060
4061 function addToMissing(id, revId) {
4062 if (!missing.has(id)) {
4063 missing.set(id, {missing: []});
4064 }
4065 missing.get(id).missing.push(revId);
4066 }
4067
4068 function processDoc(id, rev_tree) {
4069 // Is this fast enough? Maybe we should switch to a set simulated by a map
4070 var missingForId = req[id].slice(0);
4071 traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,
4072 opts) {
4073 var rev = pos + '-' + revHash;
4074 var idx = missingForId.indexOf(rev);
4075 if (idx === -1) {
4076 return;
4077 }
4078
4079 missingForId.splice(idx, 1);
4080 /* istanbul ignore if */
4081 if (opts.status !== 'available') {
4082 addToMissing(id, rev);
4083 }
4084 });
4085
4086 // Traversing the tree is synchronous, so now `missingForId` contains
4087 // revisions that were not found in the tree
4088 missingForId.forEach(function (rev) {
4089 addToMissing(id, rev);
4090 });
4091 }
4092
4093 ids.map(function (id) {
4094 this._getRevisionTree(id, function (err, rev_tree) {
4095 if (err && err.status === 404 && err.message === 'missing') {
4096 missing.set(id, {missing: req[id]});
4097 } else if (err) {
4098 /* istanbul ignore next */
4099 return callback(err);
4100 } else {
4101 processDoc(id, rev_tree);
4102 }
4103
4104 if (++count === ids.length) {
4105 // convert LazyMap to object
4106 var missingObj = {};
4107 missing.forEach(function (value, key) {
4108 missingObj[key] = value;
4109 });
4110 return callback(null, missingObj);
4111 }
4112 });
4113 }, this);
4114});
4115
4116// _bulk_get API for faster replication, as described in
4117// https://github.com/apache/couchdb-chttpd/pull/33
4118// At the "abstract" level, it will just run multiple get()s in
4119// parallel, because this isn't much of a performance cost
4120// for local databases (except the cost of multiple transactions, which is
4121// small). The http adapter overrides this in order
4122// to do a more efficient single HTTP request.
4123AbstractPouchDB.prototype.bulkGet =
4124 adapterFun('bulkGet', function (opts, callback) {
4125 bulkGet(this, opts, callback);
4126});
4127
4128// compact one document and fire callback
4129// by compacting we mean removing all revisions which
4130// are further from the leaf in revision tree than max_height
4131AbstractPouchDB.prototype.compactDocument =
4132 adapterFun('compactDocument', function (docId, maxHeight, callback) {
4133 var self = this;
4134 this._getRevisionTree(docId, function (err, revTree) {
4135 /* istanbul ignore if */
4136 if (err) {
4137 return callback(err);
4138 }
4139 var height = computeHeight(revTree);
4140 var candidates = [];
4141 var revs = [];
4142 Object.keys(height).forEach(function (rev) {
4143 if (height[rev] > maxHeight) {
4144 candidates.push(rev);
4145 }
4146 });
4147
4148 traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {
4149 var rev = pos + '-' + revHash;
4150 if (opts.status === 'available' && candidates.indexOf(rev) !== -1) {
4151 revs.push(rev);
4152 }
4153 });
4154 self._doCompaction(docId, revs, callback);
4155 });
4156});
4157
4158// compact the whole database using single document
4159// compaction
4160AbstractPouchDB.prototype.compact =
4161 adapterFun('compact', function (opts, callback) {
4162 if (typeof opts === 'function') {
4163 callback = opts;
4164 opts = {};
4165 }
4166
4167 var self = this;
4168 opts = opts || {};
4169
4170 self._compactionQueue = self._compactionQueue || [];
4171 self._compactionQueue.push({opts: opts, callback: callback});
4172 if (self._compactionQueue.length === 1) {
4173 doNextCompaction(self);
4174 }
4175});
4176AbstractPouchDB.prototype._compact = function (opts, callback) {
4177 var self = this;
4178 var changesOpts = {
4179 return_docs: false,
4180 last_seq: opts.last_seq || 0
4181 };
4182 var promises = [];
4183
4184 function onChange(row) {
4185 promises.push(self.compactDocument(row.id, 0));
4186 }
4187 function onComplete(resp) {
4188 var lastSeq = resp.last_seq;
4189 Promise.all(promises).then(function () {
4190 return upsert(self, '_local/compaction', function deltaFunc(doc) {
4191 if (!doc.last_seq || doc.last_seq < lastSeq) {
4192 doc.last_seq = lastSeq;
4193 return doc;
4194 }
4195 return false; // somebody else got here first, don't update
4196 });
4197 }).then(function () {
4198 callback(null, {ok: true});
4199 })["catch"](callback);
4200 }
4201 self.changes(changesOpts)
4202 .on('change', onChange)
4203 .on('complete', onComplete)
4204 .on('error', callback);
4205};
4206
4207/* Begin api wrappers. Specific functionality to storage belongs in the
4208 _[method] */
4209AbstractPouchDB.prototype.get = adapterFun('get', function (id, opts, cb) {
4210 if (typeof opts === 'function') {
4211 cb = opts;
4212 opts = {};
4213 }
4214 if (typeof id !== 'string') {
4215 return cb(createError(INVALID_ID));
4216 }
4217 if (isLocalId(id) && typeof this._getLocal === 'function') {
4218 return this._getLocal(id, cb);
4219 }
4220 var leaves = [], self = this;
4221
4222 function finishOpenRevs() {
4223 var result = [];
4224 var count = leaves.length;
4225 /* istanbul ignore if */
4226 if (!count) {
4227 return cb(null, result);
4228 }
4229
4230 // order with open_revs is unspecified
4231 leaves.forEach(function (leaf) {
4232 self.get(id, {
4233 rev: leaf,
4234 revs: opts.revs,
4235 latest: opts.latest,
4236 attachments: opts.attachments,
4237 binary: opts.binary
4238 }, function (err, doc) {
4239 if (!err) {
4240 // using latest=true can produce duplicates
4241 var existing;
4242 for (var i = 0, l = result.length; i < l; i++) {
4243 if (result[i].ok && result[i].ok._rev === doc._rev) {
4244 existing = true;
4245 break;
4246 }
4247 }
4248 if (!existing) {
4249 result.push({ok: doc});
4250 }
4251 } else {
4252 result.push({missing: leaf});
4253 }
4254 count--;
4255 if (!count) {
4256 cb(null, result);
4257 }
4258 });
4259 });
4260 }
4261
4262 if (opts.open_revs) {
4263 if (opts.open_revs === "all") {
4264 this._getRevisionTree(id, function (err, rev_tree) {
4265 /* istanbul ignore if */
4266 if (err) {
4267 return cb(err);
4268 }
4269 leaves = collectLeaves(rev_tree).map(function (leaf) {
4270 return leaf.rev;
4271 });
4272 finishOpenRevs();
4273 });
4274 } else {
4275 if (Array.isArray(opts.open_revs)) {
4276 leaves = opts.open_revs;
4277 for (var i = 0; i < leaves.length; i++) {
4278 var l = leaves[i];
4279 // looks like it's the only thing couchdb checks
4280 if (!(typeof (l) === "string" && /^\d+-/.test(l))) {
4281 return cb(createError(INVALID_REV));
4282 }
4283 }
4284 finishOpenRevs();
4285 } else {
4286 return cb(createError(UNKNOWN_ERROR, 'function_clause'));
4287 }
4288 }
4289 return; // open_revs does not like other options
4290 }
4291
4292 return this._get(id, opts, function (err, result) {
4293 if (err) {
4294 err.docId = id;
4295 return cb(err);
4296 }
4297
4298 var doc = result.doc;
4299 var metadata = result.metadata;
4300 var ctx = result.ctx;
4301
4302 if (opts.conflicts) {
4303 var conflicts = collectConflicts(metadata);
4304 if (conflicts.length) {
4305 doc._conflicts = conflicts;
4306 }
4307 }
4308
4309 if (isDeleted(metadata, doc._rev)) {
4310 doc._deleted = true;
4311 }
4312
4313 if (opts.revs || opts.revs_info) {
4314 var splittedRev = doc._rev.split('-');
4315 var revNo = parseInt(splittedRev[0], 10);
4316 var revHash = splittedRev[1];
4317
4318 var paths = rootToLeaf(metadata.rev_tree);
4319 var path = null;
4320
4321 for (var i = 0; i < paths.length; i++) {
4322 var currentPath = paths[i];
4323 var hashIndex = currentPath.ids.map(function (x) { return x.id; })
4324 .indexOf(revHash);
4325 var hashFoundAtRevPos = hashIndex === (revNo - 1);
4326
4327 if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {
4328 path = currentPath;
4329 }
4330 }
4331
4332 var indexOfRev = path.ids.map(function (x) { return x.id; })
4333 .indexOf(doc._rev.split('-')[1]) + 1;
4334 var howMany = path.ids.length - indexOfRev;
4335 path.ids.splice(indexOfRev, howMany);
4336 path.ids.reverse();
4337
4338 if (opts.revs) {
4339 doc._revisions = {
4340 start: (path.pos + path.ids.length) - 1,
4341 ids: path.ids.map(function (rev) {
4342 return rev.id;
4343 })
4344 };
4345 }
4346 if (opts.revs_info) {
4347 var pos = path.pos + path.ids.length;
4348 doc._revs_info = path.ids.map(function (rev) {
4349 pos--;
4350 return {
4351 rev: pos + '-' + rev.id,
4352 status: rev.opts.status
4353 };
4354 });
4355 }
4356 }
4357
4358 if (opts.attachments && doc._attachments) {
4359 var attachments = doc._attachments;
4360 var count = Object.keys(attachments).length;
4361 if (count === 0) {
4362 return cb(null, doc);
4363 }
4364 Object.keys(attachments).forEach(function (key) {
4365 this._getAttachment(doc._id, key, attachments[key], {
4366 // Previously the revision handling was done in adapter.js
4367 // getAttachment, however since idb-next doesnt we need to
4368 // pass the rev through
4369 rev: doc._rev,
4370 binary: opts.binary,
4371 ctx: ctx
4372 }, function (err, data) {
4373 var att = doc._attachments[key];
4374 att.data = data;
4375 delete att.stub;
4376 delete att.length;
4377 if (!--count) {
4378 cb(null, doc);
4379 }
4380 });
4381 }, self);
4382 } else {
4383 if (doc._attachments) {
4384 for (var key in doc._attachments) {
4385 /* istanbul ignore else */
4386 if (doc._attachments.hasOwnProperty(key)) {
4387 doc._attachments[key].stub = true;
4388 }
4389 }
4390 }
4391 cb(null, doc);
4392 }
4393 });
4394});
4395
4396// TODO: I dont like this, it forces an extra read for every
4397// attachment read and enforces a confusing api between
4398// adapter.js and the adapter implementation
4399AbstractPouchDB.prototype.getAttachment =
4400 adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {
4401 var self = this;
4402 if (opts instanceof Function) {
4403 callback = opts;
4404 opts = {};
4405 }
4406 this._get(docId, opts, function (err, res) {
4407 if (err) {
4408 return callback(err);
4409 }
4410 if (res.doc._attachments && res.doc._attachments[attachmentId]) {
4411 opts.ctx = res.ctx;
4412 opts.binary = true;
4413 self._getAttachment(docId, attachmentId,
4414 res.doc._attachments[attachmentId], opts, callback);
4415 } else {
4416 return callback(createError(MISSING_DOC));
4417 }
4418 });
4419});
4420
4421AbstractPouchDB.prototype.allDocs =
4422 adapterFun('allDocs', function (opts, callback) {
4423 if (typeof opts === 'function') {
4424 callback = opts;
4425 opts = {};
4426 }
4427 opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;
4428 if (opts.start_key) {
4429 opts.startkey = opts.start_key;
4430 }
4431 if (opts.end_key) {
4432 opts.endkey = opts.end_key;
4433 }
4434 if ('keys' in opts) {
4435 if (!Array.isArray(opts.keys)) {
4436 return callback(new TypeError('options.keys must be an array'));
4437 }
4438 var incompatibleOpt =
4439 ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {
4440 return incompatibleOpt in opts;
4441 })[0];
4442 if (incompatibleOpt) {
4443 callback(createError(QUERY_PARSE_ERROR,
4444 'Query parameter `' + incompatibleOpt +
4445 '` is not compatible with multi-get'
4446 ));
4447 return;
4448 }
4449 if (!isRemote(this)) {
4450 allDocsKeysParse(opts);
4451 if (opts.keys.length === 0) {
4452 return this._allDocs({limit: 0}, callback);
4453 }
4454 }
4455 }
4456
4457 return this._allDocs(opts, callback);
4458});
4459
4460AbstractPouchDB.prototype.changes = function (opts, callback) {
4461 if (typeof opts === 'function') {
4462 callback = opts;
4463 opts = {};
4464 }
4465
4466 opts = opts || {};
4467
4468 // By default set return_docs to false if the caller has opts.live = true,
4469 // this will prevent us from collecting the set of changes indefinitely
4470 // resulting in growing memory
4471 opts.return_docs = ('return_docs' in opts) ? opts.return_docs : !opts.live;
4472
4473 return new Changes$1(this, opts, callback);
4474};
4475
4476AbstractPouchDB.prototype.close = adapterFun('close', function (callback) {
4477 this._closed = true;
4478 this.emit('closed');
4479 return this._close(callback);
4480});
4481
4482AbstractPouchDB.prototype.info = adapterFun('info', function (callback) {
4483 var self = this;
4484 this._info(function (err, info) {
4485 if (err) {
4486 return callback(err);
4487 }
4488 // assume we know better than the adapter, unless it informs us
4489 info.db_name = info.db_name || self.name;
4490 info.auto_compaction = !!(self.auto_compaction && !isRemote(self));
4491 info.adapter = self.adapter;
4492 callback(null, info);
4493 });
4494});
4495
4496AbstractPouchDB.prototype.id = adapterFun('id', function (callback) {
4497 return this._id(callback);
4498});
4499
4500/* istanbul ignore next */
4501AbstractPouchDB.prototype.type = function () {
4502 return (typeof this._type === 'function') ? this._type() : this.adapter;
4503};
4504
4505AbstractPouchDB.prototype.bulkDocs =
4506 adapterFun('bulkDocs', function (req, opts, callback) {
4507 if (typeof opts === 'function') {
4508 callback = opts;
4509 opts = {};
4510 }
4511
4512 opts = opts || {};
4513
4514 if (Array.isArray(req)) {
4515 req = {
4516 docs: req
4517 };
4518 }
4519
4520 if (!req || !req.docs || !Array.isArray(req.docs)) {
4521 return callback(createError(MISSING_BULK_DOCS));
4522 }
4523
4524 for (var i = 0; i < req.docs.length; ++i) {
4525 if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) {
4526 return callback(createError(NOT_AN_OBJECT));
4527 }
4528 }
4529
4530 var attachmentError;
4531 req.docs.forEach(function (doc) {
4532 if (doc._attachments) {
4533 Object.keys(doc._attachments).forEach(function (name) {
4534 attachmentError = attachmentError || attachmentNameError(name);
4535 if (!doc._attachments[name].content_type) {
4536 guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');
4537 }
4538 });
4539 }
4540 });
4541
4542 if (attachmentError) {
4543 return callback(createError(BAD_REQUEST, attachmentError));
4544 }
4545
4546 if (!('new_edits' in opts)) {
4547 if ('new_edits' in req) {
4548 opts.new_edits = req.new_edits;
4549 } else {
4550 opts.new_edits = true;
4551 }
4552 }
4553
4554 var adapter = this;
4555 if (!opts.new_edits && !isRemote(adapter)) {
4556 // ensure revisions of the same doc are sorted, so that
4557 // the local adapter processes them correctly (#2935)
4558 req.docs.sort(compareByIdThenRev);
4559 }
4560
4561 cleanDocs(req.docs);
4562
4563 // in the case of conflicts, we want to return the _ids to the user
4564 // however, the underlying adapter may destroy the docs array, so
4565 // create a copy here
4566 var ids = req.docs.map(function (doc) {
4567 return doc._id;
4568 });
4569
4570 return this._bulkDocs(req, opts, function (err, res) {
4571 if (err) {
4572 return callback(err);
4573 }
4574 if (!opts.new_edits) {
4575 // this is what couch does when new_edits is false
4576 res = res.filter(function (x) {
4577 return x.error;
4578 });
4579 }
4580 // add ids for error/conflict responses (not required for CouchDB)
4581 if (!isRemote(adapter)) {
4582 for (var i = 0, l = res.length; i < l; i++) {
4583 res[i].id = res[i].id || ids[i];
4584 }
4585 }
4586
4587 callback(null, res);
4588 });
4589});
4590
4591AbstractPouchDB.prototype.registerDependentDatabase =
4592 adapterFun('registerDependentDatabase', function (dependentDb,
4593 callback) {
4594 var depDB = new this.constructor(dependentDb, this.__opts);
4595
4596 function diffFun(doc) {
4597 doc.dependentDbs = doc.dependentDbs || {};
4598 if (doc.dependentDbs[dependentDb]) {
4599 return false; // no update required
4600 }
4601 doc.dependentDbs[dependentDb] = true;
4602 return doc;
4603 }
4604 upsert(this, '_local/_pouch_dependentDbs', diffFun)
4605 .then(function () {
4606 callback(null, {db: depDB});
4607 })["catch"](callback);
4608});
4609
4610AbstractPouchDB.prototype.destroy =
4611 adapterFun('destroy', function (opts, callback) {
4612
4613 if (typeof opts === 'function') {
4614 callback = opts;
4615 opts = {};
4616 }
4617
4618 var self = this;
4619 var usePrefix = 'use_prefix' in self ? self.use_prefix : true;
4620
4621 function destroyDb() {
4622 // call destroy method of the particular adaptor
4623 self._destroy(opts, function (err, resp) {
4624 if (err) {
4625 return callback(err);
4626 }
4627 self._destroyed = true;
4628 self.emit('destroyed');
4629 callback(null, resp || { 'ok': true });
4630 });
4631 }
4632
4633 if (isRemote(self)) {
4634 // no need to check for dependent DBs if it's a remote DB
4635 return destroyDb();
4636 }
4637
4638 self.get('_local/_pouch_dependentDbs', function (err, localDoc) {
4639 if (err) {
4640 /* istanbul ignore if */
4641 if (err.status !== 404) {
4642 return callback(err);
4643 } else { // no dependencies
4644 return destroyDb();
4645 }
4646 }
4647 var dependentDbs = localDoc.dependentDbs;
4648 var PouchDB = self.constructor;
4649 var deletedMap = Object.keys(dependentDbs).map(function (name) {
4650 // use_prefix is only false in the browser
4651 /* istanbul ignore next */
4652 var trueName = usePrefix ?
4653 name.replace(new RegExp('^' + PouchDB.prefix), '') : name;
4654 return new PouchDB(trueName, self.__opts).destroy();
4655 });
4656 Promise.all(deletedMap).then(destroyDb, callback);
4657 });
4658});
4659
4660function TaskQueue() {
4661 this.isReady = false;
4662 this.failed = false;
4663 this.queue = [];
4664}
4665
4666TaskQueue.prototype.execute = function () {
4667 var fun;
4668 if (this.failed) {
4669 while ((fun = this.queue.shift())) {
4670 fun(this.failed);
4671 }
4672 } else {
4673 while ((fun = this.queue.shift())) {
4674 fun();
4675 }
4676 }
4677};
4678
4679TaskQueue.prototype.fail = function (err) {
4680 this.failed = err;
4681 this.execute();
4682};
4683
4684TaskQueue.prototype.ready = function (db) {
4685 this.isReady = true;
4686 this.db = db;
4687 this.execute();
4688};
4689
4690TaskQueue.prototype.addTask = function (fun) {
4691 this.queue.push(fun);
4692 if (this.failed) {
4693 this.execute();
4694 }
4695};
4696
4697function parseAdapter(name, opts) {
4698 var match = name.match(/([a-z-]*):\/\/(.*)/);
4699 if (match) {
4700 // the http adapter expects the fully qualified name
4701 return {
4702 name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],
4703 adapter: match[1]
4704 };
4705 }
4706
4707 var adapters = PouchDB.adapters;
4708 var preferredAdapters = PouchDB.preferredAdapters;
4709 var prefix = PouchDB.prefix;
4710 var adapterName = opts.adapter;
4711
4712 if (!adapterName) { // automatically determine adapter
4713 for (var i = 0; i < preferredAdapters.length; ++i) {
4714 adapterName = preferredAdapters[i];
4715 // check for browsers that have been upgraded from websql-only to websql+idb
4716 /* istanbul ignore if */
4717 if (adapterName === 'idb' && 'websql' in adapters &&
4718 hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {
4719 // log it, because this can be confusing during development
4720 guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' +
4721 ' avoid data loss, because it was already opened with WebSQL.');
4722 continue; // keep using websql to avoid user data loss
4723 }
4724 break;
4725 }
4726 }
4727
4728 var adapter = adapters[adapterName];
4729
4730 // if adapter is invalid, then an error will be thrown later
4731 var usePrefix = (adapter && 'use_prefix' in adapter) ?
4732 adapter.use_prefix : true;
4733
4734 return {
4735 name: usePrefix ? (prefix + name) : name,
4736 adapter: adapterName
4737 };
4738}
4739
4740// OK, so here's the deal. Consider this code:
4741// var db1 = new PouchDB('foo');
4742// var db2 = new PouchDB('foo');
4743// db1.destroy();
4744// ^ these two both need to emit 'destroyed' events,
4745// as well as the PouchDB constructor itself.
4746// So we have one db object (whichever one got destroy() called on it)
4747// responsible for emitting the initial event, which then gets emitted
4748// by the constructor, which then broadcasts it to any other dbs
4749// that may have been created with the same name.
4750function prepareForDestruction(self) {
4751
4752 function onDestroyed(from_constructor) {
4753 self.removeListener('closed', onClosed);
4754 if (!from_constructor) {
4755 self.constructor.emit('destroyed', self.name);
4756 }
4757 }
4758
4759 function onClosed() {
4760 self.removeListener('destroyed', onDestroyed);
4761 self.constructor.emit('unref', self);
4762 }
4763
4764 self.once('destroyed', onDestroyed);
4765 self.once('closed', onClosed);
4766 self.constructor.emit('ref', self);
4767}
4768
4769inherits(PouchDB, AbstractPouchDB);
4770function PouchDB(name, opts) {
4771 // In Node our test suite only tests this for PouchAlt unfortunately
4772 /* istanbul ignore if */
4773 if (!(this instanceof PouchDB)) {
4774 return new PouchDB(name, opts);
4775 }
4776
4777 var self = this;
4778 opts = opts || {};
4779
4780 if (name && typeof name === 'object') {
4781 opts = name;
4782 name = opts.name;
4783 delete opts.name;
4784 }
4785
4786 if (opts.deterministic_revs === undefined) {
4787 opts.deterministic_revs = true;
4788 }
4789
4790 this.__opts = opts = clone(opts);
4791
4792 self.auto_compaction = opts.auto_compaction;
4793 self.prefix = PouchDB.prefix;
4794
4795 if (typeof name !== 'string') {
4796 throw new Error('Missing/invalid DB name');
4797 }
4798
4799 var prefixedName = (opts.prefix || '') + name;
4800 var backend = parseAdapter(prefixedName, opts);
4801
4802 opts.name = backend.name;
4803 opts.adapter = opts.adapter || backend.adapter;
4804
4805 self.name = name;
4806 self._adapter = opts.adapter;
4807 PouchDB.emit('debug', ['adapter', 'Picked adapter: ', opts.adapter]);
4808
4809 if (!PouchDB.adapters[opts.adapter] ||
4810 !PouchDB.adapters[opts.adapter].valid()) {
4811 throw new Error('Invalid Adapter: ' + opts.adapter);
4812 }
4813
4814 AbstractPouchDB.call(self);
4815 self.taskqueue = new TaskQueue();
4816
4817 self.adapter = opts.adapter;
4818
4819 PouchDB.adapters[opts.adapter].call(self, opts, function (err) {
4820 if (err) {
4821 return self.taskqueue.fail(err);
4822 }
4823 prepareForDestruction(self);
4824
4825 self.emit('created', self);
4826 PouchDB.emit('created', self.name);
4827 self.taskqueue.ready(self);
4828 });
4829
4830}
4831
4832// AbortController was introduced quite a while after fetch and
4833// isnt required for PouchDB to function so polyfill if needed
4834var a = (typeof AbortController !== 'undefined')
4835 ? AbortController
4836 : function () { return {abort: function () {}}; };
4837
4838var f$1 = fetch;
4839var h = Headers;
4840
4841PouchDB.adapters = {};
4842PouchDB.preferredAdapters = [];
4843
4844PouchDB.prefix = '_pouch_';
4845
4846var eventEmitter = new events.EventEmitter();
4847
4848function setUpEventEmitter(Pouch) {
4849 Object.keys(events.EventEmitter.prototype).forEach(function (key) {
4850 if (typeof events.EventEmitter.prototype[key] === 'function') {
4851 Pouch[key] = eventEmitter[key].bind(eventEmitter);
4852 }
4853 });
4854
4855 // these are created in constructor.js, and allow us to notify each DB with
4856 // the same name that it was destroyed, via the constructor object
4857 var destructListeners = Pouch._destructionListeners = new ExportedMap();
4858
4859 Pouch.on('ref', function onConstructorRef(db) {
4860 if (!destructListeners.has(db.name)) {
4861 destructListeners.set(db.name, []);
4862 }
4863 destructListeners.get(db.name).push(db);
4864 });
4865
4866 Pouch.on('unref', function onConstructorUnref(db) {
4867 if (!destructListeners.has(db.name)) {
4868 return;
4869 }
4870 var dbList = destructListeners.get(db.name);
4871 var pos = dbList.indexOf(db);
4872 if (pos < 0) {
4873 /* istanbul ignore next */
4874 return;
4875 }
4876 dbList.splice(pos, 1);
4877 if (dbList.length > 1) {
4878 /* istanbul ignore next */
4879 destructListeners.set(db.name, dbList);
4880 } else {
4881 destructListeners["delete"](db.name);
4882 }
4883 });
4884
4885 Pouch.on('destroyed', function onConstructorDestroyed(name) {
4886 if (!destructListeners.has(name)) {
4887 return;
4888 }
4889 var dbList = destructListeners.get(name);
4890 destructListeners["delete"](name);
4891 dbList.forEach(function (db) {
4892 db.emit('destroyed',true);
4893 });
4894 });
4895}
4896
4897setUpEventEmitter(PouchDB);
4898
4899PouchDB.adapter = function (id, obj, addToPreferredAdapters) {
4900 /* istanbul ignore else */
4901 if (obj.valid()) {
4902 PouchDB.adapters[id] = obj;
4903 if (addToPreferredAdapters) {
4904 PouchDB.preferredAdapters.push(id);
4905 }
4906 }
4907};
4908
4909PouchDB.plugin = function (obj) {
4910 if (typeof obj === 'function') { // function style for plugins
4911 obj(PouchDB);
4912 } else if (typeof obj !== 'object' || Object.keys(obj).length === 0) {
4913 throw new Error('Invalid plugin: got "' + obj + '", expected an object or a function');
4914 } else {
4915 Object.keys(obj).forEach(function (id) { // object style for plugins
4916 PouchDB.prototype[id] = obj[id];
4917 });
4918 }
4919 if (this.__defaults) {
4920 PouchDB.__defaults = $inject_Object_assign({}, this.__defaults);
4921 }
4922 return PouchDB;
4923};
4924
4925PouchDB.defaults = function (defaultOpts) {
4926 function PouchAlt(name, opts) {
4927 if (!(this instanceof PouchAlt)) {
4928 return new PouchAlt(name, opts);
4929 }
4930
4931 opts = opts || {};
4932
4933 if (name && typeof name === 'object') {
4934 opts = name;
4935 name = opts.name;
4936 delete opts.name;
4937 }
4938
4939 opts = $inject_Object_assign({}, PouchAlt.__defaults, opts);
4940 PouchDB.call(this, name, opts);
4941 }
4942
4943 inherits(PouchAlt, PouchDB);
4944
4945 PouchAlt.preferredAdapters = PouchDB.preferredAdapters.slice();
4946 Object.keys(PouchDB).forEach(function (key) {
4947 if (!(key in PouchAlt)) {
4948 PouchAlt[key] = PouchDB[key];
4949 }
4950 });
4951
4952 // make default options transitive
4953 // https://github.com/pouchdb/pouchdb/issues/5922
4954 PouchAlt.__defaults = $inject_Object_assign({}, this.__defaults, defaultOpts);
4955
4956 return PouchAlt;
4957};
4958
4959PouchDB.fetch = function (url, opts) {
4960 return f$1(url, opts);
4961};
4962
4963// managed automatically by set-version.js
4964var version = "7.0.0";
4965
4966// this would just be "return doc[field]", but fields
4967// can be "deep" due to dot notation
4968function getFieldFromDoc(doc, parsedField) {
4969 var value = doc;
4970 for (var i = 0, len = parsedField.length; i < len; i++) {
4971 var key = parsedField[i];
4972 value = value[key];
4973 if (!value) {
4974 break;
4975 }
4976 }
4977 return value;
4978}
4979
4980function compare$1(left, right) {
4981 return left < right ? -1 : left > right ? 1 : 0;
4982}
4983
4984// Converts a string in dot notation to an array of its components, with backslash escaping
4985function parseField(fieldName) {
4986 // fields may be deep (e.g. "foo.bar.baz"), so parse
4987 var fields = [];
4988 var current = '';
4989 for (var i = 0, len = fieldName.length; i < len; i++) {
4990 var ch = fieldName[i];
4991 if (ch === '.') {
4992 if (i > 0 && fieldName[i - 1] === '\\') { // escaped delimiter
4993 current = current.substring(0, current.length - 1) + '.';
4994 } else { // not escaped, so delimiter
4995 fields.push(current);
4996 current = '';
4997 }
4998 } else { // normal character
4999 current += ch;
5000 }
5001 }
5002 fields.push(current);
5003 return fields;
5004}
5005
5006var combinationFields = ['$or', '$nor', '$not'];
5007function isCombinationalField(field) {
5008 return combinationFields.indexOf(field) > -1;
5009}
5010
5011function getKey(obj) {
5012 return Object.keys(obj)[0];
5013}
5014
5015function getValue(obj) {
5016 return obj[getKey(obj)];
5017}
5018
5019
5020// flatten an array of selectors joined by an $and operator
5021function mergeAndedSelectors(selectors) {
5022
5023 // sort to ensure that e.g. if the user specified
5024 // $and: [{$gt: 'a'}, {$gt: 'b'}], then it's collapsed into
5025 // just {$gt: 'b'}
5026 var res = {};
5027
5028 selectors.forEach(function (selector) {
5029 Object.keys(selector).forEach(function (field) {
5030 var matcher = selector[field];
5031 if (typeof matcher !== 'object') {
5032 matcher = {$eq: matcher};
5033 }
5034
5035 if (isCombinationalField(field)) {
5036 if (matcher instanceof Array) {
5037 res[field] = matcher.map(function (m) {
5038 return mergeAndedSelectors([m]);
5039 });
5040 } else {
5041 res[field] = mergeAndedSelectors([matcher]);
5042 }
5043 } else {
5044 var fieldMatchers = res[field] = res[field] || {};
5045 Object.keys(matcher).forEach(function (operator) {
5046 var value = matcher[operator];
5047
5048 if (operator === '$gt' || operator === '$gte') {
5049 return mergeGtGte(operator, value, fieldMatchers);
5050 } else if (operator === '$lt' || operator === '$lte') {
5051 return mergeLtLte(operator, value, fieldMatchers);
5052 } else if (operator === '$ne') {
5053 return mergeNe(value, fieldMatchers);
5054 } else if (operator === '$eq') {
5055 return mergeEq(value, fieldMatchers);
5056 }
5057 fieldMatchers[operator] = value;
5058 });
5059 }
5060 });
5061 });
5062
5063 return res;
5064}
5065
5066
5067
5068// collapse logically equivalent gt/gte values
5069function mergeGtGte(operator, value, fieldMatchers) {
5070 if (typeof fieldMatchers.$eq !== 'undefined') {
5071 return; // do nothing
5072 }
5073 if (typeof fieldMatchers.$gte !== 'undefined') {
5074 if (operator === '$gte') {
5075 if (value > fieldMatchers.$gte) { // more specificity
5076 fieldMatchers.$gte = value;
5077 }
5078 } else { // operator === '$gt'
5079 if (value >= fieldMatchers.$gte) { // more specificity
5080 delete fieldMatchers.$gte;
5081 fieldMatchers.$gt = value;
5082 }
5083 }
5084 } else if (typeof fieldMatchers.$gt !== 'undefined') {
5085 if (operator === '$gte') {
5086 if (value > fieldMatchers.$gt) { // more specificity
5087 delete fieldMatchers.$gt;
5088 fieldMatchers.$gte = value;
5089 }
5090 } else { // operator === '$gt'
5091 if (value > fieldMatchers.$gt) { // more specificity
5092 fieldMatchers.$gt = value;
5093 }
5094 }
5095 } else {
5096 fieldMatchers[operator] = value;
5097 }
5098}
5099
5100// collapse logically equivalent lt/lte values
5101function mergeLtLte(operator, value, fieldMatchers) {
5102 if (typeof fieldMatchers.$eq !== 'undefined') {
5103 return; // do nothing
5104 }
5105 if (typeof fieldMatchers.$lte !== 'undefined') {
5106 if (operator === '$lte') {
5107 if (value < fieldMatchers.$lte) { // more specificity
5108 fieldMatchers.$lte = value;
5109 }
5110 } else { // operator === '$gt'
5111 if (value <= fieldMatchers.$lte) { // more specificity
5112 delete fieldMatchers.$lte;
5113 fieldMatchers.$lt = value;
5114 }
5115 }
5116 } else if (typeof fieldMatchers.$lt !== 'undefined') {
5117 if (operator === '$lte') {
5118 if (value < fieldMatchers.$lt) { // more specificity
5119 delete fieldMatchers.$lt;
5120 fieldMatchers.$lte = value;
5121 }
5122 } else { // operator === '$gt'
5123 if (value < fieldMatchers.$lt) { // more specificity
5124 fieldMatchers.$lt = value;
5125 }
5126 }
5127 } else {
5128 fieldMatchers[operator] = value;
5129 }
5130}
5131
5132// combine $ne values into one array
5133function mergeNe(value, fieldMatchers) {
5134 if ('$ne' in fieldMatchers) {
5135 // there are many things this could "not" be
5136 fieldMatchers.$ne.push(value);
5137 } else { // doesn't exist yet
5138 fieldMatchers.$ne = [value];
5139 }
5140}
5141
5142// add $eq into the mix
5143function mergeEq(value, fieldMatchers) {
5144 // these all have less specificity than the $eq
5145 // TODO: check for user errors here
5146 delete fieldMatchers.$gt;
5147 delete fieldMatchers.$gte;
5148 delete fieldMatchers.$lt;
5149 delete fieldMatchers.$lte;
5150 delete fieldMatchers.$ne;
5151 fieldMatchers.$eq = value;
5152}
5153
5154
5155//
5156// normalize the selector
5157//
5158function massageSelector(input) {
5159 var result = clone(input);
5160 var wasAnded = false;
5161 if ('$and' in result) {
5162 result = mergeAndedSelectors(result['$and']);
5163 wasAnded = true;
5164 }
5165
5166 ['$or', '$nor'].forEach(function (orOrNor) {
5167 if (orOrNor in result) {
5168 // message each individual selector
5169 // e.g. {foo: 'bar'} becomes {foo: {$eq: 'bar'}}
5170 result[orOrNor].forEach(function (subSelector) {
5171 var fields = Object.keys(subSelector);
5172 for (var i = 0; i < fields.length; i++) {
5173 var field = fields[i];
5174 var matcher = subSelector[field];
5175 if (typeof matcher !== 'object' || matcher === null) {
5176 subSelector[field] = {$eq: matcher};
5177 }
5178 }
5179 });
5180 }
5181 });
5182
5183 if ('$not' in result) {
5184 //This feels a little like forcing, but it will work for now,
5185 //I would like to come back to this and make the merging of selectors a little more generic
5186 result['$not'] = mergeAndedSelectors([result['$not']]);
5187 }
5188
5189 var fields = Object.keys(result);
5190
5191 for (var i = 0; i < fields.length; i++) {
5192 var field = fields[i];
5193 var matcher = result[field];
5194
5195 if (typeof matcher !== 'object' || matcher === null) {
5196 matcher = {$eq: matcher};
5197 } else if ('$ne' in matcher && !wasAnded) {
5198 // I put these in an array, since there may be more than one
5199 // but in the "mergeAnded" operation, I already take care of that
5200 matcher.$ne = [matcher.$ne];
5201 }
5202 result[field] = matcher;
5203 }
5204
5205 return result;
5206}
5207
5208function pad(str, padWith, upToLength) {
5209 var padding = '';
5210 var targetLength = upToLength - str.length;
5211 /* istanbul ignore next */
5212 while (padding.length < targetLength) {
5213 padding += padWith;
5214 }
5215 return padding;
5216}
5217
5218function padLeft(str, padWith, upToLength) {
5219 var padding = pad(str, padWith, upToLength);
5220 return padding + str;
5221}
5222
5223var MIN_MAGNITUDE = -324; // verified by -Number.MIN_VALUE
5224var MAGNITUDE_DIGITS = 3; // ditto
5225var SEP = ''; // set to '_' for easier debugging
5226
5227function collate(a, b) {
5228
5229 if (a === b) {
5230 return 0;
5231 }
5232
5233 a = normalizeKey(a);
5234 b = normalizeKey(b);
5235
5236 var ai = collationIndex(a);
5237 var bi = collationIndex(b);
5238 if ((ai - bi) !== 0) {
5239 return ai - bi;
5240 }
5241 switch (typeof a) {
5242 case 'number':
5243 return a - b;
5244 case 'boolean':
5245 return a < b ? -1 : 1;
5246 case 'string':
5247 return stringCollate(a, b);
5248 }
5249 return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);
5250}
5251
5252// couch considers null/NaN/Infinity/-Infinity === undefined,
5253// for the purposes of mapreduce indexes. also, dates get stringified.
5254function normalizeKey(key) {
5255 switch (typeof key) {
5256 case 'undefined':
5257 return null;
5258 case 'number':
5259 if (key === Infinity || key === -Infinity || isNaN(key)) {
5260 return null;
5261 }
5262 return key;
5263 case 'object':
5264 var origKey = key;
5265 if (Array.isArray(key)) {
5266 var len = key.length;
5267 key = new Array(len);
5268 for (var i = 0; i < len; i++) {
5269 key[i] = normalizeKey(origKey[i]);
5270 }
5271 /* istanbul ignore next */
5272 } else if (key instanceof Date) {
5273 return key.toJSON();
5274 } else if (key !== null) { // generic object
5275 key = {};
5276 for (var k in origKey) {
5277 if (origKey.hasOwnProperty(k)) {
5278 var val = origKey[k];
5279 if (typeof val !== 'undefined') {
5280 key[k] = normalizeKey(val);
5281 }
5282 }
5283 }
5284 }
5285 }
5286 return key;
5287}
5288
5289function indexify(key) {
5290 if (key !== null) {
5291 switch (typeof key) {
5292 case 'boolean':
5293 return key ? 1 : 0;
5294 case 'number':
5295 return numToIndexableString(key);
5296 case 'string':
5297 // We've to be sure that key does not contain \u0000
5298 // Do order-preserving replacements:
5299 // 0 -> 1, 1
5300 // 1 -> 1, 2
5301 // 2 -> 2, 2
5302 /* eslint-disable no-control-regex */
5303 return key
5304 .replace(/\u0002/g, '\u0002\u0002')
5305 .replace(/\u0001/g, '\u0001\u0002')
5306 .replace(/\u0000/g, '\u0001\u0001');
5307 /* eslint-enable no-control-regex */
5308 case 'object':
5309 var isArray = Array.isArray(key);
5310 var arr = isArray ? key : Object.keys(key);
5311 var i = -1;
5312 var len = arr.length;
5313 var result = '';
5314 if (isArray) {
5315 while (++i < len) {
5316 result += toIndexableString(arr[i]);
5317 }
5318 } else {
5319 while (++i < len) {
5320 var objKey = arr[i];
5321 result += toIndexableString(objKey) +
5322 toIndexableString(key[objKey]);
5323 }
5324 }
5325 return result;
5326 }
5327 }
5328 return '';
5329}
5330
5331// convert the given key to a string that would be appropriate
5332// for lexical sorting, e.g. within a database, where the
5333// sorting is the same given by the collate() function.
5334function toIndexableString(key) {
5335 var zero = '\u0000';
5336 key = normalizeKey(key);
5337 return collationIndex(key) + SEP + indexify(key) + zero;
5338}
5339
5340function parseNumber(str, i) {
5341 var originalIdx = i;
5342 var num;
5343 var zero = str[i] === '1';
5344 if (zero) {
5345 num = 0;
5346 i++;
5347 } else {
5348 var neg = str[i] === '0';
5349 i++;
5350 var numAsString = '';
5351 var magAsString = str.substring(i, i + MAGNITUDE_DIGITS);
5352 var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE;
5353 /* istanbul ignore next */
5354 if (neg) {
5355 magnitude = -magnitude;
5356 }
5357 i += MAGNITUDE_DIGITS;
5358 while (true) {
5359 var ch = str[i];
5360 if (ch === '\u0000') {
5361 break;
5362 } else {
5363 numAsString += ch;
5364 }
5365 i++;
5366 }
5367 numAsString = numAsString.split('.');
5368 if (numAsString.length === 1) {
5369 num = parseInt(numAsString, 10);
5370 } else {
5371 /* istanbul ignore next */
5372 num = parseFloat(numAsString[0] + '.' + numAsString[1]);
5373 }
5374 /* istanbul ignore next */
5375 if (neg) {
5376 num = num - 10;
5377 }
5378 /* istanbul ignore next */
5379 if (magnitude !== 0) {
5380 // parseFloat is more reliable than pow due to rounding errors
5381 // e.g. Number.MAX_VALUE would return Infinity if we did
5382 // num * Math.pow(10, magnitude);
5383 num = parseFloat(num + 'e' + magnitude);
5384 }
5385 }
5386 return {num: num, length : i - originalIdx};
5387}
5388
5389// move up the stack while parsing
5390// this function moved outside of parseIndexableString for performance
5391function pop(stack, metaStack) {
5392 var obj = stack.pop();
5393
5394 if (metaStack.length) {
5395 var lastMetaElement = metaStack[metaStack.length - 1];
5396 if (obj === lastMetaElement.element) {
5397 // popping a meta-element, e.g. an object whose value is another object
5398 metaStack.pop();
5399 lastMetaElement = metaStack[metaStack.length - 1];
5400 }
5401 var element = lastMetaElement.element;
5402 var lastElementIndex = lastMetaElement.index;
5403 if (Array.isArray(element)) {
5404 element.push(obj);
5405 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
5406 var key = stack.pop();
5407 element[key] = obj;
5408 } else {
5409 stack.push(obj); // obj with key only
5410 }
5411 }
5412}
5413
5414function parseIndexableString(str) {
5415 var stack = [];
5416 var metaStack = []; // stack for arrays and objects
5417 var i = 0;
5418
5419 /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
5420 while (true) {
5421 var collationIndex = str[i++];
5422 if (collationIndex === '\u0000') {
5423 if (stack.length === 1) {
5424 return stack.pop();
5425 } else {
5426 pop(stack, metaStack);
5427 continue;
5428 }
5429 }
5430 switch (collationIndex) {
5431 case '1':
5432 stack.push(null);
5433 break;
5434 case '2':
5435 stack.push(str[i] === '1');
5436 i++;
5437 break;
5438 case '3':
5439 var parsedNum = parseNumber(str, i);
5440 stack.push(parsedNum.num);
5441 i += parsedNum.length;
5442 break;
5443 case '4':
5444 var parsedStr = '';
5445 /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
5446 while (true) {
5447 var ch = str[i];
5448 if (ch === '\u0000') {
5449 break;
5450 }
5451 parsedStr += ch;
5452 i++;
5453 }
5454 // perform the reverse of the order-preserving replacement
5455 // algorithm (see above)
5456 /* eslint-disable no-control-regex */
5457 parsedStr = parsedStr.replace(/\u0001\u0001/g, '\u0000')
5458 .replace(/\u0001\u0002/g, '\u0001')
5459 .replace(/\u0002\u0002/g, '\u0002');
5460 /* eslint-enable no-control-regex */
5461 stack.push(parsedStr);
5462 break;
5463 case '5':
5464 var arrayElement = { element: [], index: stack.length };
5465 stack.push(arrayElement.element);
5466 metaStack.push(arrayElement);
5467 break;
5468 case '6':
5469 var objElement = { element: {}, index: stack.length };
5470 stack.push(objElement.element);
5471 metaStack.push(objElement);
5472 break;
5473 /* istanbul ignore next */
5474 default:
5475 throw new Error(
5476 'bad collationIndex or unexpectedly reached end of input: ' +
5477 collationIndex);
5478 }
5479 }
5480}
5481
5482function arrayCollate(a, b) {
5483 var len = Math.min(a.length, b.length);
5484 for (var i = 0; i < len; i++) {
5485 var sort = collate(a[i], b[i]);
5486 if (sort !== 0) {
5487 return sort;
5488 }
5489 }
5490 return (a.length === b.length) ? 0 :
5491 (a.length > b.length) ? 1 : -1;
5492}
5493function stringCollate(a, b) {
5494 // See: https://github.com/daleharvey/pouchdb/issues/40
5495 // This is incompatible with the CouchDB implementation, but its the
5496 // best we can do for now
5497 return (a === b) ? 0 : ((a > b) ? 1 : -1);
5498}
5499function objectCollate(a, b) {
5500 var ak = Object.keys(a), bk = Object.keys(b);
5501 var len = Math.min(ak.length, bk.length);
5502 for (var i = 0; i < len; i++) {
5503 // First sort the keys
5504 var sort = collate(ak[i], bk[i]);
5505 if (sort !== 0) {
5506 return sort;
5507 }
5508 // if the keys are equal sort the values
5509 sort = collate(a[ak[i]], b[bk[i]]);
5510 if (sort !== 0) {
5511 return sort;
5512 }
5513
5514 }
5515 return (ak.length === bk.length) ? 0 :
5516 (ak.length > bk.length) ? 1 : -1;
5517}
5518// The collation is defined by erlangs ordered terms
5519// the atoms null, true, false come first, then numbers, strings,
5520// arrays, then objects
5521// null/undefined/NaN/Infinity/-Infinity are all considered null
5522function collationIndex(x) {
5523 var id = ['boolean', 'number', 'string', 'object'];
5524 var idx = id.indexOf(typeof x);
5525 //false if -1 otherwise true, but fast!!!!1
5526 if (~idx) {
5527 if (x === null) {
5528 return 1;
5529 }
5530 if (Array.isArray(x)) {
5531 return 5;
5532 }
5533 return idx < 3 ? (idx + 2) : (idx + 3);
5534 }
5535 /* istanbul ignore next */
5536 if (Array.isArray(x)) {
5537 return 5;
5538 }
5539}
5540
5541// conversion:
5542// x yyy zz...zz
5543// x = 0 for negative, 1 for 0, 2 for positive
5544// y = exponent (for negative numbers negated) moved so that it's >= 0
5545// z = mantisse
5546function numToIndexableString(num) {
5547
5548 if (num === 0) {
5549 return '1';
5550 }
5551
5552 // convert number to exponential format for easier and
5553 // more succinct string sorting
5554 var expFormat = num.toExponential().split(/e\+?/);
5555 var magnitude = parseInt(expFormat[1], 10);
5556
5557 var neg = num < 0;
5558
5559 var result = neg ? '0' : '2';
5560
5561 // first sort by magnitude
5562 // it's easier if all magnitudes are positive
5563 var magForComparison = ((neg ? -magnitude : magnitude) - MIN_MAGNITUDE);
5564 var magString = padLeft((magForComparison).toString(), '0', MAGNITUDE_DIGITS);
5565
5566 result += SEP + magString;
5567
5568 // then sort by the factor
5569 var factor = Math.abs(parseFloat(expFormat[0])); // [1..10)
5570 /* istanbul ignore next */
5571 if (neg) { // for negative reverse ordering
5572 factor = 10 - factor;
5573 }
5574
5575 var factorStr = factor.toFixed(20);
5576
5577 // strip zeros from the end
5578 factorStr = factorStr.replace(/\.?0+$/, '');
5579
5580 result += SEP + factorStr;
5581
5582 return result;
5583}
5584
5585// create a comparator based on the sort object
5586function createFieldSorter(sort) {
5587
5588 function getFieldValuesAsArray(doc) {
5589 return sort.map(function (sorting) {
5590 var fieldName = getKey(sorting);
5591 var parsedField = parseField(fieldName);
5592 var docFieldValue = getFieldFromDoc(doc, parsedField);
5593 return docFieldValue;
5594 });
5595 }
5596
5597 return function (aRow, bRow) {
5598 var aFieldValues = getFieldValuesAsArray(aRow.doc);
5599 var bFieldValues = getFieldValuesAsArray(bRow.doc);
5600 var collation = collate(aFieldValues, bFieldValues);
5601 if (collation !== 0) {
5602 return collation;
5603 }
5604 // this is what mango seems to do
5605 return compare$1(aRow.doc._id, bRow.doc._id);
5606 };
5607}
5608
5609function filterInMemoryFields(rows, requestDef, inMemoryFields) {
5610 rows = rows.filter(function (row) {
5611 return rowFilter(row.doc, requestDef.selector, inMemoryFields);
5612 });
5613
5614 if (requestDef.sort) {
5615 // in-memory sort
5616 var fieldSorter = createFieldSorter(requestDef.sort);
5617 rows = rows.sort(fieldSorter);
5618 if (typeof requestDef.sort[0] !== 'string' &&
5619 getValue(requestDef.sort[0]) === 'desc') {
5620 rows = rows.reverse();
5621 }
5622 }
5623
5624 if ('limit' in requestDef || 'skip' in requestDef) {
5625 // have to do the limit in-memory
5626 var skip = requestDef.skip || 0;
5627 var limit = ('limit' in requestDef ? requestDef.limit : rows.length) + skip;
5628 rows = rows.slice(skip, limit);
5629 }
5630 return rows;
5631}
5632
5633function rowFilter(doc, selector, inMemoryFields) {
5634 return inMemoryFields.every(function (field) {
5635 var matcher = selector[field];
5636 var parsedField = parseField(field);
5637 var docFieldValue = getFieldFromDoc(doc, parsedField);
5638 if (isCombinationalField(field)) {
5639 return matchCominationalSelector(field, matcher, doc);
5640 }
5641
5642 return matchSelector(matcher, doc, parsedField, docFieldValue);
5643 });
5644}
5645
5646function matchSelector(matcher, doc, parsedField, docFieldValue) {
5647 if (!matcher) {
5648 // no filtering necessary; this field is just needed for sorting
5649 return true;
5650 }
5651
5652 return Object.keys(matcher).every(function (userOperator) {
5653 var userValue = matcher[userOperator];
5654 return match(userOperator, doc, userValue, parsedField, docFieldValue);
5655 });
5656}
5657
5658function matchCominationalSelector(field, matcher, doc) {
5659
5660 if (field === '$or') {
5661 return matcher.some(function (orMatchers) {
5662 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
5663 });
5664 }
5665
5666 if (field === '$not') {
5667 return !rowFilter(doc, matcher, Object.keys(matcher));
5668 }
5669
5670 //`$nor`
5671 return !matcher.find(function (orMatchers) {
5672 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
5673 });
5674
5675}
5676
5677function match(userOperator, doc, userValue, parsedField, docFieldValue) {
5678 if (!matchers[userOperator]) {
5679 throw new Error('unknown operator "' + userOperator +
5680 '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, ' +
5681 '$nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
5682 }
5683 return matchers[userOperator](doc, userValue, parsedField, docFieldValue);
5684}
5685
5686function fieldExists(docFieldValue) {
5687 return typeof docFieldValue !== 'undefined' && docFieldValue !== null;
5688}
5689
5690function fieldIsNotUndefined(docFieldValue) {
5691 return typeof docFieldValue !== 'undefined';
5692}
5693
5694function modField(docFieldValue, userValue) {
5695 var divisor = userValue[0];
5696 var mod = userValue[1];
5697 if (divisor === 0) {
5698 throw new Error('Bad divisor, cannot divide by zero');
5699 }
5700
5701 if (parseInt(divisor, 10) !== divisor ) {
5702 throw new Error('Divisor is not an integer');
5703 }
5704
5705 if (parseInt(mod, 10) !== mod ) {
5706 throw new Error('Modulus is not an integer');
5707 }
5708
5709 if (parseInt(docFieldValue, 10) !== docFieldValue) {
5710 return false;
5711 }
5712
5713 return docFieldValue % divisor === mod;
5714}
5715
5716function arrayContainsValue(docFieldValue, userValue) {
5717 return userValue.some(function (val) {
5718 if (docFieldValue instanceof Array) {
5719 return docFieldValue.indexOf(val) > -1;
5720 }
5721
5722 return docFieldValue === val;
5723 });
5724}
5725
5726function arrayContainsAllValues(docFieldValue, userValue) {
5727 return userValue.every(function (val) {
5728 return docFieldValue.indexOf(val) > -1;
5729 });
5730}
5731
5732function arraySize(docFieldValue, userValue) {
5733 return docFieldValue.length === userValue;
5734}
5735
5736function regexMatch(docFieldValue, userValue) {
5737 var re = new RegExp(userValue);
5738
5739 return re.test(docFieldValue);
5740}
5741
5742function typeMatch(docFieldValue, userValue) {
5743
5744 switch (userValue) {
5745 case 'null':
5746 return docFieldValue === null;
5747 case 'boolean':
5748 return typeof (docFieldValue) === 'boolean';
5749 case 'number':
5750 return typeof (docFieldValue) === 'number';
5751 case 'string':
5752 return typeof (docFieldValue) === 'string';
5753 case 'array':
5754 return docFieldValue instanceof Array;
5755 case 'object':
5756 return ({}).toString.call(docFieldValue) === '[object Object]';
5757 }
5758
5759 throw new Error(userValue + ' not supported as a type.' +
5760 'Please use one of object, string, array, number, boolean or null.');
5761
5762}
5763
5764var matchers = {
5765
5766 '$elemMatch': function (doc, userValue, parsedField, docFieldValue) {
5767 if (!Array.isArray(docFieldValue)) {
5768 return false;
5769 }
5770
5771 if (docFieldValue.length === 0) {
5772 return false;
5773 }
5774
5775 if (typeof docFieldValue[0] === 'object') {
5776 return docFieldValue.some(function (val) {
5777 return rowFilter(val, userValue, Object.keys(userValue));
5778 });
5779 }
5780
5781 return docFieldValue.some(function (val) {
5782 return matchSelector(userValue, doc, parsedField, val);
5783 });
5784 },
5785
5786 '$allMatch': function (doc, userValue, parsedField, docFieldValue) {
5787 if (!Array.isArray(docFieldValue)) {
5788 return false;
5789 }
5790
5791 /* istanbul ignore next */
5792 if (docFieldValue.length === 0) {
5793 return false;
5794 }
5795
5796 if (typeof docFieldValue[0] === 'object') {
5797 return docFieldValue.every(function (val) {
5798 return rowFilter(val, userValue, Object.keys(userValue));
5799 });
5800 }
5801
5802 return docFieldValue.every(function (val) {
5803 return matchSelector(userValue, doc, parsedField, val);
5804 });
5805 },
5806
5807 '$eq': function (doc, userValue, parsedField, docFieldValue) {
5808 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0;
5809 },
5810
5811 '$gte': function (doc, userValue, parsedField, docFieldValue) {
5812 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0;
5813 },
5814
5815 '$gt': function (doc, userValue, parsedField, docFieldValue) {
5816 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0;
5817 },
5818
5819 '$lte': function (doc, userValue, parsedField, docFieldValue) {
5820 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0;
5821 },
5822
5823 '$lt': function (doc, userValue, parsedField, docFieldValue) {
5824 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0;
5825 },
5826
5827 '$exists': function (doc, userValue, parsedField, docFieldValue) {
5828 //a field that is null is still considered to exist
5829 if (userValue) {
5830 return fieldIsNotUndefined(docFieldValue);
5831 }
5832
5833 return !fieldIsNotUndefined(docFieldValue);
5834 },
5835
5836 '$mod': function (doc, userValue, parsedField, docFieldValue) {
5837 return fieldExists(docFieldValue) && modField(docFieldValue, userValue);
5838 },
5839
5840 '$ne': function (doc, userValue, parsedField, docFieldValue) {
5841 return userValue.every(function (neValue) {
5842 return collate(docFieldValue, neValue) !== 0;
5843 });
5844 },
5845 '$in': function (doc, userValue, parsedField, docFieldValue) {
5846 return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue);
5847 },
5848
5849 '$nin': function (doc, userValue, parsedField, docFieldValue) {
5850 return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue);
5851 },
5852
5853 '$size': function (doc, userValue, parsedField, docFieldValue) {
5854 return fieldExists(docFieldValue) && arraySize(docFieldValue, userValue);
5855 },
5856
5857 '$all': function (doc, userValue, parsedField, docFieldValue) {
5858 return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue);
5859 },
5860
5861 '$regex': function (doc, userValue, parsedField, docFieldValue) {
5862 return fieldExists(docFieldValue) && regexMatch(docFieldValue, userValue);
5863 },
5864
5865 '$type': function (doc, userValue, parsedField, docFieldValue) {
5866 return typeMatch(docFieldValue, userValue);
5867 }
5868};
5869
5870// return true if the given doc matches the supplied selector
5871function matchesSelector(doc, selector) {
5872 /* istanbul ignore if */
5873 if (typeof selector !== 'object') {
5874 // match the CouchDB error message
5875 throw new Error('Selector error: expected a JSON object');
5876 }
5877
5878 selector = massageSelector(selector);
5879 var row = {
5880 'doc': doc
5881 };
5882
5883 var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));
5884 return rowsMatched && rowsMatched.length === 1;
5885}
5886
5887function evalFilter(input) {
5888 return scopeEval('"use strict";\nreturn ' + input + ';', {});
5889}
5890
5891function evalView(input) {
5892 var code = [
5893 'return function(doc) {',
5894 ' "use strict";',
5895 ' var emitted = false;',
5896 ' var emit = function (a, b) {',
5897 ' emitted = true;',
5898 ' };',
5899 ' var view = ' + input + ';',
5900 ' view(doc);',
5901 ' if (emitted) {',
5902 ' return true;',
5903 ' }',
5904 '};'
5905 ].join('\n');
5906
5907 return scopeEval(code, {});
5908}
5909
5910function validate(opts, callback) {
5911 if (opts.selector) {
5912 if (opts.filter && opts.filter !== '_selector') {
5913 var filterName = typeof opts.filter === 'string' ?
5914 opts.filter : 'function';
5915 return callback(new Error('selector invalid for filter "' + filterName + '"'));
5916 }
5917 }
5918 callback();
5919}
5920
5921function normalize(opts) {
5922 if (opts.view && !opts.filter) {
5923 opts.filter = '_view';
5924 }
5925
5926 if (opts.selector && !opts.filter) {
5927 opts.filter = '_selector';
5928 }
5929
5930 if (opts.filter && typeof opts.filter === 'string') {
5931 if (opts.filter === '_view') {
5932 opts.view = normalizeDesignDocFunctionName(opts.view);
5933 } else {
5934 opts.filter = normalizeDesignDocFunctionName(opts.filter);
5935 }
5936 }
5937}
5938
5939function shouldFilter(changesHandler, opts) {
5940 return opts.filter && typeof opts.filter === 'string' &&
5941 !opts.doc_ids && !isRemote(changesHandler.db);
5942}
5943
5944function filter(changesHandler, opts) {
5945 var callback = opts.complete;
5946 if (opts.filter === '_view') {
5947 if (!opts.view || typeof opts.view !== 'string') {
5948 var err = createError(BAD_REQUEST,
5949 '`view` filter parameter not found or invalid.');
5950 return callback(err);
5951 }
5952 // fetch a view from a design doc, make it behave like a filter
5953 var viewName = parseDesignDocFunctionName(opts.view);
5954 changesHandler.db.get('_design/' + viewName[0], function (err, ddoc) {
5955 /* istanbul ignore if */
5956 if (changesHandler.isCancelled) {
5957 return callback(null, {status: 'cancelled'});
5958 }
5959 /* istanbul ignore next */
5960 if (err) {
5961 return callback(generateErrorFromResponse(err));
5962 }
5963 var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&
5964 ddoc.views[viewName[1]].map;
5965 if (!mapFun) {
5966 return callback(createError(MISSING_DOC,
5967 (ddoc.views ? 'missing json key: ' + viewName[1] :
5968 'missing json key: views')));
5969 }
5970 opts.filter = evalView(mapFun);
5971 changesHandler.doChanges(opts);
5972 });
5973 } else if (opts.selector) {
5974 opts.filter = function (doc) {
5975 return matchesSelector(doc, opts.selector);
5976 };
5977 changesHandler.doChanges(opts);
5978 } else {
5979 // fetch a filter from a design doc
5980 var filterName = parseDesignDocFunctionName(opts.filter);
5981 changesHandler.db.get('_design/' + filterName[0], function (err, ddoc) {
5982 /* istanbul ignore if */
5983 if (changesHandler.isCancelled) {
5984 return callback(null, {status: 'cancelled'});
5985 }
5986 /* istanbul ignore next */
5987 if (err) {
5988 return callback(generateErrorFromResponse(err));
5989 }
5990 var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];
5991 if (!filterFun) {
5992 return callback(createError(MISSING_DOC,
5993 ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]
5994 : 'missing json key: filters')));
5995 }
5996 opts.filter = evalFilter(filterFun);
5997 changesHandler.doChanges(opts);
5998 });
5999 }
6000}
6001
6002function applyChangesFilterPlugin(PouchDB) {
6003 PouchDB._changesFilterPlugin = {
6004 validate: validate,
6005 normalize: normalize,
6006 shouldFilter: shouldFilter,
6007 filter: filter
6008 };
6009}
6010
6011// TODO: remove from pouchdb-core (breaking)
6012PouchDB.plugin(applyChangesFilterPlugin);
6013
6014PouchDB.version = version;
6015
6016function toObject(array) {
6017 return array.reduce(function (obj, item) {
6018 obj[item] = true;
6019 return obj;
6020 }, {});
6021}
6022// List of top level reserved words for doc
6023var reservedWords = toObject([
6024 '_id',
6025 '_rev',
6026 '_attachments',
6027 '_deleted',
6028 '_revisions',
6029 '_revs_info',
6030 '_conflicts',
6031 '_deleted_conflicts',
6032 '_local_seq',
6033 '_rev_tree',
6034 //replication documents
6035 '_replication_id',
6036 '_replication_state',
6037 '_replication_state_time',
6038 '_replication_state_reason',
6039 '_replication_stats',
6040 // Specific to Couchbase Sync Gateway
6041 '_removed'
6042]);
6043
6044// List of reserved words that should end up the document
6045var dataWords = toObject([
6046 '_attachments',
6047 //replication documents
6048 '_replication_id',
6049 '_replication_state',
6050 '_replication_state_time',
6051 '_replication_state_reason',
6052 '_replication_stats'
6053]);
6054
6055function parseRevisionInfo(rev) {
6056 if (!/^\d+-./.test(rev)) {
6057 return createError(INVALID_REV);
6058 }
6059 var idx = rev.indexOf('-');
6060 var left = rev.substring(0, idx);
6061 var right = rev.substring(idx + 1);
6062 return {
6063 prefix: parseInt(left, 10),
6064 id: right
6065 };
6066}
6067
6068function makeRevTreeFromRevisions(revisions, opts) {
6069 var pos = revisions.start - revisions.ids.length + 1;
6070
6071 var revisionIds = revisions.ids;
6072 var ids = [revisionIds[0], opts, []];
6073
6074 for (var i = 1, len = revisionIds.length; i < len; i++) {
6075 ids = [revisionIds[i], {status: 'missing'}, [ids]];
6076 }
6077
6078 return [{
6079 pos: pos,
6080 ids: ids
6081 }];
6082}
6083
6084// Preprocess documents, parse their revisions, assign an id and a
6085// revision for new writes that are missing them, etc
6086function parseDoc(doc, newEdits, dbOpts) {
6087 if (!dbOpts) {
6088 dbOpts = {
6089 deterministic_revs: true
6090 };
6091 }
6092
6093 var nRevNum;
6094 var newRevId;
6095 var revInfo;
6096 var opts = {status: 'available'};
6097 if (doc._deleted) {
6098 opts.deleted = true;
6099 }
6100
6101 if (newEdits) {
6102 if (!doc._id) {
6103 doc._id = uuid();
6104 }
6105 newRevId = rev$$1(doc, dbOpts.deterministic_revs);
6106 if (doc._rev) {
6107 revInfo = parseRevisionInfo(doc._rev);
6108 if (revInfo.error) {
6109 return revInfo;
6110 }
6111 doc._rev_tree = [{
6112 pos: revInfo.prefix,
6113 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
6114 }];
6115 nRevNum = revInfo.prefix + 1;
6116 } else {
6117 doc._rev_tree = [{
6118 pos: 1,
6119 ids : [newRevId, opts, []]
6120 }];
6121 nRevNum = 1;
6122 }
6123 } else {
6124 if (doc._revisions) {
6125 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
6126 nRevNum = doc._revisions.start;
6127 newRevId = doc._revisions.ids[0];
6128 }
6129 if (!doc._rev_tree) {
6130 revInfo = parseRevisionInfo(doc._rev);
6131 if (revInfo.error) {
6132 return revInfo;
6133 }
6134 nRevNum = revInfo.prefix;
6135 newRevId = revInfo.id;
6136 doc._rev_tree = [{
6137 pos: nRevNum,
6138 ids: [newRevId, opts, []]
6139 }];
6140 }
6141 }
6142
6143 invalidIdError(doc._id);
6144
6145 doc._rev = nRevNum + '-' + newRevId;
6146
6147 var result = {metadata : {}, data : {}};
6148 for (var key in doc) {
6149 /* istanbul ignore else */
6150 if (Object.prototype.hasOwnProperty.call(doc, key)) {
6151 var specialKey = key[0] === '_';
6152 if (specialKey && !reservedWords[key]) {
6153 var error = createError(DOC_VALIDATION, key);
6154 error.message = DOC_VALIDATION.message + ': ' + key;
6155 throw error;
6156 } else if (specialKey && !dataWords[key]) {
6157 result.metadata[key.slice(1)] = doc[key];
6158 } else {
6159 result.data[key] = doc[key];
6160 }
6161 }
6162 }
6163 return result;
6164}
6165
6166function parseBase64(data) {
6167 try {
6168 return thisAtob(data);
6169 } catch (e) {
6170 var err = createError(BAD_ARG,
6171 'Attachment is not a valid base64 string');
6172 return {error: err};
6173 }
6174}
6175
6176function preprocessString(att, blobType, callback) {
6177 var asBinary = parseBase64(att.data);
6178 if (asBinary.error) {
6179 return callback(asBinary.error);
6180 }
6181
6182 att.length = asBinary.length;
6183 if (blobType === 'blob') {
6184 att.data = binStringToBluffer(asBinary, att.content_type);
6185 } else if (blobType === 'base64') {
6186 att.data = thisBtoa(asBinary);
6187 } else { // binary
6188 att.data = asBinary;
6189 }
6190 binaryMd5(asBinary, function (result) {
6191 att.digest = 'md5-' + result;
6192 callback();
6193 });
6194}
6195
6196function preprocessBlob(att, blobType, callback) {
6197 binaryMd5(att.data, function (md5) {
6198 att.digest = 'md5-' + md5;
6199 // size is for blobs (browser), length is for buffers (node)
6200 att.length = att.data.size || att.data.length || 0;
6201 if (blobType === 'binary') {
6202 blobToBinaryString(att.data, function (binString) {
6203 att.data = binString;
6204 callback();
6205 });
6206 } else if (blobType === 'base64') {
6207 blobToBase64(att.data, function (b64) {
6208 att.data = b64;
6209 callback();
6210 });
6211 } else {
6212 callback();
6213 }
6214 });
6215}
6216
6217function preprocessAttachment(att, blobType, callback) {
6218 if (att.stub) {
6219 return callback();
6220 }
6221 if (typeof att.data === 'string') { // input is a base64 string
6222 preprocessString(att, blobType, callback);
6223 } else { // input is a blob
6224 preprocessBlob(att, blobType, callback);
6225 }
6226}
6227
6228function preprocessAttachments(docInfos, blobType, callback) {
6229
6230 if (!docInfos.length) {
6231 return callback();
6232 }
6233
6234 var docv = 0;
6235 var overallErr;
6236
6237 docInfos.forEach(function (docInfo) {
6238 var attachments = docInfo.data && docInfo.data._attachments ?
6239 Object.keys(docInfo.data._attachments) : [];
6240 var recv = 0;
6241
6242 if (!attachments.length) {
6243 return done();
6244 }
6245
6246 function processedAttachment(err) {
6247 overallErr = err;
6248 recv++;
6249 if (recv === attachments.length) {
6250 done();
6251 }
6252 }
6253
6254 for (var key in docInfo.data._attachments) {
6255 if (docInfo.data._attachments.hasOwnProperty(key)) {
6256 preprocessAttachment(docInfo.data._attachments[key],
6257 blobType, processedAttachment);
6258 }
6259 }
6260 });
6261
6262 function done() {
6263 docv++;
6264 if (docInfos.length === docv) {
6265 if (overallErr) {
6266 callback(overallErr);
6267 } else {
6268 callback();
6269 }
6270 }
6271 }
6272}
6273
6274function updateDoc(revLimit, prev, docInfo, results,
6275 i, cb, writeDoc, newEdits) {
6276
6277 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
6278 results[i] = docInfo;
6279 return cb();
6280 }
6281
6282 // sometimes this is pre-calculated. historically not always
6283 var previousWinningRev = prev.winningRev || winningRev(prev);
6284 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
6285 isDeleted(prev, previousWinningRev);
6286 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
6287 isDeleted(docInfo.metadata);
6288 var isRoot = /^1-/.test(docInfo.metadata.rev);
6289
6290 if (previouslyDeleted && !deleted && newEdits && isRoot) {
6291 var newDoc = docInfo.data;
6292 newDoc._rev = previousWinningRev;
6293 newDoc._id = docInfo.metadata.id;
6294 docInfo = parseDoc(newDoc, newEdits);
6295 }
6296
6297 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
6298
6299 var inConflict = newEdits && ((
6300 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
6301 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
6302 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
6303
6304 if (inConflict) {
6305 var err = createError(REV_CONFLICT);
6306 results[i] = err;
6307 return cb();
6308 }
6309
6310 var newRev = docInfo.metadata.rev;
6311 docInfo.metadata.rev_tree = merged.tree;
6312 docInfo.stemmedRevs = merged.stemmedRevs || [];
6313 /* istanbul ignore else */
6314 if (prev.rev_map) {
6315 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
6316 }
6317
6318 // recalculate
6319 var winningRev$$1 = winningRev(docInfo.metadata);
6320 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
6321
6322 // calculate the total number of documents that were added/removed,
6323 // from the perspective of total_rows/doc_count
6324 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
6325 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
6326
6327 var newRevIsDeleted;
6328 if (newRev === winningRev$$1) {
6329 // if the new rev is the same as the winning rev, we can reuse that value
6330 newRevIsDeleted = winningRevIsDeleted;
6331 } else {
6332 // if they're not the same, then we need to recalculate
6333 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
6334 }
6335
6336 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
6337 true, delta, i, cb);
6338}
6339
6340function rootIsMissing(docInfo) {
6341 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
6342}
6343
6344function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
6345 writeDoc, opts, overallCallback) {
6346
6347 // Default to 1000 locally
6348 revLimit = revLimit || 1000;
6349
6350 function insertDoc(docInfo, resultsIdx, callback) {
6351 // Cant insert new deleted documents
6352 var winningRev$$1 = winningRev(docInfo.metadata);
6353 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
6354 if ('was_delete' in opts && deleted) {
6355 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
6356 return callback();
6357 }
6358
6359 // 4712 - detect whether a new document was inserted with a _rev
6360 var inConflict = newEdits && rootIsMissing(docInfo);
6361
6362 if (inConflict) {
6363 var err = createError(REV_CONFLICT);
6364 results[resultsIdx] = err;
6365 return callback();
6366 }
6367
6368 var delta = deleted ? 0 : 1;
6369
6370 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
6371 delta, resultsIdx, callback);
6372 }
6373
6374 var newEdits = opts.new_edits;
6375 var idsToDocs = new ExportedMap();
6376
6377 var docsDone = 0;
6378 var docsToDo = docInfos.length;
6379
6380 function checkAllDocsDone() {
6381 if (++docsDone === docsToDo && overallCallback) {
6382 overallCallback();
6383 }
6384 }
6385
6386 docInfos.forEach(function (currentDoc, resultsIdx) {
6387
6388 if (currentDoc._id && isLocalId(currentDoc._id)) {
6389 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
6390 api[fun](currentDoc, {ctx: tx}, function (err, res) {
6391 results[resultsIdx] = err || res;
6392 checkAllDocsDone();
6393 });
6394 return;
6395 }
6396
6397 var id = currentDoc.metadata.id;
6398 if (idsToDocs.has(id)) {
6399 docsToDo--; // duplicate
6400 idsToDocs.get(id).push([currentDoc, resultsIdx]);
6401 } else {
6402 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
6403 }
6404 });
6405
6406 // in the case of new_edits, the user can provide multiple docs
6407 // with the same id. these need to be processed sequentially
6408 idsToDocs.forEach(function (docs, id) {
6409 var numDone = 0;
6410
6411 function docWritten() {
6412 if (++numDone < docs.length) {
6413 nextDoc();
6414 } else {
6415 checkAllDocsDone();
6416 }
6417 }
6418 function nextDoc() {
6419 var value = docs[numDone];
6420 var currentDoc = value[0];
6421 var resultsIdx = value[1];
6422
6423 if (fetchedDocs.has(id)) {
6424 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
6425 resultsIdx, docWritten, writeDoc, newEdits);
6426 } else {
6427 // Ensure stemming applies to new writes as well
6428 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
6429 currentDoc.metadata.rev_tree = merged.tree;
6430 currentDoc.stemmedRevs = merged.stemmedRevs || [];
6431 insertDoc(currentDoc, resultsIdx, docWritten);
6432 }
6433 }
6434 nextDoc();
6435 });
6436}
6437
6438// IndexedDB requires a versioned database structure, so we use the
6439// version here to manage migrations.
6440var ADAPTER_VERSION = 5;
6441
6442// The object stores created for each database
6443// DOC_STORE stores the document meta data, its revision history and state
6444// Keyed by document id
6445var DOC_STORE = 'document-store';
6446// BY_SEQ_STORE stores a particular version of a document, keyed by its
6447// sequence id
6448var BY_SEQ_STORE = 'by-sequence';
6449// Where we store attachments
6450var ATTACH_STORE = 'attach-store';
6451// Where we store many-to-many relations
6452// between attachment digests and seqs
6453var ATTACH_AND_SEQ_STORE = 'attach-seq-store';
6454
6455// Where we store database-wide meta data in a single record
6456// keyed by id: META_STORE
6457var META_STORE = 'meta-store';
6458// Where we store local documents
6459var LOCAL_STORE = 'local-store';
6460// Where we detect blob support
6461var DETECT_BLOB_SUPPORT_STORE = 'detect-blob-support';
6462
6463function safeJsonParse(str) {
6464 // This try/catch guards against stack overflow errors.
6465 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
6466 // cannot overflow.
6467 try {
6468 return JSON.parse(str);
6469 } catch (e) {
6470 /* istanbul ignore next */
6471 return vuvuzela.parse(str);
6472 }
6473}
6474
6475function safeJsonStringify(json) {
6476 try {
6477 return JSON.stringify(json);
6478 } catch (e) {
6479 /* istanbul ignore next */
6480 return vuvuzela.stringify(json);
6481 }
6482}
6483
6484function idbError(callback) {
6485 return function (evt) {
6486 var message = 'unknown_error';
6487 if (evt.target && evt.target.error) {
6488 message = evt.target.error.name || evt.target.error.message;
6489 }
6490 callback(createError(IDB_ERROR, message, evt.type));
6491 };
6492}
6493
6494// Unfortunately, the metadata has to be stringified
6495// when it is put into the database, because otherwise
6496// IndexedDB can throw errors for deeply-nested objects.
6497// Originally we just used JSON.parse/JSON.stringify; now
6498// we use this custom vuvuzela library that avoids recursion.
6499// If we could do it all over again, we'd probably use a
6500// format for the revision trees other than JSON.
6501function encodeMetadata(metadata, winningRev, deleted) {
6502 return {
6503 data: safeJsonStringify(metadata),
6504 winningRev: winningRev,
6505 deletedOrLocal: deleted ? '1' : '0',
6506 seq: metadata.seq, // highest seq for this doc
6507 id: metadata.id
6508 };
6509}
6510
6511function decodeMetadata(storedObject) {
6512 if (!storedObject) {
6513 return null;
6514 }
6515 var metadata = safeJsonParse(storedObject.data);
6516 metadata.winningRev = storedObject.winningRev;
6517 metadata.deleted = storedObject.deletedOrLocal === '1';
6518 metadata.seq = storedObject.seq;
6519 return metadata;
6520}
6521
6522// read the doc back out from the database. we don't store the
6523// _id or _rev because we already have _doc_id_rev.
6524function decodeDoc(doc) {
6525 if (!doc) {
6526 return doc;
6527 }
6528 var idx = doc._doc_id_rev.lastIndexOf(':');
6529 doc._id = doc._doc_id_rev.substring(0, idx - 1);
6530 doc._rev = doc._doc_id_rev.substring(idx + 1);
6531 delete doc._doc_id_rev;
6532 return doc;
6533}
6534
6535// Read a blob from the database, encoding as necessary
6536// and translating from base64 if the IDB doesn't support
6537// native Blobs
6538function readBlobData(body, type, asBlob, callback) {
6539 if (asBlob) {
6540 if (!body) {
6541 callback(createBlob([''], {type: type}));
6542 } else if (typeof body !== 'string') { // we have blob support
6543 callback(body);
6544 } else { // no blob support
6545 callback(b64ToBluffer(body, type));
6546 }
6547 } else { // as base64 string
6548 if (!body) {
6549 callback('');
6550 } else if (typeof body !== 'string') { // we have blob support
6551 readAsBinaryString(body, function (binary) {
6552 callback(thisBtoa(binary));
6553 });
6554 } else { // no blob support
6555 callback(body);
6556 }
6557 }
6558}
6559
6560function fetchAttachmentsIfNecessary(doc, opts, txn, cb) {
6561 var attachments = Object.keys(doc._attachments || {});
6562 if (!attachments.length) {
6563 return cb && cb();
6564 }
6565 var numDone = 0;
6566
6567 function checkDone() {
6568 if (++numDone === attachments.length && cb) {
6569 cb();
6570 }
6571 }
6572
6573 function fetchAttachment(doc, att) {
6574 var attObj = doc._attachments[att];
6575 var digest = attObj.digest;
6576 var req = txn.objectStore(ATTACH_STORE).get(digest);
6577 req.onsuccess = function (e) {
6578 attObj.body = e.target.result.body;
6579 checkDone();
6580 };
6581 }
6582
6583 attachments.forEach(function (att) {
6584 if (opts.attachments && opts.include_docs) {
6585 fetchAttachment(doc, att);
6586 } else {
6587 doc._attachments[att].stub = true;
6588 checkDone();
6589 }
6590 });
6591}
6592
6593// IDB-specific postprocessing necessary because
6594// we don't know whether we stored a true Blob or
6595// a base64-encoded string, and if it's a Blob it
6596// needs to be read outside of the transaction context
6597function postProcessAttachments(results, asBlob) {
6598 return Promise.all(results.map(function (row) {
6599 if (row.doc && row.doc._attachments) {
6600 var attNames = Object.keys(row.doc._attachments);
6601 return Promise.all(attNames.map(function (att) {
6602 var attObj = row.doc._attachments[att];
6603 if (!('body' in attObj)) { // already processed
6604 return;
6605 }
6606 var body = attObj.body;
6607 var type = attObj.content_type;
6608 return new Promise(function (resolve) {
6609 readBlobData(body, type, asBlob, function (data) {
6610 row.doc._attachments[att] = $inject_Object_assign(
6611 pick(attObj, ['digest', 'content_type']),
6612 {data: data}
6613 );
6614 resolve();
6615 });
6616 });
6617 }));
6618 }
6619 }));
6620}
6621
6622function compactRevs(revs, docId, txn) {
6623
6624 var possiblyOrphanedDigests = [];
6625 var seqStore = txn.objectStore(BY_SEQ_STORE);
6626 var attStore = txn.objectStore(ATTACH_STORE);
6627 var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
6628 var count = revs.length;
6629
6630 function checkDone() {
6631 count--;
6632 if (!count) { // done processing all revs
6633 deleteOrphanedAttachments();
6634 }
6635 }
6636
6637 function deleteOrphanedAttachments() {
6638 if (!possiblyOrphanedDigests.length) {
6639 return;
6640 }
6641 possiblyOrphanedDigests.forEach(function (digest) {
6642 var countReq = attAndSeqStore.index('digestSeq').count(
6643 IDBKeyRange.bound(
6644 digest + '::', digest + '::\uffff', false, false));
6645 countReq.onsuccess = function (e) {
6646 var count = e.target.result;
6647 if (!count) {
6648 // orphaned
6649 attStore["delete"](digest);
6650 }
6651 };
6652 });
6653 }
6654
6655 revs.forEach(function (rev) {
6656 var index = seqStore.index('_doc_id_rev');
6657 var key = docId + "::" + rev;
6658 index.getKey(key).onsuccess = function (e) {
6659 var seq = e.target.result;
6660 if (typeof seq !== 'number') {
6661 return checkDone();
6662 }
6663 seqStore["delete"](seq);
6664
6665 var cursor = attAndSeqStore.index('seq')
6666 .openCursor(IDBKeyRange.only(seq));
6667
6668 cursor.onsuccess = function (event) {
6669 var cursor = event.target.result;
6670 if (cursor) {
6671 var digest = cursor.value.digestSeq.split('::')[0];
6672 possiblyOrphanedDigests.push(digest);
6673 attAndSeqStore["delete"](cursor.primaryKey);
6674 cursor["continue"]();
6675 } else { // done
6676 checkDone();
6677 }
6678 };
6679 };
6680 });
6681}
6682
6683function openTransactionSafely(idb, stores, mode) {
6684 try {
6685 return {
6686 txn: idb.transaction(stores, mode)
6687 };
6688 } catch (err) {
6689 return {
6690 error: err
6691 };
6692 }
6693}
6694
6695var changesHandler = new Changes();
6696
6697function idbBulkDocs(dbOpts, req, opts, api, idb, callback) {
6698 var docInfos = req.docs;
6699 var txn;
6700 var docStore;
6701 var bySeqStore;
6702 var attachStore;
6703 var attachAndSeqStore;
6704 var metaStore;
6705 var docInfoError;
6706 var metaDoc;
6707
6708 for (var i = 0, len = docInfos.length; i < len; i++) {
6709 var doc = docInfos[i];
6710 if (doc._id && isLocalId(doc._id)) {
6711 continue;
6712 }
6713 doc = docInfos[i] = parseDoc(doc, opts.new_edits, dbOpts);
6714 if (doc.error && !docInfoError) {
6715 docInfoError = doc;
6716 }
6717 }
6718
6719 if (docInfoError) {
6720 return callback(docInfoError);
6721 }
6722
6723 var allDocsProcessed = false;
6724 var docCountDelta = 0;
6725 var results = new Array(docInfos.length);
6726 var fetchedDocs = new ExportedMap();
6727 var preconditionErrored = false;
6728 var blobType = api._meta.blobSupport ? 'blob' : 'base64';
6729
6730 preprocessAttachments(docInfos, blobType, function (err) {
6731 if (err) {
6732 return callback(err);
6733 }
6734 startTransaction();
6735 });
6736
6737 function startTransaction() {
6738
6739 var stores = [
6740 DOC_STORE, BY_SEQ_STORE,
6741 ATTACH_STORE,
6742 LOCAL_STORE, ATTACH_AND_SEQ_STORE,
6743 META_STORE
6744 ];
6745 var txnResult = openTransactionSafely(idb, stores, 'readwrite');
6746 if (txnResult.error) {
6747 return callback(txnResult.error);
6748 }
6749 txn = txnResult.txn;
6750 txn.onabort = idbError(callback);
6751 txn.ontimeout = idbError(callback);
6752 txn.oncomplete = complete;
6753 docStore = txn.objectStore(DOC_STORE);
6754 bySeqStore = txn.objectStore(BY_SEQ_STORE);
6755 attachStore = txn.objectStore(ATTACH_STORE);
6756 attachAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
6757 metaStore = txn.objectStore(META_STORE);
6758
6759 metaStore.get(META_STORE).onsuccess = function (e) {
6760 metaDoc = e.target.result;
6761 updateDocCountIfReady();
6762 };
6763
6764 verifyAttachments(function (err) {
6765 if (err) {
6766 preconditionErrored = true;
6767 return callback(err);
6768 }
6769 fetchExistingDocs();
6770 });
6771 }
6772
6773 function onAllDocsProcessed() {
6774 allDocsProcessed = true;
6775 updateDocCountIfReady();
6776 }
6777
6778 function idbProcessDocs() {
6779 processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs,
6780 txn, results, writeDoc, opts, onAllDocsProcessed);
6781 }
6782
6783 function updateDocCountIfReady() {
6784 if (!metaDoc || !allDocsProcessed) {
6785 return;
6786 }
6787 // caching the docCount saves a lot of time in allDocs() and
6788 // info(), which is why we go to all the trouble of doing this
6789 metaDoc.docCount += docCountDelta;
6790 metaStore.put(metaDoc);
6791 }
6792
6793 function fetchExistingDocs() {
6794
6795 if (!docInfos.length) {
6796 return;
6797 }
6798
6799 var numFetched = 0;
6800
6801 function checkDone() {
6802 if (++numFetched === docInfos.length) {
6803 idbProcessDocs();
6804 }
6805 }
6806
6807 function readMetadata(event) {
6808 var metadata = decodeMetadata(event.target.result);
6809
6810 if (metadata) {
6811 fetchedDocs.set(metadata.id, metadata);
6812 }
6813 checkDone();
6814 }
6815
6816 for (var i = 0, len = docInfos.length; i < len; i++) {
6817 var docInfo = docInfos[i];
6818 if (docInfo._id && isLocalId(docInfo._id)) {
6819 checkDone(); // skip local docs
6820 continue;
6821 }
6822 var req = docStore.get(docInfo.metadata.id);
6823 req.onsuccess = readMetadata;
6824 }
6825 }
6826
6827 function complete() {
6828 if (preconditionErrored) {
6829 return;
6830 }
6831
6832 changesHandler.notify(api._meta.name);
6833 callback(null, results);
6834 }
6835
6836 function verifyAttachment(digest, callback) {
6837
6838 var req = attachStore.get(digest);
6839 req.onsuccess = function (e) {
6840 if (!e.target.result) {
6841 var err = createError(MISSING_STUB,
6842 'unknown stub attachment with digest ' +
6843 digest);
6844 err.status = 412;
6845 callback(err);
6846 } else {
6847 callback();
6848 }
6849 };
6850 }
6851
6852 function verifyAttachments(finish) {
6853
6854
6855 var digests = [];
6856 docInfos.forEach(function (docInfo) {
6857 if (docInfo.data && docInfo.data._attachments) {
6858 Object.keys(docInfo.data._attachments).forEach(function (filename) {
6859 var att = docInfo.data._attachments[filename];
6860 if (att.stub) {
6861 digests.push(att.digest);
6862 }
6863 });
6864 }
6865 });
6866 if (!digests.length) {
6867 return finish();
6868 }
6869 var numDone = 0;
6870 var err;
6871
6872 function checkDone() {
6873 if (++numDone === digests.length) {
6874 finish(err);
6875 }
6876 }
6877 digests.forEach(function (digest) {
6878 verifyAttachment(digest, function (attErr) {
6879 if (attErr && !err) {
6880 err = attErr;
6881 }
6882 checkDone();
6883 });
6884 });
6885 }
6886
6887 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
6888 isUpdate, delta, resultsIdx, callback) {
6889
6890 docInfo.metadata.winningRev = winningRev$$1;
6891 docInfo.metadata.deleted = winningRevIsDeleted;
6892
6893 var doc = docInfo.data;
6894 doc._id = docInfo.metadata.id;
6895 doc._rev = docInfo.metadata.rev;
6896
6897 if (newRevIsDeleted) {
6898 doc._deleted = true;
6899 }
6900
6901 var hasAttachments = doc._attachments &&
6902 Object.keys(doc._attachments).length;
6903 if (hasAttachments) {
6904 return writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,
6905 isUpdate, resultsIdx, callback);
6906 }
6907
6908 docCountDelta += delta;
6909 updateDocCountIfReady();
6910
6911 finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
6912 isUpdate, resultsIdx, callback);
6913 }
6914
6915 function finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
6916 isUpdate, resultsIdx, callback) {
6917
6918 var doc = docInfo.data;
6919 var metadata = docInfo.metadata;
6920
6921 doc._doc_id_rev = metadata.id + '::' + metadata.rev;
6922 delete doc._id;
6923 delete doc._rev;
6924
6925 function afterPutDoc(e) {
6926 var revsToDelete = docInfo.stemmedRevs || [];
6927
6928 if (isUpdate && api.auto_compaction) {
6929 revsToDelete = revsToDelete.concat(compactTree(docInfo.metadata));
6930 }
6931
6932 if (revsToDelete && revsToDelete.length) {
6933 compactRevs(revsToDelete, docInfo.metadata.id, txn);
6934 }
6935
6936 metadata.seq = e.target.result;
6937 // Current _rev is calculated from _rev_tree on read
6938 // delete metadata.rev;
6939 var metadataToStore = encodeMetadata(metadata, winningRev$$1,
6940 winningRevIsDeleted);
6941 var metaDataReq = docStore.put(metadataToStore);
6942 metaDataReq.onsuccess = afterPutMetadata;
6943 }
6944
6945 function afterPutDocError(e) {
6946 // ConstraintError, need to update, not put (see #1638 for details)
6947 e.preventDefault(); // avoid transaction abort
6948 e.stopPropagation(); // avoid transaction onerror
6949 var index = bySeqStore.index('_doc_id_rev');
6950 var getKeyReq = index.getKey(doc._doc_id_rev);
6951 getKeyReq.onsuccess = function (e) {
6952 var putReq = bySeqStore.put(doc, e.target.result);
6953 putReq.onsuccess = afterPutDoc;
6954 };
6955 }
6956
6957 function afterPutMetadata() {
6958 results[resultsIdx] = {
6959 ok: true,
6960 id: metadata.id,
6961 rev: metadata.rev
6962 };
6963 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
6964 insertAttachmentMappings(docInfo, metadata.seq, callback);
6965 }
6966
6967 var putReq = bySeqStore.put(doc);
6968
6969 putReq.onsuccess = afterPutDoc;
6970 putReq.onerror = afterPutDocError;
6971 }
6972
6973 function writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,
6974 isUpdate, resultsIdx, callback) {
6975
6976
6977 var doc = docInfo.data;
6978
6979 var numDone = 0;
6980 var attachments = Object.keys(doc._attachments);
6981
6982 function collectResults() {
6983 if (numDone === attachments.length) {
6984 finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
6985 isUpdate, resultsIdx, callback);
6986 }
6987 }
6988
6989 function attachmentSaved() {
6990 numDone++;
6991 collectResults();
6992 }
6993
6994 attachments.forEach(function (key) {
6995 var att = docInfo.data._attachments[key];
6996 if (!att.stub) {
6997 var data = att.data;
6998 delete att.data;
6999 att.revpos = parseInt(winningRev$$1, 10);
7000 var digest = att.digest;
7001 saveAttachment(digest, data, attachmentSaved);
7002 } else {
7003 numDone++;
7004 collectResults();
7005 }
7006 });
7007 }
7008
7009 // map seqs to attachment digests, which
7010 // we will need later during compaction
7011 function insertAttachmentMappings(docInfo, seq, callback) {
7012
7013 var attsAdded = 0;
7014 var attsToAdd = Object.keys(docInfo.data._attachments || {});
7015
7016 if (!attsToAdd.length) {
7017 return callback();
7018 }
7019
7020 function checkDone() {
7021 if (++attsAdded === attsToAdd.length) {
7022 callback();
7023 }
7024 }
7025
7026 function add(att) {
7027 var digest = docInfo.data._attachments[att].digest;
7028 var req = attachAndSeqStore.put({
7029 seq: seq,
7030 digestSeq: digest + '::' + seq
7031 });
7032
7033 req.onsuccess = checkDone;
7034 req.onerror = function (e) {
7035 // this callback is for a constaint error, which we ignore
7036 // because this docid/rev has already been associated with
7037 // the digest (e.g. when new_edits == false)
7038 e.preventDefault(); // avoid transaction abort
7039 e.stopPropagation(); // avoid transaction onerror
7040 checkDone();
7041 };
7042 }
7043 for (var i = 0; i < attsToAdd.length; i++) {
7044 add(attsToAdd[i]); // do in parallel
7045 }
7046 }
7047
7048 function saveAttachment(digest, data, callback) {
7049
7050
7051 var getKeyReq = attachStore.count(digest);
7052 getKeyReq.onsuccess = function (e) {
7053 var count = e.target.result;
7054 if (count) {
7055 return callback(); // already exists
7056 }
7057 var newAtt = {
7058 digest: digest,
7059 body: data
7060 };
7061 var putReq = attachStore.put(newAtt);
7062 putReq.onsuccess = callback;
7063 };
7064 }
7065}
7066
7067// Abstraction over IDBCursor and getAll()/getAllKeys() that allows us to batch our operations
7068// while falling back to a normal IDBCursor operation on browsers that don't support getAll() or
7069// getAllKeys(). This allows for a much faster implementation than just straight-up cursors, because
7070// we're not processing each document one-at-a-time.
7071function runBatchedCursor(objectStore, keyRange, descending, batchSize, onBatch) {
7072
7073 if (batchSize === -1) {
7074 batchSize = 1000;
7075 }
7076
7077 // Bail out of getAll()/getAllKeys() in the following cases:
7078 // 1) either method is unsupported - we need both
7079 // 2) batchSize is 1 (might as well use IDBCursor)
7080 // 3) descending – no real way to do this via getAll()/getAllKeys()
7081
7082 var useGetAll = typeof objectStore.getAll === 'function' &&
7083 typeof objectStore.getAllKeys === 'function' &&
7084 batchSize > 1 && !descending;
7085
7086 var keysBatch;
7087 var valuesBatch;
7088 var pseudoCursor;
7089
7090 function onGetAll(e) {
7091 valuesBatch = e.target.result;
7092 if (keysBatch) {
7093 onBatch(keysBatch, valuesBatch, pseudoCursor);
7094 }
7095 }
7096
7097 function onGetAllKeys(e) {
7098 keysBatch = e.target.result;
7099 if (valuesBatch) {
7100 onBatch(keysBatch, valuesBatch, pseudoCursor);
7101 }
7102 }
7103
7104 function continuePseudoCursor() {
7105 if (!keysBatch.length) { // no more results
7106 return onBatch();
7107 }
7108 // fetch next batch, exclusive start
7109 var lastKey = keysBatch[keysBatch.length - 1];
7110 var newKeyRange;
7111 if (keyRange && keyRange.upper) {
7112 try {
7113 newKeyRange = IDBKeyRange.bound(lastKey, keyRange.upper,
7114 true, keyRange.upperOpen);
7115 } catch (e) {
7116 if (e.name === "DataError" && e.code === 0) {
7117 return onBatch(); // we're done, startkey and endkey are equal
7118 }
7119 }
7120 } else {
7121 newKeyRange = IDBKeyRange.lowerBound(lastKey, true);
7122 }
7123 keyRange = newKeyRange;
7124 keysBatch = null;
7125 valuesBatch = null;
7126 objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;
7127 objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;
7128 }
7129
7130 function onCursor(e) {
7131 var cursor = e.target.result;
7132 if (!cursor) { // done
7133 return onBatch();
7134 }
7135 // regular IDBCursor acts like a batch where batch size is always 1
7136 onBatch([cursor.key], [cursor.value], cursor);
7137 }
7138
7139 if (useGetAll) {
7140 pseudoCursor = {"continue": continuePseudoCursor};
7141 objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;
7142 objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;
7143 } else if (descending) {
7144 objectStore.openCursor(keyRange, 'prev').onsuccess = onCursor;
7145 } else {
7146 objectStore.openCursor(keyRange).onsuccess = onCursor;
7147 }
7148}
7149
7150// simple shim for objectStore.getAll(), falling back to IDBCursor
7151function getAll(objectStore, keyRange, onSuccess) {
7152 if (typeof objectStore.getAll === 'function') {
7153 // use native getAll
7154 objectStore.getAll(keyRange).onsuccess = onSuccess;
7155 return;
7156 }
7157 // fall back to cursors
7158 var values = [];
7159
7160 function onCursor(e) {
7161 var cursor = e.target.result;
7162 if (cursor) {
7163 values.push(cursor.value);
7164 cursor["continue"]();
7165 } else {
7166 onSuccess({
7167 target: {
7168 result: values
7169 }
7170 });
7171 }
7172 }
7173
7174 objectStore.openCursor(keyRange).onsuccess = onCursor;
7175}
7176
7177function allDocsKeys(keys, docStore, onBatch) {
7178 // It's not guaranted to be returned in right order
7179 var valuesBatch = new Array(keys.length);
7180 var count = 0;
7181 keys.forEach(function (key, index) {
7182 docStore.get(key).onsuccess = function (event) {
7183 if (event.target.result) {
7184 valuesBatch[index] = event.target.result;
7185 } else {
7186 valuesBatch[index] = {key: key, error: 'not_found'};
7187 }
7188 count++;
7189 if (count === keys.length) {
7190 onBatch(keys, valuesBatch, {});
7191 }
7192 };
7193 });
7194}
7195
7196function createKeyRange(start, end, inclusiveEnd, key, descending) {
7197 try {
7198 if (start && end) {
7199 if (descending) {
7200 return IDBKeyRange.bound(end, start, !inclusiveEnd, false);
7201 } else {
7202 return IDBKeyRange.bound(start, end, false, !inclusiveEnd);
7203 }
7204 } else if (start) {
7205 if (descending) {
7206 return IDBKeyRange.upperBound(start);
7207 } else {
7208 return IDBKeyRange.lowerBound(start);
7209 }
7210 } else if (end) {
7211 if (descending) {
7212 return IDBKeyRange.lowerBound(end, !inclusiveEnd);
7213 } else {
7214 return IDBKeyRange.upperBound(end, !inclusiveEnd);
7215 }
7216 } else if (key) {
7217 return IDBKeyRange.only(key);
7218 }
7219 } catch (e) {
7220 return {error: e};
7221 }
7222 return null;
7223}
7224
7225function idbAllDocs(opts, idb, callback) {
7226 var start = 'startkey' in opts ? opts.startkey : false;
7227 var end = 'endkey' in opts ? opts.endkey : false;
7228 var key = 'key' in opts ? opts.key : false;
7229 var keys = 'keys' in opts ? opts.keys : false;
7230 var skip = opts.skip || 0;
7231 var limit = typeof opts.limit === 'number' ? opts.limit : -1;
7232 var inclusiveEnd = opts.inclusive_end !== false;
7233
7234 var keyRange ;
7235 var keyRangeError;
7236 if (!keys) {
7237 keyRange = createKeyRange(start, end, inclusiveEnd, key, opts.descending);
7238 keyRangeError = keyRange && keyRange.error;
7239 if (keyRangeError &&
7240 !(keyRangeError.name === "DataError" && keyRangeError.code === 0)) {
7241 // DataError with error code 0 indicates start is less than end, so
7242 // can just do an empty query. Else need to throw
7243 return callback(createError(IDB_ERROR,
7244 keyRangeError.name, keyRangeError.message));
7245 }
7246 }
7247
7248 var stores = [DOC_STORE, BY_SEQ_STORE, META_STORE];
7249
7250 if (opts.attachments) {
7251 stores.push(ATTACH_STORE);
7252 }
7253 var txnResult = openTransactionSafely(idb, stores, 'readonly');
7254 if (txnResult.error) {
7255 return callback(txnResult.error);
7256 }
7257 var txn = txnResult.txn;
7258 txn.oncomplete = onTxnComplete;
7259 txn.onabort = idbError(callback);
7260 var docStore = txn.objectStore(DOC_STORE);
7261 var seqStore = txn.objectStore(BY_SEQ_STORE);
7262 var metaStore = txn.objectStore(META_STORE);
7263 var docIdRevIndex = seqStore.index('_doc_id_rev');
7264 var results = [];
7265 var docCount;
7266 var updateSeq;
7267
7268 metaStore.get(META_STORE).onsuccess = function (e) {
7269 docCount = e.target.result.docCount;
7270 };
7271
7272 /* istanbul ignore if */
7273 if (opts.update_seq) {
7274 getMaxUpdateSeq(seqStore, function (e) {
7275 if (e.target.result && e.target.result.length > 0) {
7276 updateSeq = e.target.result[0];
7277 }
7278 });
7279 }
7280
7281 function getMaxUpdateSeq(objectStore, onSuccess) {
7282 function onCursor(e) {
7283 var cursor = e.target.result;
7284 var maxKey = undefined;
7285 if (cursor && cursor.key) {
7286 maxKey = cursor.key;
7287 }
7288 return onSuccess({
7289 target: {
7290 result: [maxKey]
7291 }
7292 });
7293 }
7294 objectStore.openCursor(null, 'prev').onsuccess = onCursor;
7295 }
7296
7297 // if the user specifies include_docs=true, then we don't
7298 // want to block the main cursor while we're fetching the doc
7299 function fetchDocAsynchronously(metadata, row, winningRev$$1) {
7300 var key = metadata.id + "::" + winningRev$$1;
7301 docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {
7302 row.doc = decodeDoc(e.target.result) || {};
7303 if (opts.conflicts) {
7304 var conflicts = collectConflicts(metadata);
7305 if (conflicts.length) {
7306 row.doc._conflicts = conflicts;
7307 }
7308 }
7309 fetchAttachmentsIfNecessary(row.doc, opts, txn);
7310 };
7311 }
7312
7313 function allDocsInner(winningRev$$1, metadata) {
7314 var row = {
7315 id: metadata.id,
7316 key: metadata.id,
7317 value: {
7318 rev: winningRev$$1
7319 }
7320 };
7321 var deleted = metadata.deleted;
7322 if (deleted) {
7323 if (keys) {
7324 results.push(row);
7325 // deleted docs are okay with "keys" requests
7326 row.value.deleted = true;
7327 row.doc = null;
7328 }
7329 } else if (skip-- <= 0) {
7330 results.push(row);
7331 if (opts.include_docs) {
7332 fetchDocAsynchronously(metadata, row, winningRev$$1);
7333 }
7334 }
7335 }
7336
7337 function processBatch(batchValues) {
7338 for (var i = 0, len = batchValues.length; i < len; i++) {
7339 if (results.length === limit) {
7340 break;
7341 }
7342 var batchValue = batchValues[i];
7343 if (batchValue.error && keys) {
7344 // key was not found with "keys" requests
7345 results.push(batchValue);
7346 continue;
7347 }
7348 var metadata = decodeMetadata(batchValue);
7349 var winningRev$$1 = metadata.winningRev;
7350 allDocsInner(winningRev$$1, metadata);
7351 }
7352 }
7353
7354 function onBatch(batchKeys, batchValues, cursor) {
7355 if (!cursor) {
7356 return;
7357 }
7358 processBatch(batchValues);
7359 if (results.length < limit) {
7360 cursor["continue"]();
7361 }
7362 }
7363
7364 function onGetAll(e) {
7365 var values = e.target.result;
7366 if (opts.descending) {
7367 values = values.reverse();
7368 }
7369 processBatch(values);
7370 }
7371
7372 function onResultsReady() {
7373 var returnVal = {
7374 total_rows: docCount,
7375 offset: opts.skip,
7376 rows: results
7377 };
7378
7379 /* istanbul ignore if */
7380 if (opts.update_seq && updateSeq !== undefined) {
7381 returnVal.update_seq = updateSeq;
7382 }
7383 callback(null, returnVal);
7384 }
7385
7386 function onTxnComplete() {
7387 if (opts.attachments) {
7388 postProcessAttachments(results, opts.binary).then(onResultsReady);
7389 } else {
7390 onResultsReady();
7391 }
7392 }
7393
7394 // don't bother doing any requests if start > end or limit === 0
7395 if (keyRangeError || limit === 0) {
7396 return;
7397 }
7398 if (keys) {
7399 return allDocsKeys(opts.keys, docStore, onBatch);
7400 }
7401 if (limit === -1) { // just fetch everything
7402 return getAll(docStore, keyRange, onGetAll);
7403 }
7404 // else do a cursor
7405 // choose a batch size based on the skip, since we'll need to skip that many
7406 runBatchedCursor(docStore, keyRange, opts.descending, limit + skip, onBatch);
7407}
7408
7409//
7410// Blobs are not supported in all versions of IndexedDB, notably
7411// Chrome <37 and Android <5. In those versions, storing a blob will throw.
7412//
7413// Various other blob bugs exist in Chrome v37-42 (inclusive).
7414// Detecting them is expensive and confusing to users, and Chrome 37-42
7415// is at very low usage worldwide, so we do a hacky userAgent check instead.
7416//
7417// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
7418// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
7419// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
7420//
7421function checkBlobSupport(txn) {
7422 return new Promise(function (resolve) {
7423 var blob$$1 = createBlob(['']);
7424 var req = txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob$$1, 'key');
7425
7426 req.onsuccess = function () {
7427 var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
7428 var matchedEdge = navigator.userAgent.match(/Edge\//);
7429 // MS Edge pretends to be Chrome 42:
7430 // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
7431 resolve(matchedEdge || !matchedChrome ||
7432 parseInt(matchedChrome[1], 10) >= 43);
7433 };
7434
7435 req.onerror = txn.onabort = function (e) {
7436 // If the transaction aborts now its due to not being able to
7437 // write to the database, likely due to the disk being full
7438 e.preventDefault();
7439 e.stopPropagation();
7440 resolve(false);
7441 };
7442 })["catch"](function () {
7443 return false; // error, so assume unsupported
7444 });
7445}
7446
7447function countDocs(txn, cb) {
7448 var index = txn.objectStore(DOC_STORE).index('deletedOrLocal');
7449 index.count(IDBKeyRange.only('0')).onsuccess = function (e) {
7450 cb(e.target.result);
7451 };
7452}
7453
7454// This task queue ensures that IDB open calls are done in their own tick
7455
7456var running = false;
7457var queue = [];
7458
7459function tryCode(fun, err, res, PouchDB) {
7460 try {
7461 fun(err, res);
7462 } catch (err) {
7463 // Shouldn't happen, but in some odd cases
7464 // IndexedDB implementations might throw a sync
7465 // error, in which case this will at least log it.
7466 PouchDB.emit('error', err);
7467 }
7468}
7469
7470function applyNext() {
7471 if (running || !queue.length) {
7472 return;
7473 }
7474 running = true;
7475 queue.shift()();
7476}
7477
7478function enqueueTask(action, callback, PouchDB) {
7479 queue.push(function runAction() {
7480 action(function runCallback(err, res) {
7481 tryCode(callback, err, res, PouchDB);
7482 running = false;
7483 nextTick(function runNext() {
7484 applyNext(PouchDB);
7485 });
7486 });
7487 });
7488 applyNext();
7489}
7490
7491function changes(opts, api, dbName, idb) {
7492 opts = clone(opts);
7493
7494 if (opts.continuous) {
7495 var id = dbName + ':' + uuid();
7496 changesHandler.addListener(dbName, id, api, opts);
7497 changesHandler.notify(dbName);
7498 return {
7499 cancel: function () {
7500 changesHandler.removeListener(dbName, id);
7501 }
7502 };
7503 }
7504
7505 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
7506
7507 opts.since = opts.since || 0;
7508 var lastSeq = opts.since;
7509
7510 var limit = 'limit' in opts ? opts.limit : -1;
7511 if (limit === 0) {
7512 limit = 1; // per CouchDB _changes spec
7513 }
7514
7515 var results = [];
7516 var numResults = 0;
7517 var filter = filterChange(opts);
7518 var docIdsToMetadata = new ExportedMap();
7519
7520 var txn;
7521 var bySeqStore;
7522 var docStore;
7523 var docIdRevIndex;
7524
7525 function onBatch(batchKeys, batchValues, cursor) {
7526 if (!cursor || !batchKeys.length) { // done
7527 return;
7528 }
7529
7530 var winningDocs = new Array(batchKeys.length);
7531 var metadatas = new Array(batchKeys.length);
7532
7533 function processMetadataAndWinningDoc(metadata, winningDoc) {
7534 var change = opts.processChange(winningDoc, metadata, opts);
7535 lastSeq = change.seq = metadata.seq;
7536
7537 var filtered = filter(change);
7538 if (typeof filtered === 'object') { // anything but true/false indicates error
7539 return Promise.reject(filtered);
7540 }
7541
7542 if (!filtered) {
7543 return Promise.resolve();
7544 }
7545 numResults++;
7546 if (opts.return_docs) {
7547 results.push(change);
7548 }
7549 // process the attachment immediately
7550 // for the benefit of live listeners
7551 if (opts.attachments && opts.include_docs) {
7552 return new Promise(function (resolve) {
7553 fetchAttachmentsIfNecessary(winningDoc, opts, txn, function () {
7554 postProcessAttachments([change], opts.binary).then(function () {
7555 resolve(change);
7556 });
7557 });
7558 });
7559 } else {
7560 return Promise.resolve(change);
7561 }
7562 }
7563
7564 function onBatchDone() {
7565 var promises = [];
7566 for (var i = 0, len = winningDocs.length; i < len; i++) {
7567 if (numResults === limit) {
7568 break;
7569 }
7570 var winningDoc = winningDocs[i];
7571 if (!winningDoc) {
7572 continue;
7573 }
7574 var metadata = metadatas[i];
7575 promises.push(processMetadataAndWinningDoc(metadata, winningDoc));
7576 }
7577
7578 Promise.all(promises).then(function (changes) {
7579 for (var i = 0, len = changes.length; i < len; i++) {
7580 if (changes[i]) {
7581 opts.onChange(changes[i]);
7582 }
7583 }
7584 })["catch"](opts.complete);
7585
7586 if (numResults !== limit) {
7587 cursor["continue"]();
7588 }
7589 }
7590
7591 // Fetch all metadatas/winningdocs from this batch in parallel, then process
7592 // them all only once all data has been collected. This is done in parallel
7593 // because it's faster than doing it one-at-a-time.
7594 var numDone = 0;
7595 batchValues.forEach(function (value, i) {
7596 var doc = decodeDoc(value);
7597 var seq = batchKeys[i];
7598 fetchWinningDocAndMetadata(doc, seq, function (metadata, winningDoc) {
7599 metadatas[i] = metadata;
7600 winningDocs[i] = winningDoc;
7601 if (++numDone === batchKeys.length) {
7602 onBatchDone();
7603 }
7604 });
7605 });
7606 }
7607
7608 function onGetMetadata(doc, seq, metadata, cb) {
7609 if (metadata.seq !== seq) {
7610 // some other seq is later
7611 return cb();
7612 }
7613
7614 if (metadata.winningRev === doc._rev) {
7615 // this is the winning doc
7616 return cb(metadata, doc);
7617 }
7618
7619 // fetch winning doc in separate request
7620 var docIdRev = doc._id + '::' + metadata.winningRev;
7621 var req = docIdRevIndex.get(docIdRev);
7622 req.onsuccess = function (e) {
7623 cb(metadata, decodeDoc(e.target.result));
7624 };
7625 }
7626
7627 function fetchWinningDocAndMetadata(doc, seq, cb) {
7628 if (docIds && !docIds.has(doc._id)) {
7629 return cb();
7630 }
7631
7632 var metadata = docIdsToMetadata.get(doc._id);
7633 if (metadata) { // cached
7634 return onGetMetadata(doc, seq, metadata, cb);
7635 }
7636 // metadata not cached, have to go fetch it
7637 docStore.get(doc._id).onsuccess = function (e) {
7638 metadata = decodeMetadata(e.target.result);
7639 docIdsToMetadata.set(doc._id, metadata);
7640 onGetMetadata(doc, seq, metadata, cb);
7641 };
7642 }
7643
7644 function finish() {
7645 opts.complete(null, {
7646 results: results,
7647 last_seq: lastSeq
7648 });
7649 }
7650
7651 function onTxnComplete() {
7652 if (!opts.continuous && opts.attachments) {
7653 // cannot guarantee that postProcessing was already done,
7654 // so do it again
7655 postProcessAttachments(results).then(finish);
7656 } else {
7657 finish();
7658 }
7659 }
7660
7661 var objectStores = [DOC_STORE, BY_SEQ_STORE];
7662 if (opts.attachments) {
7663 objectStores.push(ATTACH_STORE);
7664 }
7665 var txnResult = openTransactionSafely(idb, objectStores, 'readonly');
7666 if (txnResult.error) {
7667 return opts.complete(txnResult.error);
7668 }
7669 txn = txnResult.txn;
7670 txn.onabort = idbError(opts.complete);
7671 txn.oncomplete = onTxnComplete;
7672
7673 bySeqStore = txn.objectStore(BY_SEQ_STORE);
7674 docStore = txn.objectStore(DOC_STORE);
7675 docIdRevIndex = bySeqStore.index('_doc_id_rev');
7676
7677 var keyRange = (opts.since && !opts.descending) ?
7678 IDBKeyRange.lowerBound(opts.since, true) : null;
7679
7680 runBatchedCursor(bySeqStore, keyRange, opts.descending, limit, onBatch);
7681}
7682
7683var cachedDBs = new ExportedMap();
7684var blobSupportPromise;
7685var openReqList = new ExportedMap();
7686
7687function IdbPouch(opts, callback) {
7688 var api = this;
7689
7690 enqueueTask(function (thisCallback) {
7691 init(api, opts, thisCallback);
7692 }, callback, api.constructor);
7693}
7694
7695function init(api, opts, callback) {
7696
7697 var dbName = opts.name;
7698
7699 var idb = null;
7700 api._meta = null;
7701
7702 // called when creating a fresh new database
7703 function createSchema(db) {
7704 var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'});
7705 db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true})
7706 .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
7707 db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'});
7708 db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false});
7709 db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
7710
7711 // added in v2
7712 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
7713
7714 // added in v3
7715 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'});
7716
7717 // added in v4
7718 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
7719 {autoIncrement: true});
7720 attAndSeqStore.createIndex('seq', 'seq');
7721 attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
7722 }
7723
7724 // migration to version 2
7725 // unfortunately "deletedOrLocal" is a misnomer now that we no longer
7726 // store local docs in the main doc-store, but whaddyagonnado
7727 function addDeletedOrLocalIndex(txn, callback) {
7728 var docStore = txn.objectStore(DOC_STORE);
7729 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
7730
7731 docStore.openCursor().onsuccess = function (event) {
7732 var cursor = event.target.result;
7733 if (cursor) {
7734 var metadata = cursor.value;
7735 var deleted = isDeleted(metadata);
7736 metadata.deletedOrLocal = deleted ? "1" : "0";
7737 docStore.put(metadata);
7738 cursor["continue"]();
7739 } else {
7740 callback();
7741 }
7742 };
7743 }
7744
7745 // migration to version 3 (part 1)
7746 function createLocalStoreSchema(db) {
7747 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'})
7748 .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
7749 }
7750
7751 // migration to version 3 (part 2)
7752 function migrateLocalStore(txn, cb) {
7753 var localStore = txn.objectStore(LOCAL_STORE);
7754 var docStore = txn.objectStore(DOC_STORE);
7755 var seqStore = txn.objectStore(BY_SEQ_STORE);
7756
7757 var cursor = docStore.openCursor();
7758 cursor.onsuccess = function (event) {
7759 var cursor = event.target.result;
7760 if (cursor) {
7761 var metadata = cursor.value;
7762 var docId = metadata.id;
7763 var local = isLocalId(docId);
7764 var rev = winningRev(metadata);
7765 if (local) {
7766 var docIdRev = docId + "::" + rev;
7767 // remove all seq entries
7768 // associated with this docId
7769 var start = docId + "::";
7770 var end = docId + "::~";
7771 var index = seqStore.index('_doc_id_rev');
7772 var range = IDBKeyRange.bound(start, end, false, false);
7773 var seqCursor = index.openCursor(range);
7774 seqCursor.onsuccess = function (e) {
7775 seqCursor = e.target.result;
7776 if (!seqCursor) {
7777 // done
7778 docStore["delete"](cursor.primaryKey);
7779 cursor["continue"]();
7780 } else {
7781 var data = seqCursor.value;
7782 if (data._doc_id_rev === docIdRev) {
7783 localStore.put(data);
7784 }
7785 seqStore["delete"](seqCursor.primaryKey);
7786 seqCursor["continue"]();
7787 }
7788 };
7789 } else {
7790 cursor["continue"]();
7791 }
7792 } else if (cb) {
7793 cb();
7794 }
7795 };
7796 }
7797
7798 // migration to version 4 (part 1)
7799 function addAttachAndSeqStore(db) {
7800 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
7801 {autoIncrement: true});
7802 attAndSeqStore.createIndex('seq', 'seq');
7803 attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
7804 }
7805
7806 // migration to version 4 (part 2)
7807 function migrateAttsAndSeqs(txn, callback) {
7808 var seqStore = txn.objectStore(BY_SEQ_STORE);
7809 var attStore = txn.objectStore(ATTACH_STORE);
7810 var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
7811
7812 // need to actually populate the table. this is the expensive part,
7813 // so as an optimization, check first that this database even
7814 // contains attachments
7815 var req = attStore.count();
7816 req.onsuccess = function (e) {
7817 var count = e.target.result;
7818 if (!count) {
7819 return callback(); // done
7820 }
7821
7822 seqStore.openCursor().onsuccess = function (e) {
7823 var cursor = e.target.result;
7824 if (!cursor) {
7825 return callback(); // done
7826 }
7827 var doc = cursor.value;
7828 var seq = cursor.primaryKey;
7829 var atts = Object.keys(doc._attachments || {});
7830 var digestMap = {};
7831 for (var j = 0; j < atts.length; j++) {
7832 var att = doc._attachments[atts[j]];
7833 digestMap[att.digest] = true; // uniq digests, just in case
7834 }
7835 var digests = Object.keys(digestMap);
7836 for (j = 0; j < digests.length; j++) {
7837 var digest = digests[j];
7838 attAndSeqStore.put({
7839 seq: seq,
7840 digestSeq: digest + '::' + seq
7841 });
7842 }
7843 cursor["continue"]();
7844 };
7845 };
7846 }
7847
7848 // migration to version 5
7849 // Instead of relying on on-the-fly migration of metadata,
7850 // this brings the doc-store to its modern form:
7851 // - metadata.winningrev
7852 // - metadata.seq
7853 // - stringify the metadata when storing it
7854 function migrateMetadata(txn) {
7855
7856 function decodeMetadataCompat(storedObject) {
7857 if (!storedObject.data) {
7858 // old format, when we didn't store it stringified
7859 storedObject.deleted = storedObject.deletedOrLocal === '1';
7860 return storedObject;
7861 }
7862 return decodeMetadata(storedObject);
7863 }
7864
7865 // ensure that every metadata has a winningRev and seq,
7866 // which was previously created on-the-fly but better to migrate
7867 var bySeqStore = txn.objectStore(BY_SEQ_STORE);
7868 var docStore = txn.objectStore(DOC_STORE);
7869 var cursor = docStore.openCursor();
7870 cursor.onsuccess = function (e) {
7871 var cursor = e.target.result;
7872 if (!cursor) {
7873 return; // done
7874 }
7875 var metadata = decodeMetadataCompat(cursor.value);
7876
7877 metadata.winningRev = metadata.winningRev ||
7878 winningRev(metadata);
7879
7880 function fetchMetadataSeq() {
7881 // metadata.seq was added post-3.2.0, so if it's missing,
7882 // we need to fetch it manually
7883 var start = metadata.id + '::';
7884 var end = metadata.id + '::\uffff';
7885 var req = bySeqStore.index('_doc_id_rev').openCursor(
7886 IDBKeyRange.bound(start, end));
7887
7888 var metadataSeq = 0;
7889 req.onsuccess = function (e) {
7890 var cursor = e.target.result;
7891 if (!cursor) {
7892 metadata.seq = metadataSeq;
7893 return onGetMetadataSeq();
7894 }
7895 var seq = cursor.primaryKey;
7896 if (seq > metadataSeq) {
7897 metadataSeq = seq;
7898 }
7899 cursor["continue"]();
7900 };
7901 }
7902
7903 function onGetMetadataSeq() {
7904 var metadataToStore = encodeMetadata(metadata,
7905 metadata.winningRev, metadata.deleted);
7906
7907 var req = docStore.put(metadataToStore);
7908 req.onsuccess = function () {
7909 cursor["continue"]();
7910 };
7911 }
7912
7913 if (metadata.seq) {
7914 return onGetMetadataSeq();
7915 }
7916
7917 fetchMetadataSeq();
7918 };
7919
7920 }
7921
7922 api._remote = false;
7923 api.type = function () {
7924 return 'idb';
7925 };
7926
7927 api._id = toPromise(function (callback) {
7928 callback(null, api._meta.instanceId);
7929 });
7930
7931 api._bulkDocs = function idb_bulkDocs(req, reqOpts, callback) {
7932 idbBulkDocs(opts, req, reqOpts, api, idb, callback);
7933 };
7934
7935 // First we look up the metadata in the ids database, then we fetch the
7936 // current revision(s) from the by sequence store
7937 api._get = function idb_get(id, opts, callback) {
7938 var doc;
7939 var metadata;
7940 var err;
7941 var txn = opts.ctx;
7942 if (!txn) {
7943 var txnResult = openTransactionSafely(idb,
7944 [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
7945 if (txnResult.error) {
7946 return callback(txnResult.error);
7947 }
7948 txn = txnResult.txn;
7949 }
7950
7951 function finish() {
7952 callback(err, {doc: doc, metadata: metadata, ctx: txn});
7953 }
7954
7955 txn.objectStore(DOC_STORE).get(id).onsuccess = function (e) {
7956 metadata = decodeMetadata(e.target.result);
7957 // we can determine the result here if:
7958 // 1. there is no such document
7959 // 2. the document is deleted and we don't ask about specific rev
7960 // When we ask with opts.rev we expect the answer to be either
7961 // doc (possibly with _deleted=true) or missing error
7962 if (!metadata) {
7963 err = createError(MISSING_DOC, 'missing');
7964 return finish();
7965 }
7966
7967 var rev;
7968 if (!opts.rev) {
7969 rev = metadata.winningRev;
7970 var deleted = isDeleted(metadata);
7971 if (deleted) {
7972 err = createError(MISSING_DOC, "deleted");
7973 return finish();
7974 }
7975 } else {
7976 rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;
7977 }
7978
7979 var objectStore = txn.objectStore(BY_SEQ_STORE);
7980 var key = metadata.id + '::' + rev;
7981
7982 objectStore.index('_doc_id_rev').get(key).onsuccess = function (e) {
7983 doc = e.target.result;
7984 if (doc) {
7985 doc = decodeDoc(doc);
7986 }
7987 if (!doc) {
7988 err = createError(MISSING_DOC, 'missing');
7989 return finish();
7990 }
7991 finish();
7992 };
7993 };
7994 };
7995
7996 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
7997 var txn;
7998 if (opts.ctx) {
7999 txn = opts.ctx;
8000 } else {
8001 var txnResult = openTransactionSafely(idb,
8002 [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
8003 if (txnResult.error) {
8004 return callback(txnResult.error);
8005 }
8006 txn = txnResult.txn;
8007 }
8008 var digest = attachment.digest;
8009 var type = attachment.content_type;
8010
8011 txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function (e) {
8012 var body = e.target.result.body;
8013 readBlobData(body, type, opts.binary, function (blobData) {
8014 callback(null, blobData);
8015 });
8016 };
8017 };
8018
8019 api._info = function idb_info(callback) {
8020 var updateSeq;
8021 var docCount;
8022
8023 var txnResult = openTransactionSafely(idb, [META_STORE, BY_SEQ_STORE], 'readonly');
8024 if (txnResult.error) {
8025 return callback(txnResult.error);
8026 }
8027 var txn = txnResult.txn;
8028 txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {
8029 docCount = e.target.result.docCount;
8030 };
8031 txn.objectStore(BY_SEQ_STORE).openCursor(null, 'prev').onsuccess = function (e) {
8032 var cursor = e.target.result;
8033 updateSeq = cursor ? cursor.key : 0;
8034 };
8035
8036 txn.oncomplete = function () {
8037 callback(null, {
8038 doc_count: docCount,
8039 update_seq: updateSeq,
8040 // for debugging
8041 idb_attachment_format: (api._meta.blobSupport ? 'binary' : 'base64')
8042 });
8043 };
8044 };
8045
8046 api._allDocs = function idb_allDocs(opts, callback) {
8047 idbAllDocs(opts, idb, callback);
8048 };
8049
8050 api._changes = function idbChanges(opts) {
8051 return changes(opts, api, dbName, idb);
8052 };
8053
8054 api._close = function (callback) {
8055 // https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase#close
8056 // "Returns immediately and closes the connection in a separate thread..."
8057 idb.close();
8058 cachedDBs["delete"](dbName);
8059 callback();
8060 };
8061
8062 api._getRevisionTree = function (docId, callback) {
8063 var txnResult = openTransactionSafely(idb, [DOC_STORE], 'readonly');
8064 if (txnResult.error) {
8065 return callback(txnResult.error);
8066 }
8067 var txn = txnResult.txn;
8068 var req = txn.objectStore(DOC_STORE).get(docId);
8069 req.onsuccess = function (event) {
8070 var doc = decodeMetadata(event.target.result);
8071 if (!doc) {
8072 callback(createError(MISSING_DOC));
8073 } else {
8074 callback(null, doc.rev_tree);
8075 }
8076 };
8077 };
8078
8079 // This function removes revisions of document docId
8080 // which are listed in revs and sets this document
8081 // revision to to rev_tree
8082 api._doCompaction = function (docId, revs, callback) {
8083 var stores = [
8084 DOC_STORE,
8085 BY_SEQ_STORE,
8086 ATTACH_STORE,
8087 ATTACH_AND_SEQ_STORE
8088 ];
8089 var txnResult = openTransactionSafely(idb, stores, 'readwrite');
8090 if (txnResult.error) {
8091 return callback(txnResult.error);
8092 }
8093 var txn = txnResult.txn;
8094
8095 var docStore = txn.objectStore(DOC_STORE);
8096
8097 docStore.get(docId).onsuccess = function (event) {
8098 var metadata = decodeMetadata(event.target.result);
8099 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
8100 revHash, ctx, opts) {
8101 var rev = pos + '-' + revHash;
8102 if (revs.indexOf(rev) !== -1) {
8103 opts.status = 'missing';
8104 }
8105 });
8106 compactRevs(revs, docId, txn);
8107 var winningRev$$1 = metadata.winningRev;
8108 var deleted = metadata.deleted;
8109 txn.objectStore(DOC_STORE).put(
8110 encodeMetadata(metadata, winningRev$$1, deleted));
8111 };
8112 txn.onabort = idbError(callback);
8113 txn.oncomplete = function () {
8114 callback();
8115 };
8116 };
8117
8118
8119 api._getLocal = function (id, callback) {
8120 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readonly');
8121 if (txnResult.error) {
8122 return callback(txnResult.error);
8123 }
8124 var tx = txnResult.txn;
8125 var req = tx.objectStore(LOCAL_STORE).get(id);
8126
8127 req.onerror = idbError(callback);
8128 req.onsuccess = function (e) {
8129 var doc = e.target.result;
8130 if (!doc) {
8131 callback(createError(MISSING_DOC));
8132 } else {
8133 delete doc['_doc_id_rev']; // for backwards compat
8134 callback(null, doc);
8135 }
8136 };
8137 };
8138
8139 api._putLocal = function (doc, opts, callback) {
8140 if (typeof opts === 'function') {
8141 callback = opts;
8142 opts = {};
8143 }
8144 delete doc._revisions; // ignore this, trust the rev
8145 var oldRev = doc._rev;
8146 var id = doc._id;
8147 if (!oldRev) {
8148 doc._rev = '0-1';
8149 } else {
8150 doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1);
8151 }
8152
8153 var tx = opts.ctx;
8154 var ret;
8155 if (!tx) {
8156 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
8157 if (txnResult.error) {
8158 return callback(txnResult.error);
8159 }
8160 tx = txnResult.txn;
8161 tx.onerror = idbError(callback);
8162 tx.oncomplete = function () {
8163 if (ret) {
8164 callback(null, ret);
8165 }
8166 };
8167 }
8168
8169 var oStore = tx.objectStore(LOCAL_STORE);
8170 var req;
8171 if (oldRev) {
8172 req = oStore.get(id);
8173 req.onsuccess = function (e) {
8174 var oldDoc = e.target.result;
8175 if (!oldDoc || oldDoc._rev !== oldRev) {
8176 callback(createError(REV_CONFLICT));
8177 } else { // update
8178 var req = oStore.put(doc);
8179 req.onsuccess = function () {
8180 ret = {ok: true, id: doc._id, rev: doc._rev};
8181 if (opts.ctx) { // return immediately
8182 callback(null, ret);
8183 }
8184 };
8185 }
8186 };
8187 } else { // new doc
8188 req = oStore.add(doc);
8189 req.onerror = function (e) {
8190 // constraint error, already exists
8191 callback(createError(REV_CONFLICT));
8192 e.preventDefault(); // avoid transaction abort
8193 e.stopPropagation(); // avoid transaction onerror
8194 };
8195 req.onsuccess = function () {
8196 ret = {ok: true, id: doc._id, rev: doc._rev};
8197 if (opts.ctx) { // return immediately
8198 callback(null, ret);
8199 }
8200 };
8201 }
8202 };
8203
8204 api._removeLocal = function (doc, opts, callback) {
8205 if (typeof opts === 'function') {
8206 callback = opts;
8207 opts = {};
8208 }
8209 var tx = opts.ctx;
8210 if (!tx) {
8211 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
8212 if (txnResult.error) {
8213 return callback(txnResult.error);
8214 }
8215 tx = txnResult.txn;
8216 tx.oncomplete = function () {
8217 if (ret) {
8218 callback(null, ret);
8219 }
8220 };
8221 }
8222 var ret;
8223 var id = doc._id;
8224 var oStore = tx.objectStore(LOCAL_STORE);
8225 var req = oStore.get(id);
8226
8227 req.onerror = idbError(callback);
8228 req.onsuccess = function (e) {
8229 var oldDoc = e.target.result;
8230 if (!oldDoc || oldDoc._rev !== doc._rev) {
8231 callback(createError(MISSING_DOC));
8232 } else {
8233 oStore["delete"](id);
8234 ret = {ok: true, id: id, rev: '0-0'};
8235 if (opts.ctx) { // return immediately
8236 callback(null, ret);
8237 }
8238 }
8239 };
8240 };
8241
8242 api._destroy = function (opts, callback) {
8243 changesHandler.removeAllListeners(dbName);
8244
8245 //Close open request for "dbName" database to fix ie delay.
8246 var openReq = openReqList.get(dbName);
8247 if (openReq && openReq.result) {
8248 openReq.result.close();
8249 cachedDBs["delete"](dbName);
8250 }
8251 var req = indexedDB.deleteDatabase(dbName);
8252
8253 req.onsuccess = function () {
8254 //Remove open request from the list.
8255 openReqList["delete"](dbName);
8256 if (hasLocalStorage() && (dbName in localStorage)) {
8257 delete localStorage[dbName];
8258 }
8259 callback(null, { 'ok': true });
8260 };
8261
8262 req.onerror = idbError(callback);
8263 };
8264
8265 var cached = cachedDBs.get(dbName);
8266
8267 if (cached) {
8268 idb = cached.idb;
8269 api._meta = cached.global;
8270 return nextTick(function () {
8271 callback(null, api);
8272 });
8273 }
8274
8275 var req = indexedDB.open(dbName, ADAPTER_VERSION);
8276 openReqList.set(dbName, req);
8277
8278 req.onupgradeneeded = function (e) {
8279 var db = e.target.result;
8280 if (e.oldVersion < 1) {
8281 return createSchema(db); // new db, initial schema
8282 }
8283 // do migrations
8284
8285 var txn = e.currentTarget.transaction;
8286 // these migrations have to be done in this function, before
8287 // control is returned to the event loop, because IndexedDB
8288
8289 if (e.oldVersion < 3) {
8290 createLocalStoreSchema(db); // v2 -> v3
8291 }
8292 if (e.oldVersion < 4) {
8293 addAttachAndSeqStore(db); // v3 -> v4
8294 }
8295
8296 var migrations = [
8297 addDeletedOrLocalIndex, // v1 -> v2
8298 migrateLocalStore, // v2 -> v3
8299 migrateAttsAndSeqs, // v3 -> v4
8300 migrateMetadata // v4 -> v5
8301 ];
8302
8303 var i = e.oldVersion;
8304
8305 function next() {
8306 var migration = migrations[i - 1];
8307 i++;
8308 if (migration) {
8309 migration(txn, next);
8310 }
8311 }
8312
8313 next();
8314 };
8315
8316 req.onsuccess = function (e) {
8317
8318 idb = e.target.result;
8319
8320 idb.onversionchange = function () {
8321 idb.close();
8322 cachedDBs["delete"](dbName);
8323 };
8324
8325 idb.onabort = function (e) {
8326 guardedConsole('error', 'Database has a global failure', e.target.error);
8327 idb.close();
8328 cachedDBs["delete"](dbName);
8329 };
8330
8331 // Do a few setup operations (in parallel as much as possible):
8332 // 1. Fetch meta doc
8333 // 2. Check blob support
8334 // 3. Calculate docCount
8335 // 4. Generate an instanceId if necessary
8336 // 5. Store docCount and instanceId on meta doc
8337
8338 var txn = idb.transaction([
8339 META_STORE,
8340 DETECT_BLOB_SUPPORT_STORE,
8341 DOC_STORE
8342 ], 'readwrite');
8343
8344 var storedMetaDoc = false;
8345 var metaDoc;
8346 var docCount;
8347 var blobSupport;
8348 var instanceId;
8349
8350 function completeSetup() {
8351 if (typeof blobSupport === 'undefined' || !storedMetaDoc) {
8352 return;
8353 }
8354 api._meta = {
8355 name: dbName,
8356 instanceId: instanceId,
8357 blobSupport: blobSupport
8358 };
8359
8360 cachedDBs.set(dbName, {
8361 idb: idb,
8362 global: api._meta
8363 });
8364 callback(null, api);
8365 }
8366
8367 function storeMetaDocIfReady() {
8368 if (typeof docCount === 'undefined' || typeof metaDoc === 'undefined') {
8369 return;
8370 }
8371 var instanceKey = dbName + '_id';
8372 if (instanceKey in metaDoc) {
8373 instanceId = metaDoc[instanceKey];
8374 } else {
8375 metaDoc[instanceKey] = instanceId = uuid();
8376 }
8377 metaDoc.docCount = docCount;
8378 txn.objectStore(META_STORE).put(metaDoc);
8379 }
8380
8381 //
8382 // fetch or generate the instanceId
8383 //
8384 txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {
8385 metaDoc = e.target.result || { id: META_STORE };
8386 storeMetaDocIfReady();
8387 };
8388
8389 //
8390 // countDocs
8391 //
8392 countDocs(txn, function (count) {
8393 docCount = count;
8394 storeMetaDocIfReady();
8395 });
8396
8397 //
8398 // check blob support
8399 //
8400 if (!blobSupportPromise) {
8401 // make sure blob support is only checked once
8402 blobSupportPromise = checkBlobSupport(txn);
8403 }
8404
8405 blobSupportPromise.then(function (val) {
8406 blobSupport = val;
8407 completeSetup();
8408 });
8409
8410 // only when the metadata put transaction has completed,
8411 // consider the setup done
8412 txn.oncomplete = function () {
8413 storedMetaDoc = true;
8414 completeSetup();
8415 };
8416 txn.onabort = idbError(callback);
8417 };
8418
8419 req.onerror = function () {
8420 var msg = 'Failed to open indexedDB, are you in private browsing mode?';
8421 guardedConsole('error', msg);
8422 callback(createError(IDB_ERROR, msg));
8423 };
8424}
8425
8426IdbPouch.valid = function () {
8427 // Following #7085 buggy idb versions (typically Safari < 10.1) are
8428 // considered valid.
8429
8430 // On Firefox SecurityError is thrown while referencing indexedDB if cookies
8431 // are not allowed. `typeof indexedDB` also triggers the error.
8432 try {
8433 // some outdated implementations of IDB that appear on Samsung
8434 // and HTC Android devices <4.4 are missing IDBKeyRange
8435 return typeof indexedDB !== 'undefined' && typeof IDBKeyRange !== 'undefined';
8436 } catch (e) {
8437 return false;
8438 }
8439};
8440
8441function IDBPouch (PouchDB) {
8442 PouchDB.adapter('idb', IdbPouch, true);
8443}
8444
8445// dead simple promise pool, inspired by https://github.com/timdp/es6-promise-pool
8446// but much smaller in code size. limits the number of concurrent promises that are executed
8447
8448
8449function pool(promiseFactories, limit) {
8450 return new Promise(function (resolve, reject) {
8451 var running = 0;
8452 var current = 0;
8453 var done = 0;
8454 var len = promiseFactories.length;
8455 var err;
8456
8457 function runNext() {
8458 running++;
8459 promiseFactories[current++]().then(onSuccess, onError);
8460 }
8461
8462 function doNext() {
8463 if (++done === len) {
8464 /* istanbul ignore if */
8465 if (err) {
8466 reject(err);
8467 } else {
8468 resolve();
8469 }
8470 } else {
8471 runNextBatch();
8472 }
8473 }
8474
8475 function onSuccess() {
8476 running--;
8477 doNext();
8478 }
8479
8480 /* istanbul ignore next */
8481 function onError(thisErr) {
8482 running--;
8483 err = err || thisErr;
8484 doNext();
8485 }
8486
8487 function runNextBatch() {
8488 while (running < limit && current < len) {
8489 runNext();
8490 }
8491 }
8492
8493 runNextBatch();
8494 });
8495}
8496
8497var CHANGES_BATCH_SIZE = 25;
8498var MAX_SIMULTANEOUS_REVS = 50;
8499var CHANGES_TIMEOUT_BUFFER = 5000;
8500var DEFAULT_HEARTBEAT = 10000;
8501
8502var supportsBulkGetMap = {};
8503
8504function readAttachmentsAsBlobOrBuffer(row) {
8505 var doc = row.doc || row.ok;
8506 var atts = doc._attachments;
8507 if (!atts) {
8508 return;
8509 }
8510 Object.keys(atts).forEach(function (filename) {
8511 var att = atts[filename];
8512 att.data = b64ToBluffer(att.data, att.content_type);
8513 });
8514}
8515
8516function encodeDocId(id) {
8517 if (/^_design/.test(id)) {
8518 return '_design/' + encodeURIComponent(id.slice(8));
8519 }
8520 if (/^_local/.test(id)) {
8521 return '_local/' + encodeURIComponent(id.slice(7));
8522 }
8523 return encodeURIComponent(id);
8524}
8525
8526function preprocessAttachments$1(doc) {
8527 if (!doc._attachments || !Object.keys(doc._attachments)) {
8528 return Promise.resolve();
8529 }
8530
8531 return Promise.all(Object.keys(doc._attachments).map(function (key) {
8532 var attachment = doc._attachments[key];
8533 if (attachment.data && typeof attachment.data !== 'string') {
8534 return new Promise(function (resolve) {
8535 blobToBase64(attachment.data, resolve);
8536 }).then(function (b64) {
8537 attachment.data = b64;
8538 });
8539 }
8540 }));
8541}
8542
8543function hasUrlPrefix(opts) {
8544 if (!opts.prefix) {
8545 return false;
8546 }
8547 var protocol = parseUri(opts.prefix).protocol;
8548 return protocol === 'http' || protocol === 'https';
8549}
8550
8551// Get all the information you possibly can about the URI given by name and
8552// return it as a suitable object.
8553function getHost(name, opts) {
8554 // encode db name if opts.prefix is a url (#5574)
8555 if (hasUrlPrefix(opts)) {
8556 var dbName = opts.name.substr(opts.prefix.length);
8557 // Ensure prefix has a trailing slash
8558 var prefix = opts.prefix.replace(/\/?$/, '/');
8559 name = prefix + encodeURIComponent(dbName);
8560 }
8561
8562 var uri = parseUri(name);
8563 if (uri.user || uri.password) {
8564 uri.auth = {username: uri.user, password: uri.password};
8565 }
8566
8567 // Split the path part of the URI into parts using '/' as the delimiter
8568 // after removing any leading '/' and any trailing '/'
8569 var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/');
8570
8571 uri.db = parts.pop();
8572 // Prevent double encoding of URI component
8573 if (uri.db.indexOf('%') === -1) {
8574 uri.db = encodeURIComponent(uri.db);
8575 }
8576
8577 uri.path = parts.join('/');
8578
8579 return uri;
8580}
8581
8582// Generate a URL with the host data given by opts and the given path
8583function genDBUrl(opts, path) {
8584 return genUrl(opts, opts.db + '/' + path);
8585}
8586
8587// Generate a URL with the host data given by opts and the given path
8588function genUrl(opts, path) {
8589 // If the host already has a path, then we need to have a path delimiter
8590 // Otherwise, the path delimiter is the empty string
8591 var pathDel = !opts.path ? '' : '/';
8592
8593 // If the host already has a path, then we need to have a path delimiter
8594 // Otherwise, the path delimiter is the empty string
8595 return opts.protocol + '://' + opts.host +
8596 (opts.port ? (':' + opts.port) : '') +
8597 '/' + opts.path + pathDel + path;
8598}
8599
8600function paramsToStr(params) {
8601 return '?' + Object.keys(params).map(function (k) {
8602 return k + '=' + encodeURIComponent(params[k]);
8603 }).join('&');
8604}
8605
8606function shouldCacheBust(opts) {
8607 var ua = (typeof navigator !== 'undefined' && navigator.userAgent) ?
8608 navigator.userAgent.toLowerCase() : '';
8609 var isIE = ua.indexOf('msie') !== -1;
8610 var isTrident = ua.indexOf('trident') !== -1;
8611 var isEdge = ua.indexOf('edge') !== -1;
8612 var isGET = !('method' in opts) || opts.method === 'GET';
8613 return (isIE || isTrident || isEdge) && isGET;
8614}
8615
8616// Implements the PouchDB API for dealing with CouchDB instances over HTTP
8617function HttpPouch(opts, callback) {
8618
8619 // The functions that will be publicly available for HttpPouch
8620 var api = this;
8621
8622 var host = getHost(opts.name, opts);
8623 var dbUrl = genDBUrl(host, '');
8624
8625 opts = clone(opts);
8626
8627 var ourFetch = function (url, options) {
8628
8629 options = options || {};
8630 options.headers = options.headers || new h();
8631
8632 if (opts.auth || host.auth) {
8633 var nAuth = opts.auth || host.auth;
8634 var str = nAuth.username + ':' + nAuth.password;
8635 var token = thisBtoa(unescape(encodeURIComponent(str)));
8636 options.headers.set('Authorization', 'Basic ' + token);
8637 }
8638
8639 var headers = opts.headers || {};
8640 Object.keys(headers).forEach(function (key) {
8641 options.headers.append(key, headers[key]);
8642 });
8643
8644 /* istanbul ignore if */
8645 if (shouldCacheBust(options)) {
8646 url += (url.indexOf('?') === -1 ? '?' : '&') + '_nonce=' + Date.now();
8647 }
8648
8649 var fetchFun = opts.fetch || f$1;
8650 return fetchFun(url, options);
8651 };
8652
8653 function adapterFun$$1(name, fun) {
8654 return adapterFun(name, getArguments(function (args) {
8655 setup().then(function () {
8656 return fun.apply(this, args);
8657 })["catch"](function (e) {
8658 var callback = args.pop();
8659 callback(e);
8660 });
8661 })).bind(api);
8662 }
8663
8664 function fetchJSON(url, options, callback) {
8665
8666 var result = {};
8667
8668 options = options || {};
8669 options.headers = options.headers || new h();
8670
8671 if (!options.headers.get('Content-Type')) {
8672 options.headers.set('Content-Type', 'application/json');
8673 }
8674 if (!options.headers.get('Accept')) {
8675 options.headers.set('Accept', 'application/json');
8676 }
8677
8678 return ourFetch(url, options).then(function (response) {
8679 result.ok = response.ok;
8680 result.status = response.status;
8681 return response.json();
8682 }).then(function (json) {
8683 result.data = json;
8684 if (!result.ok) {
8685 result.data.status = result.status;
8686 var err = generateErrorFromResponse(result.data);
8687 if (callback) {
8688 return callback(err);
8689 } else {
8690 throw err;
8691 }
8692 }
8693
8694 if (Array.isArray(result.data)) {
8695 result.data = result.data.map(function (v) {
8696 if (v.error || v.missing) {
8697 return generateErrorFromResponse(v);
8698 } else {
8699 return v;
8700 }
8701 });
8702 }
8703
8704 if (callback) {
8705 callback(null, result.data);
8706 } else {
8707 return result;
8708 }
8709 });
8710 }
8711
8712 var setupPromise;
8713
8714 function setup() {
8715 if (opts.skip_setup) {
8716 return Promise.resolve();
8717 }
8718
8719 // If there is a setup in process or previous successful setup
8720 // done then we will use that
8721 // If previous setups have been rejected we will try again
8722 if (setupPromise) {
8723 return setupPromise;
8724 }
8725
8726 setupPromise = fetchJSON(dbUrl)["catch"](function (err) {
8727 if (err && err.status && err.status === 404) {
8728 // Doesnt exist, create it
8729 explainError(404, 'PouchDB is just detecting if the remote exists.');
8730 return fetchJSON(dbUrl, {method: 'PUT'});
8731 } else {
8732 return Promise.reject(err);
8733 }
8734 })["catch"](function (err) {
8735 // If we try to create a database that already exists, skipped in
8736 // istanbul since its catching a race condition.
8737 /* istanbul ignore if */
8738 if (err && err.status && err.status === 412) {
8739 return true;
8740 }
8741 return Promise.reject(err);
8742 });
8743
8744 setupPromise["catch"](function () {
8745 setupPromise = null;
8746 });
8747
8748 return setupPromise;
8749 }
8750
8751 nextTick(function () {
8752 callback(null, api);
8753 });
8754
8755 api._remote = true;
8756
8757 /* istanbul ignore next */
8758 api.type = function () {
8759 return 'http';
8760 };
8761
8762 api.id = adapterFun$$1('id', function (callback) {
8763 ourFetch(genUrl(host, '')).then(function (response) {
8764 return response.json();
8765 }).then(function (result) {
8766 var uuid$$1 = (result && result.uuid) ?
8767 (result.uuid + host.db) : genDBUrl(host, '');
8768 callback(null, uuid$$1);
8769 })["catch"](function (err) {
8770 callback(err);
8771 });
8772 });
8773
8774 // Sends a POST request to the host calling the couchdb _compact function
8775 // version: The version of CouchDB it is running
8776 api.compact = adapterFun$$1('compact', function (opts, callback) {
8777 if (typeof opts === 'function') {
8778 callback = opts;
8779 opts = {};
8780 }
8781 opts = clone(opts);
8782
8783 fetchJSON(genDBUrl(host, '_compact'), {method: 'POST'}).then(function () {
8784 function ping() {
8785 api.info(function (err, res) {
8786 // CouchDB may send a "compact_running:true" if it's
8787 // already compacting. PouchDB Server doesn't.
8788 /* istanbul ignore else */
8789 if (res && !res.compact_running) {
8790 callback(null, {ok: true});
8791 } else {
8792 setTimeout(ping, opts.interval || 200);
8793 }
8794 });
8795 }
8796 // Ping the http if it's finished compaction
8797 ping();
8798 });
8799 });
8800
8801 api.bulkGet = adapterFun('bulkGet', function (opts, callback) {
8802 var self = this;
8803
8804 function doBulkGet(cb) {
8805 var params = {};
8806 if (opts.revs) {
8807 params.revs = true;
8808 }
8809 if (opts.attachments) {
8810 /* istanbul ignore next */
8811 params.attachments = true;
8812 }
8813 if (opts.latest) {
8814 params.latest = true;
8815 }
8816 fetchJSON(genDBUrl(host, '_bulk_get' + paramsToStr(params)), {
8817 method: 'POST',
8818 body: JSON.stringify({ docs: opts.docs})
8819 }).then(function (result) {
8820 if (opts.attachments && opts.binary) {
8821 result.data.results.forEach(function (res) {
8822 res.docs.forEach(readAttachmentsAsBlobOrBuffer);
8823 });
8824 }
8825 cb(null, result.data);
8826 })["catch"](cb);
8827 }
8828
8829 /* istanbul ignore next */
8830 function doBulkGetShim() {
8831 // avoid "url too long error" by splitting up into multiple requests
8832 var batchSize = MAX_SIMULTANEOUS_REVS;
8833 var numBatches = Math.ceil(opts.docs.length / batchSize);
8834 var numDone = 0;
8835 var results = new Array(numBatches);
8836
8837 function onResult(batchNum) {
8838 return function (err, res) {
8839 // err is impossible because shim returns a list of errs in that case
8840 results[batchNum] = res.results;
8841 if (++numDone === numBatches) {
8842 callback(null, {results: flatten(results)});
8843 }
8844 };
8845 }
8846
8847 for (var i = 0; i < numBatches; i++) {
8848 var subOpts = pick(opts, ['revs', 'attachments', 'binary', 'latest']);
8849 subOpts.docs = opts.docs.slice(i * batchSize,
8850 Math.min(opts.docs.length, (i + 1) * batchSize));
8851 bulkGet(self, subOpts, onResult(i));
8852 }
8853 }
8854
8855 // mark the whole database as either supporting or not supporting _bulk_get
8856 var dbUrl = genUrl(host, '');
8857 var supportsBulkGet = supportsBulkGetMap[dbUrl];
8858
8859 /* istanbul ignore next */
8860 if (typeof supportsBulkGet !== 'boolean') {
8861 // check if this database supports _bulk_get
8862 doBulkGet(function (err, res) {
8863 if (err) {
8864 supportsBulkGetMap[dbUrl] = false;
8865 explainError(
8866 err.status,
8867 'PouchDB is just detecting if the remote ' +
8868 'supports the _bulk_get API.'
8869 );
8870 doBulkGetShim();
8871 } else {
8872 supportsBulkGetMap[dbUrl] = true;
8873 callback(null, res);
8874 }
8875 });
8876 } else if (supportsBulkGet) {
8877 doBulkGet(callback);
8878 } else {
8879 doBulkGetShim();
8880 }
8881 });
8882
8883 // Calls GET on the host, which gets back a JSON string containing
8884 // couchdb: A welcome string
8885 // version: The version of CouchDB it is running
8886 api._info = function (callback) {
8887 setup().then(function () {
8888 return ourFetch(genDBUrl(host, ''));
8889 }).then(function (response) {
8890 return response.json();
8891 }).then(function (info) {
8892 info.host = genDBUrl(host, '');
8893 callback(null, info);
8894 })["catch"](callback);
8895 };
8896
8897 api.fetch = function (path, options) {
8898 return setup().then(function () {
8899 return ourFetch(genDBUrl(host, path), options);
8900 });
8901 };
8902
8903 // Get the document with the given id from the database given by host.
8904 // The id could be solely the _id in the database, or it may be a
8905 // _design/ID or _local/ID path
8906 api.get = adapterFun$$1('get', function (id, opts, callback) {
8907 // If no options were given, set the callback to the second parameter
8908 if (typeof opts === 'function') {
8909 callback = opts;
8910 opts = {};
8911 }
8912 opts = clone(opts);
8913
8914 // List of parameters to add to the GET request
8915 var params = {};
8916
8917 if (opts.revs) {
8918 params.revs = true;
8919 }
8920
8921 if (opts.revs_info) {
8922 params.revs_info = true;
8923 }
8924
8925 if (opts.latest) {
8926 params.latest = true;
8927 }
8928
8929 if (opts.open_revs) {
8930 if (opts.open_revs !== "all") {
8931 opts.open_revs = JSON.stringify(opts.open_revs);
8932 }
8933 params.open_revs = opts.open_revs;
8934 }
8935
8936 if (opts.rev) {
8937 params.rev = opts.rev;
8938 }
8939
8940 if (opts.conflicts) {
8941 params.conflicts = opts.conflicts;
8942 }
8943
8944 /* istanbul ignore if */
8945 if (opts.update_seq) {
8946 params.update_seq = opts.update_seq;
8947 }
8948
8949 id = encodeDocId(id);
8950
8951 function fetchAttachments(doc) {
8952 var atts = doc._attachments;
8953 var filenames = atts && Object.keys(atts);
8954 if (!atts || !filenames.length) {
8955 return;
8956 }
8957 // we fetch these manually in separate XHRs, because
8958 // Sync Gateway would normally send it back as multipart/mixed,
8959 // which we cannot parse. Also, this is more efficient than
8960 // receiving attachments as base64-encoded strings.
8961 function fetchData(filename) {
8962 var att = atts[filename];
8963 var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +
8964 '?rev=' + doc._rev;
8965 return ourFetch(genDBUrl(host, path)).then(function (response) {
8966 if (typeof process !== 'undefined' && !process.browser) {
8967 return response.buffer();
8968 } else {
8969 /* istanbul ignore next */
8970 return response.blob();
8971 }
8972 }).then(function (blob) {
8973 if (opts.binary) {
8974 // TODO: Can we remove this?
8975 if (typeof process !== 'undefined' && !process.browser) {
8976 blob.type = att.content_type;
8977 }
8978 return blob;
8979 }
8980 return new Promise(function (resolve) {
8981 blobToBase64(blob, resolve);
8982 });
8983 }).then(function (data) {
8984 delete att.stub;
8985 delete att.length;
8986 att.data = data;
8987 });
8988 }
8989
8990 var promiseFactories = filenames.map(function (filename) {
8991 return function () {
8992 return fetchData(filename);
8993 };
8994 });
8995
8996 // This limits the number of parallel xhr requests to 5 any time
8997 // to avoid issues with maximum browser request limits
8998 return pool(promiseFactories, 5);
8999 }
9000
9001 function fetchAllAttachments(docOrDocs) {
9002 if (Array.isArray(docOrDocs)) {
9003 return Promise.all(docOrDocs.map(function (doc) {
9004 if (doc.ok) {
9005 return fetchAttachments(doc.ok);
9006 }
9007 }));
9008 }
9009 return fetchAttachments(docOrDocs);
9010 }
9011
9012 var url = genDBUrl(host, id + paramsToStr(params));
9013 fetchJSON(url).then(function (res) {
9014 return Promise.resolve().then(function () {
9015 if (opts.attachments) {
9016 return fetchAllAttachments(res.data);
9017 }
9018 }).then(function () {
9019 callback(null, res.data);
9020 });
9021 })["catch"](function (e) {
9022 e.docId = id;
9023 callback(e);
9024 });
9025 });
9026
9027
9028 // Delete the document given by doc from the database given by host.
9029 api.remove = adapterFun$$1('remove', function (docOrId, optsOrRev, opts, cb) {
9030 var doc;
9031 if (typeof optsOrRev === 'string') {
9032 // id, rev, opts, callback style
9033 doc = {
9034 _id: docOrId,
9035 _rev: optsOrRev
9036 };
9037 if (typeof opts === 'function') {
9038 cb = opts;
9039 opts = {};
9040 }
9041 } else {
9042 // doc, opts, callback style
9043 doc = docOrId;
9044 if (typeof optsOrRev === 'function') {
9045 cb = optsOrRev;
9046 opts = {};
9047 } else {
9048 cb = opts;
9049 opts = optsOrRev;
9050 }
9051 }
9052
9053 var rev = (doc._rev || opts.rev);
9054 var url = genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev;
9055
9056 fetchJSON(url, {method: 'DELETE'}, cb)["catch"](cb);
9057 });
9058
9059 function encodeAttachmentId(attachmentId) {
9060 return attachmentId.split("/").map(encodeURIComponent).join("/");
9061 }
9062
9063 // Get the attachment
9064 api.getAttachment = adapterFun$$1('getAttachment', function (docId, attachmentId,
9065 opts, callback) {
9066 if (typeof opts === 'function') {
9067 callback = opts;
9068 opts = {};
9069 }
9070 var params = opts.rev ? ('?rev=' + opts.rev) : '';
9071 var url = genDBUrl(host, encodeDocId(docId)) + '/' +
9072 encodeAttachmentId(attachmentId) + params;
9073 var contentType;
9074 ourFetch(url, {method: 'GET'}).then(function (response) {
9075 contentType = response.headers.get('content-type');
9076 if (!response.ok) {
9077 throw response;
9078 } else {
9079 if (typeof process !== 'undefined' && !process.browser) {
9080 return response.buffer();
9081 } else {
9082 /* istanbul ignore next */
9083 return response.blob();
9084 }
9085 }
9086 }).then(function (blob) {
9087 // TODO: also remove
9088 if (typeof process !== 'undefined' && !process.browser) {
9089 blob.type = contentType;
9090 }
9091 callback(null, blob);
9092 })["catch"](function (err) {
9093 callback(err);
9094 });
9095 });
9096
9097 // Remove the attachment given by the id and rev
9098 api.removeAttachment = adapterFun$$1('removeAttachment', function (docId,
9099 attachmentId,
9100 rev,
9101 callback) {
9102 var url = genDBUrl(host, encodeDocId(docId) + '/' +
9103 encodeAttachmentId(attachmentId)) + '?rev=' + rev;
9104 fetchJSON(url, {method: 'DELETE'}, callback)["catch"](callback);
9105 });
9106
9107 // Add the attachment given by blob and its contentType property
9108 // to the document with the given id, the revision given by rev, and
9109 // add it to the database given by host.
9110 api.putAttachment = adapterFun$$1('putAttachment', function (docId, attachmentId,
9111 rev, blob,
9112 type, callback) {
9113 if (typeof type === 'function') {
9114 callback = type;
9115 type = blob;
9116 blob = rev;
9117 rev = null;
9118 }
9119 var id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId);
9120 var url = genDBUrl(host, id);
9121 if (rev) {
9122 url += '?rev=' + rev;
9123 }
9124
9125 if (typeof blob === 'string') {
9126 // input is assumed to be a base64 string
9127 var binary;
9128 try {
9129 binary = thisAtob(blob);
9130 } catch (err) {
9131 return callback(createError(BAD_ARG,
9132 'Attachment is not a valid base64 string'));
9133 }
9134 blob = binary ? binStringToBluffer(binary, type) : '';
9135 }
9136
9137 // Add the attachment
9138 fetchJSON(url, {
9139 headers: new h({'Content-Type': type}),
9140 method: 'PUT',
9141 body: blob
9142 }, callback)["catch"](callback);
9143 });
9144
9145 // Update/create multiple documents given by req in the database
9146 // given by host.
9147 api._bulkDocs = function (req, opts, callback) {
9148 // If new_edits=false then it prevents the database from creating
9149 // new revision numbers for the documents. Instead it just uses
9150 // the old ones. This is used in database replication.
9151 req.new_edits = opts.new_edits;
9152
9153 setup().then(function () {
9154 return Promise.all(req.docs.map(preprocessAttachments$1));
9155 }).then(function () {
9156 // Update/create the documents
9157 return fetchJSON(genDBUrl(host, '_bulk_docs'), {
9158 method: 'POST',
9159 body: JSON.stringify(req)
9160 }, callback);
9161 })["catch"](callback);
9162 };
9163
9164
9165 // Update/create document
9166 api._put = function (doc, opts, callback) {
9167 setup().then(function () {
9168 return preprocessAttachments$1(doc);
9169 }).then(function () {
9170 return fetchJSON(genDBUrl(host, encodeDocId(doc._id)), {
9171 method: 'PUT',
9172 body: JSON.stringify(doc)
9173 });
9174 }).then(function (result) {
9175 callback(null, result.data);
9176 })["catch"](function (err) {
9177 err.docId = doc && doc._id;
9178 callback(err);
9179 });
9180 };
9181
9182
9183 // Get a listing of the documents in the database given
9184 // by host and ordered by increasing id.
9185 api.allDocs = adapterFun$$1('allDocs', function (opts, callback) {
9186 if (typeof opts === 'function') {
9187 callback = opts;
9188 opts = {};
9189 }
9190 opts = clone(opts);
9191
9192 // List of parameters to add to the GET request
9193 var params = {};
9194 var body;
9195 var method = 'GET';
9196
9197 if (opts.conflicts) {
9198 params.conflicts = true;
9199 }
9200
9201 /* istanbul ignore if */
9202 if (opts.update_seq) {
9203 params.update_seq = true;
9204 }
9205
9206 if (opts.descending) {
9207 params.descending = true;
9208 }
9209
9210 if (opts.include_docs) {
9211 params.include_docs = true;
9212 }
9213
9214 // added in CouchDB 1.6.0
9215 if (opts.attachments) {
9216 params.attachments = true;
9217 }
9218
9219 if (opts.key) {
9220 params.key = JSON.stringify(opts.key);
9221 }
9222
9223 if (opts.start_key) {
9224 opts.startkey = opts.start_key;
9225 }
9226
9227 if (opts.startkey) {
9228 params.startkey = JSON.stringify(opts.startkey);
9229 }
9230
9231 if (opts.end_key) {
9232 opts.endkey = opts.end_key;
9233 }
9234
9235 if (opts.endkey) {
9236 params.endkey = JSON.stringify(opts.endkey);
9237 }
9238
9239 if (typeof opts.inclusive_end !== 'undefined') {
9240 params.inclusive_end = !!opts.inclusive_end;
9241 }
9242
9243 if (typeof opts.limit !== 'undefined') {
9244 params.limit = opts.limit;
9245 }
9246
9247 if (typeof opts.skip !== 'undefined') {
9248 params.skip = opts.skip;
9249 }
9250
9251 var paramStr = paramsToStr(params);
9252
9253 if (typeof opts.keys !== 'undefined') {
9254 method = 'POST';
9255 body = {keys: opts.keys};
9256 }
9257
9258 fetchJSON(genDBUrl(host, '_all_docs' + paramStr), {
9259 method: method,
9260 body: JSON.stringify(body)
9261 }).then(function (result) {
9262 if (opts.include_docs && opts.attachments && opts.binary) {
9263 result.data.rows.forEach(readAttachmentsAsBlobOrBuffer);
9264 }
9265 callback(null, result.data);
9266 })["catch"](callback);
9267 });
9268
9269 // Get a list of changes made to documents in the database given by host.
9270 // TODO According to the README, there should be two other methods here,
9271 // api.changes.addListener and api.changes.removeListener.
9272 api._changes = function (opts) {
9273
9274 // We internally page the results of a changes request, this means
9275 // if there is a large set of changes to be returned we can start
9276 // processing them quicker instead of waiting on the entire
9277 // set of changes to return and attempting to process them at once
9278 var batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE;
9279
9280 opts = clone(opts);
9281
9282 if (opts.continuous && !('heartbeat' in opts)) {
9283 opts.heartbeat = DEFAULT_HEARTBEAT;
9284 }
9285
9286 var requestTimeout = ('timeout' in opts) ? opts.timeout : 30 * 1000;
9287
9288 // ensure CHANGES_TIMEOUT_BUFFER applies
9289 if ('timeout' in opts && opts.timeout &&
9290 (requestTimeout - opts.timeout) < CHANGES_TIMEOUT_BUFFER) {
9291 requestTimeout = opts.timeout + CHANGES_TIMEOUT_BUFFER;
9292 }
9293
9294 /* istanbul ignore if */
9295 if ('heartbeat' in opts && opts.heartbeat &&
9296 (requestTimeout - opts.heartbeat) < CHANGES_TIMEOUT_BUFFER) {
9297 requestTimeout = opts.heartbeat + CHANGES_TIMEOUT_BUFFER;
9298 }
9299
9300 var params = {};
9301 if ('timeout' in opts && opts.timeout) {
9302 params.timeout = opts.timeout;
9303 }
9304
9305 var limit = (typeof opts.limit !== 'undefined') ? opts.limit : false;
9306 var leftToFetch = limit;
9307
9308 if (opts.style) {
9309 params.style = opts.style;
9310 }
9311
9312 if (opts.include_docs || opts.filter && typeof opts.filter === 'function') {
9313 params.include_docs = true;
9314 }
9315
9316 if (opts.attachments) {
9317 params.attachments = true;
9318 }
9319
9320 if (opts.continuous) {
9321 params.feed = 'longpoll';
9322 }
9323
9324 if (opts.seq_interval) {
9325 params.seq_interval = opts.seq_interval;
9326 }
9327
9328 if (opts.conflicts) {
9329 params.conflicts = true;
9330 }
9331
9332 if (opts.descending) {
9333 params.descending = true;
9334 }
9335
9336 /* istanbul ignore if */
9337 if (opts.update_seq) {
9338 params.update_seq = true;
9339 }
9340
9341 if ('heartbeat' in opts) {
9342 // If the heartbeat value is false, it disables the default heartbeat
9343 if (opts.heartbeat) {
9344 params.heartbeat = opts.heartbeat;
9345 }
9346 }
9347
9348 if (opts.filter && typeof opts.filter === 'string') {
9349 params.filter = opts.filter;
9350 }
9351
9352 if (opts.view && typeof opts.view === 'string') {
9353 params.filter = '_view';
9354 params.view = opts.view;
9355 }
9356
9357 // If opts.query_params exists, pass it through to the changes request.
9358 // These parameters may be used by the filter on the source database.
9359 if (opts.query_params && typeof opts.query_params === 'object') {
9360 for (var param_name in opts.query_params) {
9361 /* istanbul ignore else */
9362 if (opts.query_params.hasOwnProperty(param_name)) {
9363 params[param_name] = opts.query_params[param_name];
9364 }
9365 }
9366 }
9367
9368 var method = 'GET';
9369 var body;
9370
9371 if (opts.doc_ids) {
9372 // set this automagically for the user; it's annoying that couchdb
9373 // requires both a "filter" and a "doc_ids" param.
9374 params.filter = '_doc_ids';
9375 method = 'POST';
9376 body = {doc_ids: opts.doc_ids };
9377 }
9378 /* istanbul ignore next */
9379 else if (opts.selector) {
9380 // set this automagically for the user, similar to above
9381 params.filter = '_selector';
9382 method = 'POST';
9383 body = {selector: opts.selector };
9384 }
9385
9386 var controller = new a();
9387 var lastFetchedSeq;
9388
9389 // Get all the changes starting wtih the one immediately after the
9390 // sequence number given by since.
9391 var fetchData = function (since, callback) {
9392 if (opts.aborted) {
9393 return;
9394 }
9395 params.since = since;
9396 // "since" can be any kind of json object in Cloudant/CouchDB 2.x
9397 /* istanbul ignore next */
9398 if (typeof params.since === "object") {
9399 params.since = JSON.stringify(params.since);
9400 }
9401
9402 if (opts.descending) {
9403 if (limit) {
9404 params.limit = leftToFetch;
9405 }
9406 } else {
9407 params.limit = (!limit || leftToFetch > batchSize) ?
9408 batchSize : leftToFetch;
9409 }
9410
9411 // Set the options for the ajax call
9412 var url = genDBUrl(host, '_changes' + paramsToStr(params));
9413 var fetchOpts = {
9414 signal: controller.signal,
9415 method: method,
9416 body: JSON.stringify(body)
9417 };
9418 lastFetchedSeq = since;
9419
9420 /* istanbul ignore if */
9421 if (opts.aborted) {
9422 return;
9423 }
9424
9425 // Get the changes
9426 setup().then(function () {
9427 return fetchJSON(url, fetchOpts, callback);
9428 })["catch"](callback);
9429 };
9430
9431 // If opts.since exists, get all the changes from the sequence
9432 // number given by opts.since. Otherwise, get all the changes
9433 // from the sequence number 0.
9434 var results = {results: []};
9435
9436 var fetched = function (err, res) {
9437 if (opts.aborted) {
9438 return;
9439 }
9440 var raw_results_length = 0;
9441 // If the result of the ajax call (res) contains changes (res.results)
9442 if (res && res.results) {
9443 raw_results_length = res.results.length;
9444 results.last_seq = res.last_seq;
9445 var pending = null;
9446 var lastSeq = null;
9447 // Attach 'pending' property if server supports it (CouchDB 2.0+)
9448 /* istanbul ignore if */
9449 if (typeof res.pending === 'number') {
9450 pending = res.pending;
9451 }
9452 if (typeof results.last_seq === 'string' || typeof results.last_seq === 'number') {
9453 lastSeq = results.last_seq;
9454 }
9455 // For each change
9456 var req = {};
9457 req.query = opts.query_params;
9458 res.results = res.results.filter(function (c) {
9459 leftToFetch--;
9460 var ret = filterChange(opts)(c);
9461 if (ret) {
9462 if (opts.include_docs && opts.attachments && opts.binary) {
9463 readAttachmentsAsBlobOrBuffer(c);
9464 }
9465 if (opts.return_docs) {
9466 results.results.push(c);
9467 }
9468 opts.onChange(c, pending, lastSeq);
9469 }
9470 return ret;
9471 });
9472 } else if (err) {
9473 // In case of an error, stop listening for changes and call
9474 // opts.complete
9475 opts.aborted = true;
9476 opts.complete(err);
9477 return;
9478 }
9479
9480 // The changes feed may have timed out with no results
9481 // if so reuse last update sequence
9482 if (res && res.last_seq) {
9483 lastFetchedSeq = res.last_seq;
9484 }
9485
9486 var finished = (limit && leftToFetch <= 0) ||
9487 (res && raw_results_length < batchSize) ||
9488 (opts.descending);
9489
9490 if ((opts.continuous && !(limit && leftToFetch <= 0)) || !finished) {
9491 // Queue a call to fetch again with the newest sequence number
9492 nextTick(function () { fetchData(lastFetchedSeq, fetched); });
9493 } else {
9494 // We're done, call the callback
9495 opts.complete(null, results);
9496 }
9497 };
9498
9499 fetchData(opts.since || 0, fetched);
9500
9501 // Return a method to cancel this method from processing any more
9502 return {
9503 cancel: function () {
9504 opts.aborted = true;
9505 controller.abort();
9506 }
9507 };
9508 };
9509
9510 // Given a set of document/revision IDs (given by req), tets the subset of
9511 // those that do NOT correspond to revisions stored in the database.
9512 // See http://wiki.apache.org/couchdb/HttpPostRevsDiff
9513 api.revsDiff = adapterFun$$1('revsDiff', function (req, opts, callback) {
9514 // If no options were given, set the callback to be the second parameter
9515 if (typeof opts === 'function') {
9516 callback = opts;
9517 opts = {};
9518 }
9519
9520 // Get the missing document/revision IDs
9521 fetchJSON(genDBUrl(host, '_revs_diff'), {
9522 method: 'POST',
9523 body: JSON.stringify(req)
9524 }, callback)["catch"](callback);
9525 });
9526
9527 api._close = function (callback) {
9528 callback();
9529 };
9530
9531 api._destroy = function (options, callback) {
9532 fetchJSON(genDBUrl(host, ''), {method: 'DELETE'}).then(function (json) {
9533 callback(null, json);
9534 })["catch"](function (err) {
9535 /* istanbul ignore if */
9536 if (err.status === 404) {
9537 callback(null, {ok: true});
9538 } else {
9539 callback(err);
9540 }
9541 });
9542 };
9543}
9544
9545// HttpPouch is a valid adapter.
9546HttpPouch.valid = function () {
9547 return true;
9548};
9549
9550function HttpPouch$1 (PouchDB) {
9551 PouchDB.adapter('http', HttpPouch, false);
9552 PouchDB.adapter('https', HttpPouch, false);
9553}
9554
9555function QueryParseError(message) {
9556 this.status = 400;
9557 this.name = 'query_parse_error';
9558 this.message = message;
9559 this.error = true;
9560 try {
9561 Error.captureStackTrace(this, QueryParseError);
9562 } catch (e) {}
9563}
9564
9565inherits(QueryParseError, Error);
9566
9567function NotFoundError(message) {
9568 this.status = 404;
9569 this.name = 'not_found';
9570 this.message = message;
9571 this.error = true;
9572 try {
9573 Error.captureStackTrace(this, NotFoundError);
9574 } catch (e) {}
9575}
9576
9577inherits(NotFoundError, Error);
9578
9579function BuiltInError(message) {
9580 this.status = 500;
9581 this.name = 'invalid_value';
9582 this.message = message;
9583 this.error = true;
9584 try {
9585 Error.captureStackTrace(this, BuiltInError);
9586 } catch (e) {}
9587}
9588
9589inherits(BuiltInError, Error);
9590
9591function promisedCallback(promise, callback) {
9592 if (callback) {
9593 promise.then(function (res) {
9594 nextTick(function () {
9595 callback(null, res);
9596 });
9597 }, function (reason) {
9598 nextTick(function () {
9599 callback(reason);
9600 });
9601 });
9602 }
9603 return promise;
9604}
9605
9606function callbackify(fun) {
9607 return getArguments(function (args) {
9608 var cb = args.pop();
9609 var promise = fun.apply(this, args);
9610 if (typeof cb === 'function') {
9611 promisedCallback(promise, cb);
9612 }
9613 return promise;
9614 });
9615}
9616
9617// Promise finally util similar to Q.finally
9618function fin(promise, finalPromiseFactory) {
9619 return promise.then(function (res) {
9620 return finalPromiseFactory().then(function () {
9621 return res;
9622 });
9623 }, function (reason) {
9624 return finalPromiseFactory().then(function () {
9625 throw reason;
9626 });
9627 });
9628}
9629
9630function sequentialize(queue, promiseFactory) {
9631 return function () {
9632 var args = arguments;
9633 var that = this;
9634 return queue.add(function () {
9635 return promiseFactory.apply(that, args);
9636 });
9637 };
9638}
9639
9640// uniq an array of strings, order not guaranteed
9641// similar to underscore/lodash _.uniq
9642function uniq(arr) {
9643 var theSet = new ExportedSet(arr);
9644 var result = new Array(theSet.size);
9645 var index = -1;
9646 theSet.forEach(function (value) {
9647 result[++index] = value;
9648 });
9649 return result;
9650}
9651
9652function mapToKeysArray(map) {
9653 var result = new Array(map.size);
9654 var index = -1;
9655 map.forEach(function (value, key) {
9656 result[++index] = key;
9657 });
9658 return result;
9659}
9660
9661function createBuiltInError(name) {
9662 var message = 'builtin ' + name +
9663 ' function requires map values to be numbers' +
9664 ' or number arrays';
9665 return new BuiltInError(message);
9666}
9667
9668function sum(values) {
9669 var result = 0;
9670 for (var i = 0, len = values.length; i < len; i++) {
9671 var num = values[i];
9672 if (typeof num !== 'number') {
9673 if (Array.isArray(num)) {
9674 // lists of numbers are also allowed, sum them separately
9675 result = typeof result === 'number' ? [result] : result;
9676 for (var j = 0, jLen = num.length; j < jLen; j++) {
9677 var jNum = num[j];
9678 if (typeof jNum !== 'number') {
9679 throw createBuiltInError('_sum');
9680 } else if (typeof result[j] === 'undefined') {
9681 result.push(jNum);
9682 } else {
9683 result[j] += jNum;
9684 }
9685 }
9686 } else { // not array/number
9687 throw createBuiltInError('_sum');
9688 }
9689 } else if (typeof result === 'number') {
9690 result += num;
9691 } else { // add number to array
9692 result[0] += num;
9693 }
9694 }
9695 return result;
9696}
9697
9698var log = guardedConsole.bind(null, 'log');
9699var isArray = Array.isArray;
9700var toJSON = JSON.parse;
9701
9702function evalFunctionWithEval(func, emit) {
9703 return scopeEval(
9704 "return (" + func.replace(/;\s*$/, "") + ");",
9705 {
9706 emit: emit,
9707 sum: sum,
9708 log: log,
9709 isArray: isArray,
9710 toJSON: toJSON
9711 }
9712 );
9713}
9714
9715/*
9716 * Simple task queue to sequentialize actions. Assumes
9717 * callbacks will eventually fire (once).
9718 */
9719
9720
9721function TaskQueue$1() {
9722 this.promise = new Promise(function (fulfill) {fulfill(); });
9723}
9724TaskQueue$1.prototype.add = function (promiseFactory) {
9725 this.promise = this.promise["catch"](function () {
9726 // just recover
9727 }).then(function () {
9728 return promiseFactory();
9729 });
9730 return this.promise;
9731};
9732TaskQueue$1.prototype.finish = function () {
9733 return this.promise;
9734};
9735
9736function stringify(input) {
9737 if (!input) {
9738 return 'undefined'; // backwards compat for empty reduce
9739 }
9740 // for backwards compat with mapreduce, functions/strings are stringified
9741 // as-is. everything else is JSON-stringified.
9742 switch (typeof input) {
9743 case 'function':
9744 // e.g. a mapreduce map
9745 return input.toString();
9746 case 'string':
9747 // e.g. a mapreduce built-in _reduce function
9748 return input.toString();
9749 default:
9750 // e.g. a JSON object in the case of mango queries
9751 return JSON.stringify(input);
9752 }
9753}
9754
9755/* create a string signature for a view so we can cache it and uniq it */
9756function createViewSignature(mapFun, reduceFun) {
9757 // the "undefined" part is for backwards compatibility
9758 return stringify(mapFun) + stringify(reduceFun) + 'undefined';
9759}
9760
9761function createView(sourceDB, viewName, mapFun, reduceFun, temporary, localDocName) {
9762 var viewSignature = createViewSignature(mapFun, reduceFun);
9763
9764 var cachedViews;
9765 if (!temporary) {
9766 // cache this to ensure we don't try to update the same view twice
9767 cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {};
9768 if (cachedViews[viewSignature]) {
9769 return cachedViews[viewSignature];
9770 }
9771 }
9772
9773 var promiseForView = sourceDB.info().then(function (info) {
9774
9775 var depDbName = info.db_name + '-mrview-' +
9776 (temporary ? 'temp' : stringMd5(viewSignature));
9777
9778 // save the view name in the source db so it can be cleaned up if necessary
9779 // (e.g. when the _design doc is deleted, remove all associated view data)
9780 function diffFunction(doc) {
9781 doc.views = doc.views || {};
9782 var fullViewName = viewName;
9783 if (fullViewName.indexOf('/') === -1) {
9784 fullViewName = viewName + '/' + viewName;
9785 }
9786 var depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {};
9787 /* istanbul ignore if */
9788 if (depDbs[depDbName]) {
9789 return; // no update necessary
9790 }
9791 depDbs[depDbName] = true;
9792 return doc;
9793 }
9794 return upsert(sourceDB, '_local/' + localDocName, diffFunction).then(function () {
9795 return sourceDB.registerDependentDatabase(depDbName).then(function (res) {
9796 var db = res.db;
9797 db.auto_compaction = true;
9798 var view = {
9799 name: depDbName,
9800 db: db,
9801 sourceDB: sourceDB,
9802 adapter: sourceDB.adapter,
9803 mapFun: mapFun,
9804 reduceFun: reduceFun
9805 };
9806 return view.db.get('_local/lastSeq')["catch"](function (err) {
9807 /* istanbul ignore if */
9808 if (err.status !== 404) {
9809 throw err;
9810 }
9811 }).then(function (lastSeqDoc) {
9812 view.seq = lastSeqDoc ? lastSeqDoc.seq : 0;
9813 if (cachedViews) {
9814 view.db.once('destroyed', function () {
9815 delete cachedViews[viewSignature];
9816 });
9817 }
9818 return view;
9819 });
9820 });
9821 });
9822 });
9823
9824 if (cachedViews) {
9825 cachedViews[viewSignature] = promiseForView;
9826 }
9827 return promiseForView;
9828}
9829
9830var persistentQueues = {};
9831var tempViewQueue = new TaskQueue$1();
9832var CHANGES_BATCH_SIZE$1 = 50;
9833
9834function parseViewName(name) {
9835 // can be either 'ddocname/viewname' or just 'viewname'
9836 // (where the ddoc name is the same)
9837 return name.indexOf('/') === -1 ? [name, name] : name.split('/');
9838}
9839
9840function isGenOne(changes) {
9841 // only return true if the current change is 1-
9842 // and there are no other leafs
9843 return changes.length === 1 && /^1-/.test(changes[0].rev);
9844}
9845
9846function emitError(db, e) {
9847 try {
9848 db.emit('error', e);
9849 } catch (err) {
9850 guardedConsole('error',
9851 'The user\'s map/reduce function threw an uncaught error.\n' +
9852 'You can debug this error by doing:\n' +
9853 'myDatabase.on(\'error\', function (err) { debugger; });\n' +
9854 'Please double-check your map/reduce function.');
9855 guardedConsole('error', e);
9856 }
9857}
9858
9859/**
9860 * Returns an "abstract" mapreduce object of the form:
9861 *
9862 * {
9863 * query: queryFun,
9864 * viewCleanup: viewCleanupFun
9865 * }
9866 *
9867 * Arguments are:
9868 *
9869 * localDoc: string
9870 * This is for the local doc that gets saved in order to track the
9871 * "dependent" DBs and clean them up for viewCleanup. It should be
9872 * unique, so that indexer plugins don't collide with each other.
9873 * mapper: function (mapFunDef, emit)
9874 * Returns a map function based on the mapFunDef, which in the case of
9875 * normal map/reduce is just the de-stringified function, but may be
9876 * something else, such as an object in the case of pouchdb-find.
9877 * reducer: function (reduceFunDef)
9878 * Ditto, but for reducing. Modules don't have to support reducing
9879 * (e.g. pouchdb-find).
9880 * ddocValidator: function (ddoc, viewName)
9881 * Throws an error if the ddoc or viewName is not valid.
9882 * This could be a way to communicate to the user that the configuration for the
9883 * indexer is invalid.
9884 */
9885function createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator) {
9886
9887 function tryMap(db, fun, doc) {
9888 // emit an event if there was an error thrown by a map function.
9889 // putting try/catches in a single function also avoids deoptimizations.
9890 try {
9891 fun(doc);
9892 } catch (e) {
9893 emitError(db, e);
9894 }
9895 }
9896
9897 function tryReduce(db, fun, keys, values, rereduce) {
9898 // same as above, but returning the result or an error. there are two separate
9899 // functions to avoid extra memory allocations since the tryCode() case is used
9900 // for custom map functions (common) vs this function, which is only used for
9901 // custom reduce functions (rare)
9902 try {
9903 return {output : fun(keys, values, rereduce)};
9904 } catch (e) {
9905 emitError(db, e);
9906 return {error: e};
9907 }
9908 }
9909
9910 function sortByKeyThenValue(x, y) {
9911 var keyCompare = collate(x.key, y.key);
9912 return keyCompare !== 0 ? keyCompare : collate(x.value, y.value);
9913 }
9914
9915 function sliceResults(results, limit, skip) {
9916 skip = skip || 0;
9917 if (typeof limit === 'number') {
9918 return results.slice(skip, limit + skip);
9919 } else if (skip > 0) {
9920 return results.slice(skip);
9921 }
9922 return results;
9923 }
9924
9925 function rowToDocId(row) {
9926 var val = row.value;
9927 // Users can explicitly specify a joined doc _id, or it
9928 // defaults to the doc _id that emitted the key/value.
9929 var docId = (val && typeof val === 'object' && val._id) || row.id;
9930 return docId;
9931 }
9932
9933 function readAttachmentsAsBlobOrBuffer(res) {
9934 res.rows.forEach(function (row) {
9935 var atts = row.doc && row.doc._attachments;
9936 if (!atts) {
9937 return;
9938 }
9939 Object.keys(atts).forEach(function (filename) {
9940 var att = atts[filename];
9941 atts[filename].data = b64ToBluffer(att.data, att.content_type);
9942 });
9943 });
9944 }
9945
9946 function postprocessAttachments(opts) {
9947 return function (res) {
9948 if (opts.include_docs && opts.attachments && opts.binary) {
9949 readAttachmentsAsBlobOrBuffer(res);
9950 }
9951 return res;
9952 };
9953 }
9954
9955 function addHttpParam(paramName, opts, params, asJson) {
9956 // add an http param from opts to params, optionally json-encoded
9957 var val = opts[paramName];
9958 if (typeof val !== 'undefined') {
9959 if (asJson) {
9960 val = encodeURIComponent(JSON.stringify(val));
9961 }
9962 params.push(paramName + '=' + val);
9963 }
9964 }
9965
9966 function coerceInteger(integerCandidate) {
9967 if (typeof integerCandidate !== 'undefined') {
9968 var asNumber = Number(integerCandidate);
9969 // prevents e.g. '1foo' or '1.1' being coerced to 1
9970 if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) {
9971 return asNumber;
9972 } else {
9973 return integerCandidate;
9974 }
9975 }
9976 }
9977
9978 function coerceOptions(opts) {
9979 opts.group_level = coerceInteger(opts.group_level);
9980 opts.limit = coerceInteger(opts.limit);
9981 opts.skip = coerceInteger(opts.skip);
9982 return opts;
9983 }
9984
9985 function checkPositiveInteger(number) {
9986 if (number) {
9987 if (typeof number !== 'number') {
9988 return new QueryParseError('Invalid value for integer: "' +
9989 number + '"');
9990 }
9991 if (number < 0) {
9992 return new QueryParseError('Invalid value for positive integer: ' +
9993 '"' + number + '"');
9994 }
9995 }
9996 }
9997
9998 function checkQueryParseError(options, fun) {
9999 var startkeyName = options.descending ? 'endkey' : 'startkey';
10000 var endkeyName = options.descending ? 'startkey' : 'endkey';
10001
10002 if (typeof options[startkeyName] !== 'undefined' &&
10003 typeof options[endkeyName] !== 'undefined' &&
10004 collate(options[startkeyName], options[endkeyName]) > 0) {
10005 throw new QueryParseError('No rows can match your key range, ' +
10006 'reverse your start_key and end_key or set {descending : true}');
10007 } else if (fun.reduce && options.reduce !== false) {
10008 if (options.include_docs) {
10009 throw new QueryParseError('{include_docs:true} is invalid for reduce');
10010 } else if (options.keys && options.keys.length > 1 &&
10011 !options.group && !options.group_level) {
10012 throw new QueryParseError('Multi-key fetches for reduce views must use ' +
10013 '{group: true}');
10014 }
10015 }
10016 ['group_level', 'limit', 'skip'].forEach(function (optionName) {
10017 var error = checkPositiveInteger(options[optionName]);
10018 if (error) {
10019 throw error;
10020 }
10021 });
10022 }
10023
10024 function httpQuery(db, fun, opts) {
10025 // List of parameters to add to the PUT request
10026 var params = [];
10027 var body;
10028 var method = 'GET';
10029 var ok, status;
10030
10031 // If opts.reduce exists and is defined, then add it to the list
10032 // of parameters.
10033 // If reduce=false then the results are that of only the map function
10034 // not the final result of map and reduce.
10035 addHttpParam('reduce', opts, params);
10036 addHttpParam('include_docs', opts, params);
10037 addHttpParam('attachments', opts, params);
10038 addHttpParam('limit', opts, params);
10039 addHttpParam('descending', opts, params);
10040 addHttpParam('group', opts, params);
10041 addHttpParam('group_level', opts, params);
10042 addHttpParam('skip', opts, params);
10043 addHttpParam('stale', opts, params);
10044 addHttpParam('conflicts', opts, params);
10045 addHttpParam('startkey', opts, params, true);
10046 addHttpParam('start_key', opts, params, true);
10047 addHttpParam('endkey', opts, params, true);
10048 addHttpParam('end_key', opts, params, true);
10049 addHttpParam('inclusive_end', opts, params);
10050 addHttpParam('key', opts, params, true);
10051 addHttpParam('update_seq', opts, params);
10052
10053 // Format the list of parameters into a valid URI query string
10054 params = params.join('&');
10055 params = params === '' ? '' : '?' + params;
10056
10057 // If keys are supplied, issue a POST to circumvent GET query string limits
10058 // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
10059 if (typeof opts.keys !== 'undefined') {
10060 var MAX_URL_LENGTH = 2000;
10061 // according to http://stackoverflow.com/a/417184/680742,
10062 // the de facto URL length limit is 2000 characters
10063
10064 var keysAsString =
10065 'keys=' + encodeURIComponent(JSON.stringify(opts.keys));
10066 if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) {
10067 // If the keys are short enough, do a GET. we do this to work around
10068 // Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239)
10069 params += (params[0] === '?' ? '&' : '?') + keysAsString;
10070 } else {
10071 method = 'POST';
10072 if (typeof fun === 'string') {
10073 body = {keys: opts.keys};
10074 } else { // fun is {map : mapfun}, so append to this
10075 fun.keys = opts.keys;
10076 }
10077 }
10078 }
10079
10080 // We are referencing a query defined in the design doc
10081 if (typeof fun === 'string') {
10082 var parts = parseViewName(fun);
10083 return db.fetch('_design/' + parts[0] + '/_view/' + parts[1] + params, {
10084 headers: new h({'Content-Type': 'application/json'}),
10085 method: method,
10086 body: JSON.stringify(body)
10087 }).then(function (response) {
10088 ok = response.ok;
10089 status = response.status;
10090 return response.json();
10091 }).then(function (result) {
10092 if (!ok) {
10093 result.status = status;
10094 throw generateErrorFromResponse(result);
10095 }
10096 // fail the entire request if the result contains an error
10097 result.rows.forEach(function (row) {
10098 /* istanbul ignore if */
10099 if (row.value && row.value.error && row.value.error === "builtin_reduce_error") {
10100 throw new Error(row.reason);
10101 }
10102 });
10103 return result;
10104 }).then(postprocessAttachments(opts));
10105 }
10106
10107 // We are using a temporary view, terrible for performance, good for testing
10108 body = body || {};
10109 Object.keys(fun).forEach(function (key) {
10110 if (Array.isArray(fun[key])) {
10111 body[key] = fun[key];
10112 } else {
10113 body[key] = fun[key].toString();
10114 }
10115 });
10116
10117 return db.fetch('_temp_view' + params, {
10118 headers: new h({'Content-Type': 'application/json'}),
10119 method: 'POST',
10120 body: JSON.stringify(body)
10121 }).then(function (response) {
10122 ok = response.ok;
10123 status = response.status;
10124 return response.json();
10125 }).then(function (result) {
10126 if (!ok) {
10127 result.status = status;
10128 throw generateErrorFromResponse(result);
10129 }
10130 return result;
10131 }).then(postprocessAttachments(opts));
10132 }
10133
10134 // custom adapters can define their own api._query
10135 // and override the default behavior
10136 /* istanbul ignore next */
10137 function customQuery(db, fun, opts) {
10138 return new Promise(function (resolve, reject) {
10139 db._query(fun, opts, function (err, res) {
10140 if (err) {
10141 return reject(err);
10142 }
10143 resolve(res);
10144 });
10145 });
10146 }
10147
10148 // custom adapters can define their own api._viewCleanup
10149 // and override the default behavior
10150 /* istanbul ignore next */
10151 function customViewCleanup(db) {
10152 return new Promise(function (resolve, reject) {
10153 db._viewCleanup(function (err, res) {
10154 if (err) {
10155 return reject(err);
10156 }
10157 resolve(res);
10158 });
10159 });
10160 }
10161
10162 function defaultsTo(value) {
10163 return function (reason) {
10164 /* istanbul ignore else */
10165 if (reason.status === 404) {
10166 return value;
10167 } else {
10168 throw reason;
10169 }
10170 };
10171 }
10172
10173 // returns a promise for a list of docs to update, based on the input docId.
10174 // the order doesn't matter, because post-3.2.0, bulkDocs
10175 // is an atomic operation in all three adapters.
10176 function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
10177 var metaDocId = '_local/doc_' + docId;
10178 var defaultMetaDoc = {_id: metaDocId, keys: []};
10179 var docData = docIdsToChangesAndEmits.get(docId);
10180 var indexableKeysToKeyValues = docData[0];
10181 var changes = docData[1];
10182
10183 function getMetaDoc() {
10184 if (isGenOne(changes)) {
10185 // generation 1, so we can safely assume initial state
10186 // for performance reasons (avoids unnecessary GETs)
10187 return Promise.resolve(defaultMetaDoc);
10188 }
10189 return view.db.get(metaDocId)["catch"](defaultsTo(defaultMetaDoc));
10190 }
10191
10192 function getKeyValueDocs(metaDoc) {
10193 if (!metaDoc.keys.length) {
10194 // no keys, no need for a lookup
10195 return Promise.resolve({rows: []});
10196 }
10197 return view.db.allDocs({
10198 keys: metaDoc.keys,
10199 include_docs: true
10200 });
10201 }
10202
10203 function processKeyValueDocs(metaDoc, kvDocsRes) {
10204 var kvDocs = [];
10205 var oldKeys = new ExportedSet();
10206
10207 for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {
10208 var row = kvDocsRes.rows[i];
10209 var doc = row.doc;
10210 if (!doc) { // deleted
10211 continue;
10212 }
10213 kvDocs.push(doc);
10214 oldKeys.add(doc._id);
10215 doc._deleted = !indexableKeysToKeyValues.has(doc._id);
10216 if (!doc._deleted) {
10217 var keyValue = indexableKeysToKeyValues.get(doc._id);
10218 if ('value' in keyValue) {
10219 doc.value = keyValue.value;
10220 }
10221 }
10222 }
10223 var newKeys = mapToKeysArray(indexableKeysToKeyValues);
10224 newKeys.forEach(function (key) {
10225 if (!oldKeys.has(key)) {
10226 // new doc
10227 var kvDoc = {
10228 _id: key
10229 };
10230 var keyValue = indexableKeysToKeyValues.get(key);
10231 if ('value' in keyValue) {
10232 kvDoc.value = keyValue.value;
10233 }
10234 kvDocs.push(kvDoc);
10235 }
10236 });
10237 metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));
10238 kvDocs.push(metaDoc);
10239
10240 return kvDocs;
10241 }
10242
10243 return getMetaDoc().then(function (metaDoc) {
10244 return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {
10245 return processKeyValueDocs(metaDoc, kvDocsRes);
10246 });
10247 });
10248 }
10249
10250 // updates all emitted key/value docs and metaDocs in the mrview database
10251 // for the given batch of documents from the source database
10252 function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
10253 var seqDocId = '_local/lastSeq';
10254 return view.db.get(seqDocId)[
10255 "catch"](defaultsTo({_id: seqDocId, seq: 0}))
10256 .then(function (lastSeqDoc) {
10257 var docIds = mapToKeysArray(docIdsToChangesAndEmits);
10258 return Promise.all(docIds.map(function (docId) {
10259 return getDocsToPersist(docId, view, docIdsToChangesAndEmits);
10260 })).then(function (listOfDocsToPersist) {
10261 var docsToPersist = flatten(listOfDocsToPersist);
10262 lastSeqDoc.seq = seq;
10263 docsToPersist.push(lastSeqDoc);
10264 // write all docs in a single operation, update the seq once
10265 return view.db.bulkDocs({docs : docsToPersist});
10266 });
10267 });
10268 }
10269
10270 function getQueue(view) {
10271 var viewName = typeof view === 'string' ? view : view.name;
10272 var queue = persistentQueues[viewName];
10273 if (!queue) {
10274 queue = persistentQueues[viewName] = new TaskQueue$1();
10275 }
10276 return queue;
10277 }
10278
10279 function updateView(view) {
10280 return sequentialize(getQueue(view), function () {
10281 return updateViewInQueue(view);
10282 })();
10283 }
10284
10285 function updateViewInQueue(view) {
10286 // bind the emit function once
10287 var mapResults;
10288 var doc;
10289
10290 function emit(key, value) {
10291 var output = {id: doc._id, key: normalizeKey(key)};
10292 // Don't explicitly store the value unless it's defined and non-null.
10293 // This saves on storage space, because often people don't use it.
10294 if (typeof value !== 'undefined' && value !== null) {
10295 output.value = normalizeKey(value);
10296 }
10297 mapResults.push(output);
10298 }
10299
10300 var mapFun = mapper(view.mapFun, emit);
10301
10302 var currentSeq = view.seq || 0;
10303
10304 function processChange(docIdsToChangesAndEmits, seq) {
10305 return function () {
10306 return saveKeyValues(view, docIdsToChangesAndEmits, seq);
10307 };
10308 }
10309
10310 var queue = new TaskQueue$1();
10311
10312 function processNextBatch() {
10313 return view.sourceDB.changes({
10314 return_docs: true,
10315 conflicts: true,
10316 include_docs: true,
10317 style: 'all_docs',
10318 since: currentSeq,
10319 limit: CHANGES_BATCH_SIZE$1
10320 }).then(processBatch);
10321 }
10322
10323 function processBatch(response) {
10324 var results = response.results;
10325 if (!results.length) {
10326 return;
10327 }
10328 var docIdsToChangesAndEmits = createDocIdsToChangesAndEmits(results);
10329 queue.add(processChange(docIdsToChangesAndEmits, currentSeq));
10330 if (results.length < CHANGES_BATCH_SIZE$1) {
10331 return;
10332 }
10333 return processNextBatch();
10334 }
10335
10336 function createDocIdsToChangesAndEmits(results) {
10337 var docIdsToChangesAndEmits = new ExportedMap();
10338 for (var i = 0, len = results.length; i < len; i++) {
10339 var change = results[i];
10340 if (change.doc._id[0] !== '_') {
10341 mapResults = [];
10342 doc = change.doc;
10343
10344 if (!doc._deleted) {
10345 tryMap(view.sourceDB, mapFun, doc);
10346 }
10347 mapResults.sort(sortByKeyThenValue);
10348
10349 var indexableKeysToKeyValues = createIndexableKeysToKeyValues(mapResults);
10350 docIdsToChangesAndEmits.set(change.doc._id, [
10351 indexableKeysToKeyValues,
10352 change.changes
10353 ]);
10354 }
10355 currentSeq = change.seq;
10356 }
10357 return docIdsToChangesAndEmits;
10358 }
10359
10360 function createIndexableKeysToKeyValues(mapResults) {
10361 var indexableKeysToKeyValues = new ExportedMap();
10362 var lastKey;
10363 for (var i = 0, len = mapResults.length; i < len; i++) {
10364 var emittedKeyValue = mapResults[i];
10365 var complexKey = [emittedKeyValue.key, emittedKeyValue.id];
10366 if (i > 0 && collate(emittedKeyValue.key, lastKey) === 0) {
10367 complexKey.push(i); // dup key+id, so make it unique
10368 }
10369 indexableKeysToKeyValues.set(toIndexableString(complexKey), emittedKeyValue);
10370 lastKey = emittedKeyValue.key;
10371 }
10372 return indexableKeysToKeyValues;
10373 }
10374
10375 return processNextBatch().then(function () {
10376 return queue.finish();
10377 }).then(function () {
10378 view.seq = currentSeq;
10379 });
10380 }
10381
10382 function reduceView(view, results, options) {
10383 if (options.group_level === 0) {
10384 delete options.group_level;
10385 }
10386
10387 var shouldGroup = options.group || options.group_level;
10388
10389 var reduceFun = reducer(view.reduceFun);
10390
10391 var groups = [];
10392 var lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY :
10393 options.group_level;
10394 results.forEach(function (e) {
10395 var last = groups[groups.length - 1];
10396 var groupKey = shouldGroup ? e.key : null;
10397
10398 // only set group_level for array keys
10399 if (shouldGroup && Array.isArray(groupKey)) {
10400 groupKey = groupKey.slice(0, lvl);
10401 }
10402
10403 if (last && collate(last.groupKey, groupKey) === 0) {
10404 last.keys.push([e.key, e.id]);
10405 last.values.push(e.value);
10406 return;
10407 }
10408 groups.push({
10409 keys: [[e.key, e.id]],
10410 values: [e.value],
10411 groupKey: groupKey
10412 });
10413 });
10414 results = [];
10415 for (var i = 0, len = groups.length; i < len; i++) {
10416 var e = groups[i];
10417 var reduceTry = tryReduce(view.sourceDB, reduceFun, e.keys, e.values, false);
10418 if (reduceTry.error && reduceTry.error instanceof BuiltInError) {
10419 // CouchDB returns an error if a built-in errors out
10420 throw reduceTry.error;
10421 }
10422 results.push({
10423 // CouchDB just sets the value to null if a non-built-in errors out
10424 value: reduceTry.error ? null : reduceTry.output,
10425 key: e.groupKey
10426 });
10427 }
10428 // no total_rows/offset when reducing
10429 return {rows: sliceResults(results, options.limit, options.skip)};
10430 }
10431
10432 function queryView(view, opts) {
10433 return sequentialize(getQueue(view), function () {
10434 return queryViewInQueue(view, opts);
10435 })();
10436 }
10437
10438 function queryViewInQueue(view, opts) {
10439 var totalRows;
10440 var shouldReduce = view.reduceFun && opts.reduce !== false;
10441 var skip = opts.skip || 0;
10442 if (typeof opts.keys !== 'undefined' && !opts.keys.length) {
10443 // equivalent query
10444 opts.limit = 0;
10445 delete opts.keys;
10446 }
10447
10448 function fetchFromView(viewOpts) {
10449 viewOpts.include_docs = true;
10450 return view.db.allDocs(viewOpts).then(function (res) {
10451 totalRows = res.total_rows;
10452 return res.rows.map(function (result) {
10453
10454 // implicit migration - in older versions of PouchDB,
10455 // we explicitly stored the doc as {id: ..., key: ..., value: ...}
10456 // this is tested in a migration test
10457 /* istanbul ignore next */
10458 if ('value' in result.doc && typeof result.doc.value === 'object' &&
10459 result.doc.value !== null) {
10460 var keys = Object.keys(result.doc.value).sort();
10461 // this detection method is not perfect, but it's unlikely the user
10462 // emitted a value which was an object with these 3 exact keys
10463 var expectedKeys = ['id', 'key', 'value'];
10464 if (!(keys < expectedKeys || keys > expectedKeys)) {
10465 return result.doc.value;
10466 }
10467 }
10468
10469 var parsedKeyAndDocId = parseIndexableString(result.doc._id);
10470 return {
10471 key: parsedKeyAndDocId[0],
10472 id: parsedKeyAndDocId[1],
10473 value: ('value' in result.doc ? result.doc.value : null)
10474 };
10475 });
10476 });
10477 }
10478
10479 function onMapResultsReady(rows) {
10480 var finalResults;
10481 if (shouldReduce) {
10482 finalResults = reduceView(view, rows, opts);
10483 } else {
10484 finalResults = {
10485 total_rows: totalRows,
10486 offset: skip,
10487 rows: rows
10488 };
10489 }
10490 /* istanbul ignore if */
10491 if (opts.update_seq) {
10492 finalResults.update_seq = view.seq;
10493 }
10494 if (opts.include_docs) {
10495 var docIds = uniq(rows.map(rowToDocId));
10496
10497 return view.sourceDB.allDocs({
10498 keys: docIds,
10499 include_docs: true,
10500 conflicts: opts.conflicts,
10501 attachments: opts.attachments,
10502 binary: opts.binary
10503 }).then(function (allDocsRes) {
10504 var docIdsToDocs = new ExportedMap();
10505 allDocsRes.rows.forEach(function (row) {
10506 docIdsToDocs.set(row.id, row.doc);
10507 });
10508 rows.forEach(function (row) {
10509 var docId = rowToDocId(row);
10510 var doc = docIdsToDocs.get(docId);
10511 if (doc) {
10512 row.doc = doc;
10513 }
10514 });
10515 return finalResults;
10516 });
10517 } else {
10518 return finalResults;
10519 }
10520 }
10521
10522 if (typeof opts.keys !== 'undefined') {
10523 var keys = opts.keys;
10524 var fetchPromises = keys.map(function (key) {
10525 var viewOpts = {
10526 startkey : toIndexableString([key]),
10527 endkey : toIndexableString([key, {}])
10528 };
10529 /* istanbul ignore if */
10530 if (opts.update_seq) {
10531 viewOpts.update_seq = true;
10532 }
10533 return fetchFromView(viewOpts);
10534 });
10535 return Promise.all(fetchPromises).then(flatten).then(onMapResultsReady);
10536 } else { // normal query, no 'keys'
10537 var viewOpts = {
10538 descending : opts.descending
10539 };
10540 /* istanbul ignore if */
10541 if (opts.update_seq) {
10542 viewOpts.update_seq = true;
10543 }
10544 var startkey;
10545 var endkey;
10546 if ('start_key' in opts) {
10547 startkey = opts.start_key;
10548 }
10549 if ('startkey' in opts) {
10550 startkey = opts.startkey;
10551 }
10552 if ('end_key' in opts) {
10553 endkey = opts.end_key;
10554 }
10555 if ('endkey' in opts) {
10556 endkey = opts.endkey;
10557 }
10558 if (typeof startkey !== 'undefined') {
10559 viewOpts.startkey = opts.descending ?
10560 toIndexableString([startkey, {}]) :
10561 toIndexableString([startkey]);
10562 }
10563 if (typeof endkey !== 'undefined') {
10564 var inclusiveEnd = opts.inclusive_end !== false;
10565 if (opts.descending) {
10566 inclusiveEnd = !inclusiveEnd;
10567 }
10568
10569 viewOpts.endkey = toIndexableString(
10570 inclusiveEnd ? [endkey, {}] : [endkey]);
10571 }
10572 if (typeof opts.key !== 'undefined') {
10573 var keyStart = toIndexableString([opts.key]);
10574 var keyEnd = toIndexableString([opts.key, {}]);
10575 if (viewOpts.descending) {
10576 viewOpts.endkey = keyStart;
10577 viewOpts.startkey = keyEnd;
10578 } else {
10579 viewOpts.startkey = keyStart;
10580 viewOpts.endkey = keyEnd;
10581 }
10582 }
10583 if (!shouldReduce) {
10584 if (typeof opts.limit === 'number') {
10585 viewOpts.limit = opts.limit;
10586 }
10587 viewOpts.skip = skip;
10588 }
10589 return fetchFromView(viewOpts).then(onMapResultsReady);
10590 }
10591 }
10592
10593 function httpViewCleanup(db) {
10594 return db.fetch('_view_cleanup', {
10595 headers: new h({'Content-Type': 'application/json'}),
10596 method: 'POST'
10597 }).then(function (response) {
10598 return response.json();
10599 });
10600 }
10601
10602 function localViewCleanup(db) {
10603 return db.get('_local/' + localDocName).then(function (metaDoc) {
10604 var docsToViews = new ExportedMap();
10605 Object.keys(metaDoc.views).forEach(function (fullViewName) {
10606 var parts = parseViewName(fullViewName);
10607 var designDocName = '_design/' + parts[0];
10608 var viewName = parts[1];
10609 var views = docsToViews.get(designDocName);
10610 if (!views) {
10611 views = new ExportedSet();
10612 docsToViews.set(designDocName, views);
10613 }
10614 views.add(viewName);
10615 });
10616 var opts = {
10617 keys : mapToKeysArray(docsToViews),
10618 include_docs : true
10619 };
10620 return db.allDocs(opts).then(function (res) {
10621 var viewsToStatus = {};
10622 res.rows.forEach(function (row) {
10623 var ddocName = row.key.substring(8); // cuts off '_design/'
10624 docsToViews.get(row.key).forEach(function (viewName) {
10625 var fullViewName = ddocName + '/' + viewName;
10626 /* istanbul ignore if */
10627 if (!metaDoc.views[fullViewName]) {
10628 // new format, without slashes, to support PouchDB 2.2.0
10629 // migration test in pouchdb's browser.migration.js verifies this
10630 fullViewName = viewName;
10631 }
10632 var viewDBNames = Object.keys(metaDoc.views[fullViewName]);
10633 // design doc deleted, or view function nonexistent
10634 var statusIsGood = row.doc && row.doc.views &&
10635 row.doc.views[viewName];
10636 viewDBNames.forEach(function (viewDBName) {
10637 viewsToStatus[viewDBName] =
10638 viewsToStatus[viewDBName] || statusIsGood;
10639 });
10640 });
10641 });
10642 var dbsToDelete = Object.keys(viewsToStatus).filter(
10643 function (viewDBName) { return !viewsToStatus[viewDBName]; });
10644 var destroyPromises = dbsToDelete.map(function (viewDBName) {
10645 return sequentialize(getQueue(viewDBName), function () {
10646 return new db.constructor(viewDBName, db.__opts).destroy();
10647 })();
10648 });
10649 return Promise.all(destroyPromises).then(function () {
10650 return {ok: true};
10651 });
10652 });
10653 }, defaultsTo({ok: true}));
10654 }
10655
10656 function queryPromised(db, fun, opts) {
10657 /* istanbul ignore next */
10658 if (typeof db._query === 'function') {
10659 return customQuery(db, fun, opts);
10660 }
10661 if (isRemote(db)) {
10662 return httpQuery(db, fun, opts);
10663 }
10664
10665 if (typeof fun !== 'string') {
10666 // temp_view
10667 checkQueryParseError(opts, fun);
10668
10669 tempViewQueue.add(function () {
10670 var createViewPromise = createView(
10671 /* sourceDB */ db,
10672 /* viewName */ 'temp_view/temp_view',
10673 /* mapFun */ fun.map,
10674 /* reduceFun */ fun.reduce,
10675 /* temporary */ true,
10676 /* localDocName */ localDocName);
10677 return createViewPromise.then(function (view) {
10678 return fin(updateView(view).then(function () {
10679 return queryView(view, opts);
10680 }), function () {
10681 return view.db.destroy();
10682 });
10683 });
10684 });
10685 return tempViewQueue.finish();
10686 } else {
10687 // persistent view
10688 var fullViewName = fun;
10689 var parts = parseViewName(fullViewName);
10690 var designDocName = parts[0];
10691 var viewName = parts[1];
10692 return db.get('_design/' + designDocName).then(function (doc) {
10693 var fun = doc.views && doc.views[viewName];
10694
10695 if (!fun) {
10696 // basic validator; it's assumed that every subclass would want this
10697 throw new NotFoundError('ddoc ' + doc._id + ' has no view named ' +
10698 viewName);
10699 }
10700
10701 ddocValidator(doc, viewName);
10702 checkQueryParseError(opts, fun);
10703
10704 var createViewPromise = createView(
10705 /* sourceDB */ db,
10706 /* viewName */ fullViewName,
10707 /* mapFun */ fun.map,
10708 /* reduceFun */ fun.reduce,
10709 /* temporary */ false,
10710 /* localDocName */ localDocName);
10711 return createViewPromise.then(function (view) {
10712 if (opts.stale === 'ok' || opts.stale === 'update_after') {
10713 if (opts.stale === 'update_after') {
10714 nextTick(function () {
10715 updateView(view);
10716 });
10717 }
10718 return queryView(view, opts);
10719 } else { // stale not ok
10720 return updateView(view).then(function () {
10721 return queryView(view, opts);
10722 });
10723 }
10724 });
10725 });
10726 }
10727 }
10728
10729 function abstractQuery(fun, opts, callback) {
10730 var db = this;
10731 if (typeof opts === 'function') {
10732 callback = opts;
10733 opts = {};
10734 }
10735 opts = opts ? coerceOptions(opts) : {};
10736
10737 if (typeof fun === 'function') {
10738 fun = {map : fun};
10739 }
10740
10741 var promise = Promise.resolve().then(function () {
10742 return queryPromised(db, fun, opts);
10743 });
10744 promisedCallback(promise, callback);
10745 return promise;
10746 }
10747
10748 var abstractViewCleanup = callbackify(function () {
10749 var db = this;
10750 /* istanbul ignore next */
10751 if (typeof db._viewCleanup === 'function') {
10752 return customViewCleanup(db);
10753 }
10754 if (isRemote(db)) {
10755 return httpViewCleanup(db);
10756 }
10757 return localViewCleanup(db);
10758 });
10759
10760 return {
10761 query: abstractQuery,
10762 viewCleanup: abstractViewCleanup
10763 };
10764}
10765
10766var builtInReduce = {
10767 _sum: function (keys, values) {
10768 return sum(values);
10769 },
10770
10771 _count: function (keys, values) {
10772 return values.length;
10773 },
10774
10775 _stats: function (keys, values) {
10776 // no need to implement rereduce=true, because Pouch
10777 // will never call it
10778 function sumsqr(values) {
10779 var _sumsqr = 0;
10780 for (var i = 0, len = values.length; i < len; i++) {
10781 var num = values[i];
10782 _sumsqr += (num * num);
10783 }
10784 return _sumsqr;
10785 }
10786 return {
10787 sum : sum(values),
10788 min : Math.min.apply(null, values),
10789 max : Math.max.apply(null, values),
10790 count : values.length,
10791 sumsqr : sumsqr(values)
10792 };
10793 }
10794};
10795
10796function getBuiltIn(reduceFunString) {
10797 if (/^_sum/.test(reduceFunString)) {
10798 return builtInReduce._sum;
10799 } else if (/^_count/.test(reduceFunString)) {
10800 return builtInReduce._count;
10801 } else if (/^_stats/.test(reduceFunString)) {
10802 return builtInReduce._stats;
10803 } else if (/^_/.test(reduceFunString)) {
10804 throw new Error(reduceFunString + ' is not a supported reduce function.');
10805 }
10806}
10807
10808function mapper(mapFun, emit) {
10809 // for temp_views one can use emit(doc, emit), see #38
10810 if (typeof mapFun === "function" && mapFun.length === 2) {
10811 var origMap = mapFun;
10812 return function (doc) {
10813 return origMap(doc, emit);
10814 };
10815 } else {
10816 return evalFunctionWithEval(mapFun.toString(), emit);
10817 }
10818}
10819
10820function reducer(reduceFun) {
10821 var reduceFunString = reduceFun.toString();
10822 var builtIn = getBuiltIn(reduceFunString);
10823 if (builtIn) {
10824 return builtIn;
10825 } else {
10826 return evalFunctionWithEval(reduceFunString);
10827 }
10828}
10829
10830function ddocValidator(ddoc, viewName) {
10831 var fun = ddoc.views && ddoc.views[viewName];
10832 if (typeof fun.map !== 'string') {
10833 throw new NotFoundError('ddoc ' + ddoc._id + ' has no string view named ' +
10834 viewName + ', instead found object of type: ' + typeof fun.map);
10835 }
10836}
10837
10838var localDocName = 'mrviews';
10839var abstract = createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator);
10840
10841function query(fun, opts, callback) {
10842 return abstract.query.call(this, fun, opts, callback);
10843}
10844
10845function viewCleanup(callback) {
10846 return abstract.viewCleanup.call(this, callback);
10847}
10848
10849var mapreduce = {
10850 query: query,
10851 viewCleanup: viewCleanup
10852};
10853
10854function isGenOne$1(rev) {
10855 return /^1-/.test(rev);
10856}
10857
10858function fileHasChanged(localDoc, remoteDoc, filename) {
10859 return !localDoc._attachments ||
10860 !localDoc._attachments[filename] ||
10861 localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest;
10862}
10863
10864function getDocAttachments(db, doc) {
10865 var filenames = Object.keys(doc._attachments);
10866 return Promise.all(filenames.map(function (filename) {
10867 return db.getAttachment(doc._id, filename, {rev: doc._rev});
10868 }));
10869}
10870
10871function getDocAttachmentsFromTargetOrSource(target, src, doc) {
10872 var doCheckForLocalAttachments = isRemote(src) && !isRemote(target);
10873 var filenames = Object.keys(doc._attachments);
10874
10875 if (!doCheckForLocalAttachments) {
10876 return getDocAttachments(src, doc);
10877 }
10878
10879 return target.get(doc._id).then(function (localDoc) {
10880 return Promise.all(filenames.map(function (filename) {
10881 if (fileHasChanged(localDoc, doc, filename)) {
10882 return src.getAttachment(doc._id, filename);
10883 }
10884
10885 return target.getAttachment(localDoc._id, filename);
10886 }));
10887 })["catch"](function (error) {
10888 /* istanbul ignore if */
10889 if (error.status !== 404) {
10890 throw error;
10891 }
10892
10893 return getDocAttachments(src, doc);
10894 });
10895}
10896
10897function createBulkGetOpts(diffs) {
10898 var requests = [];
10899 Object.keys(diffs).forEach(function (id) {
10900 var missingRevs = diffs[id].missing;
10901 missingRevs.forEach(function (missingRev) {
10902 requests.push({
10903 id: id,
10904 rev: missingRev
10905 });
10906 });
10907 });
10908
10909 return {
10910 docs: requests,
10911 revs: true,
10912 latest: true
10913 };
10914}
10915
10916//
10917// Fetch all the documents from the src as described in the "diffs",
10918// which is a mapping of docs IDs to revisions. If the state ever
10919// changes to "cancelled", then the returned promise will be rejected.
10920// Else it will be resolved with a list of fetched documents.
10921//
10922function getDocs(src, target, diffs, state) {
10923 diffs = clone(diffs); // we do not need to modify this
10924
10925 var resultDocs = [],
10926 ok = true;
10927
10928 function getAllDocs() {
10929
10930 var bulkGetOpts = createBulkGetOpts(diffs);
10931
10932 if (!bulkGetOpts.docs.length) { // optimization: skip empty requests
10933 return;
10934 }
10935
10936 return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) {
10937 /* istanbul ignore if */
10938 if (state.cancelled) {
10939 throw new Error('cancelled');
10940 }
10941 return Promise.all(bulkGetResponse.results.map(function (bulkGetInfo) {
10942 return Promise.all(bulkGetInfo.docs.map(function (doc) {
10943 var remoteDoc = doc.ok;
10944
10945 if (doc.error) {
10946 // when AUTO_COMPACTION is set, docs can be returned which look
10947 // like this: {"missing":"1-7c3ac256b693c462af8442f992b83696"}
10948 ok = false;
10949 }
10950
10951 if (!remoteDoc || !remoteDoc._attachments) {
10952 return remoteDoc;
10953 }
10954
10955 return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc)
10956 .then(function (attachments) {
10957 var filenames = Object.keys(remoteDoc._attachments);
10958 attachments
10959 .forEach(function (attachment, i) {
10960 var att = remoteDoc._attachments[filenames[i]];
10961 delete att.stub;
10962 delete att.length;
10963 att.data = attachment;
10964 });
10965
10966 return remoteDoc;
10967 });
10968 }));
10969 }))
10970
10971 .then(function (results) {
10972 resultDocs = resultDocs.concat(flatten(results).filter(Boolean));
10973 });
10974 });
10975 }
10976
10977 function hasAttachments(doc) {
10978 return doc._attachments && Object.keys(doc._attachments).length > 0;
10979 }
10980
10981 function hasConflicts(doc) {
10982 return doc._conflicts && doc._conflicts.length > 0;
10983 }
10984
10985 function fetchRevisionOneDocs(ids) {
10986 // Optimization: fetch gen-1 docs and attachments in
10987 // a single request using _all_docs
10988 return src.allDocs({
10989 keys: ids,
10990 include_docs: true,
10991 conflicts: true
10992 }).then(function (res) {
10993 if (state.cancelled) {
10994 throw new Error('cancelled');
10995 }
10996 res.rows.forEach(function (row) {
10997 if (row.deleted || !row.doc || !isGenOne$1(row.value.rev) ||
10998 hasAttachments(row.doc) || hasConflicts(row.doc)) {
10999 // if any of these conditions apply, we need to fetch using get()
11000 return;
11001 }
11002
11003 // strip _conflicts array to appease CSG (#5793)
11004 /* istanbul ignore if */
11005 if (row.doc._conflicts) {
11006 delete row.doc._conflicts;
11007 }
11008
11009 // the doc we got back from allDocs() is sufficient
11010 resultDocs.push(row.doc);
11011 delete diffs[row.id];
11012 });
11013 });
11014 }
11015
11016 function getRevisionOneDocs() {
11017 // filter out the generation 1 docs and get them
11018 // leaving the non-generation one docs to be got otherwise
11019 var ids = Object.keys(diffs).filter(function (id) {
11020 var missing = diffs[id].missing;
11021 return missing.length === 1 && isGenOne$1(missing[0]);
11022 });
11023 if (ids.length > 0) {
11024 return fetchRevisionOneDocs(ids);
11025 }
11026 }
11027
11028 function returnResult() {
11029 return { ok:ok, docs:resultDocs };
11030 }
11031
11032 return Promise.resolve()
11033 .then(getRevisionOneDocs)
11034 .then(getAllDocs)
11035 .then(returnResult);
11036}
11037
11038var CHECKPOINT_VERSION = 1;
11039var REPLICATOR = "pouchdb";
11040// This is an arbitrary number to limit the
11041// amount of replication history we save in the checkpoint.
11042// If we save too much, the checkpoing docs will become very big,
11043// if we save fewer, we'll run a greater risk of having to
11044// read all the changes from 0 when checkpoint PUTs fail
11045// CouchDB 2.0 has a more involved history pruning,
11046// but let's go for the simple version for now.
11047var CHECKPOINT_HISTORY_SIZE = 5;
11048var LOWEST_SEQ = 0;
11049
11050function updateCheckpoint(db, id, checkpoint, session, returnValue) {
11051 return db.get(id)["catch"](function (err) {
11052 if (err.status === 404) {
11053 if (db.adapter === 'http' || db.adapter === 'https') {
11054 explainError(
11055 404, 'PouchDB is just checking if a remote checkpoint exists.'
11056 );
11057 }
11058 return {
11059 session_id: session,
11060 _id: id,
11061 history: [],
11062 replicator: REPLICATOR,
11063 version: CHECKPOINT_VERSION
11064 };
11065 }
11066 throw err;
11067 }).then(function (doc) {
11068 if (returnValue.cancelled) {
11069 return;
11070 }
11071
11072 // if the checkpoint has not changed, do not update
11073 if (doc.last_seq === checkpoint) {
11074 return;
11075 }
11076
11077 // Filter out current entry for this replication
11078 doc.history = (doc.history || []).filter(function (item) {
11079 return item.session_id !== session;
11080 });
11081
11082 // Add the latest checkpoint to history
11083 doc.history.unshift({
11084 last_seq: checkpoint,
11085 session_id: session
11086 });
11087
11088 // Just take the last pieces in history, to
11089 // avoid really big checkpoint docs.
11090 // see comment on history size above
11091 doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE);
11092
11093 doc.version = CHECKPOINT_VERSION;
11094 doc.replicator = REPLICATOR;
11095
11096 doc.session_id = session;
11097 doc.last_seq = checkpoint;
11098
11099 return db.put(doc)["catch"](function (err) {
11100 if (err.status === 409) {
11101 // retry; someone is trying to write a checkpoint simultaneously
11102 return updateCheckpoint(db, id, checkpoint, session, returnValue);
11103 }
11104 throw err;
11105 });
11106 });
11107}
11108
11109function Checkpointer(src, target, id, returnValue, opts) {
11110 this.src = src;
11111 this.target = target;
11112 this.id = id;
11113 this.returnValue = returnValue;
11114 this.opts = opts || {};
11115}
11116
11117Checkpointer.prototype.writeCheckpoint = function (checkpoint, session) {
11118 var self = this;
11119 return this.updateTarget(checkpoint, session).then(function () {
11120 return self.updateSource(checkpoint, session);
11121 });
11122};
11123
11124Checkpointer.prototype.updateTarget = function (checkpoint, session) {
11125 if (this.opts.writeTargetCheckpoint) {
11126 return updateCheckpoint(this.target, this.id, checkpoint,
11127 session, this.returnValue);
11128 } else {
11129 return Promise.resolve(true);
11130 }
11131};
11132
11133Checkpointer.prototype.updateSource = function (checkpoint, session) {
11134 if (this.opts.writeSourceCheckpoint) {
11135 var self = this;
11136 return updateCheckpoint(this.src, this.id, checkpoint,
11137 session, this.returnValue)[
11138 "catch"](function (err) {
11139 if (isForbiddenError(err)) {
11140 self.opts.writeSourceCheckpoint = false;
11141 return true;
11142 }
11143 throw err;
11144 });
11145 } else {
11146 return Promise.resolve(true);
11147 }
11148};
11149
11150var comparisons = {
11151 "undefined": function (targetDoc, sourceDoc) {
11152 // This is the previous comparison function
11153 if (collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) {
11154 return sourceDoc.last_seq;
11155 }
11156 /* istanbul ignore next */
11157 return 0;
11158 },
11159 "1": function (targetDoc, sourceDoc) {
11160 // This is the comparison function ported from CouchDB
11161 return compareReplicationLogs(sourceDoc, targetDoc).last_seq;
11162 }
11163};
11164
11165Checkpointer.prototype.getCheckpoint = function () {
11166 var self = this;
11167
11168 if (self.opts && self.opts.writeSourceCheckpoint && !self.opts.writeTargetCheckpoint) {
11169 return self.src.get(self.id).then(function (sourceDoc) {
11170 return sourceDoc.last_seq || LOWEST_SEQ;
11171 })["catch"](function (err) {
11172 /* istanbul ignore if */
11173 if (err.status !== 404) {
11174 throw err;
11175 }
11176 return LOWEST_SEQ;
11177 });
11178 }
11179
11180 return self.target.get(self.id).then(function (targetDoc) {
11181 if (self.opts && self.opts.writeTargetCheckpoint && !self.opts.writeSourceCheckpoint) {
11182 return targetDoc.last_seq || LOWEST_SEQ;
11183 }
11184
11185 return self.src.get(self.id).then(function (sourceDoc) {
11186 // Since we can't migrate an old version doc to a new one
11187 // (no session id), we just go with the lowest seq in this case
11188 /* istanbul ignore if */
11189 if (targetDoc.version !== sourceDoc.version) {
11190 return LOWEST_SEQ;
11191 }
11192
11193 var version;
11194 if (targetDoc.version) {
11195 version = targetDoc.version.toString();
11196 } else {
11197 version = "undefined";
11198 }
11199
11200 if (version in comparisons) {
11201 return comparisons[version](targetDoc, sourceDoc);
11202 }
11203 /* istanbul ignore next */
11204 return LOWEST_SEQ;
11205 }, function (err) {
11206 if (err.status === 404 && targetDoc.last_seq) {
11207 return self.src.put({
11208 _id: self.id,
11209 last_seq: LOWEST_SEQ
11210 }).then(function () {
11211 return LOWEST_SEQ;
11212 }, function (err) {
11213 if (isForbiddenError(err)) {
11214 self.opts.writeSourceCheckpoint = false;
11215 return targetDoc.last_seq;
11216 }
11217 /* istanbul ignore next */
11218 return LOWEST_SEQ;
11219 });
11220 }
11221 throw err;
11222 });
11223 })["catch"](function (err) {
11224 if (err.status !== 404) {
11225 throw err;
11226 }
11227 return LOWEST_SEQ;
11228 });
11229};
11230// This checkpoint comparison is ported from CouchDBs source
11231// they come from here:
11232// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906
11233
11234function compareReplicationLogs(srcDoc, tgtDoc) {
11235 if (srcDoc.session_id === tgtDoc.session_id) {
11236 return {
11237 last_seq: srcDoc.last_seq,
11238 history: srcDoc.history
11239 };
11240 }
11241
11242 return compareReplicationHistory(srcDoc.history, tgtDoc.history);
11243}
11244
11245function compareReplicationHistory(sourceHistory, targetHistory) {
11246 // the erlang loop via function arguments is not so easy to repeat in JS
11247 // therefore, doing this as recursion
11248 var S = sourceHistory[0];
11249 var sourceRest = sourceHistory.slice(1);
11250 var T = targetHistory[0];
11251 var targetRest = targetHistory.slice(1);
11252
11253 if (!S || targetHistory.length === 0) {
11254 return {
11255 last_seq: LOWEST_SEQ,
11256 history: []
11257 };
11258 }
11259
11260 var sourceId = S.session_id;
11261 /* istanbul ignore if */
11262 if (hasSessionId(sourceId, targetHistory)) {
11263 return {
11264 last_seq: S.last_seq,
11265 history: sourceHistory
11266 };
11267 }
11268
11269 var targetId = T.session_id;
11270 if (hasSessionId(targetId, sourceRest)) {
11271 return {
11272 last_seq: T.last_seq,
11273 history: targetRest
11274 };
11275 }
11276
11277 return compareReplicationHistory(sourceRest, targetRest);
11278}
11279
11280function hasSessionId(sessionId, history) {
11281 var props = history[0];
11282 var rest = history.slice(1);
11283
11284 if (!sessionId || history.length === 0) {
11285 return false;
11286 }
11287
11288 if (sessionId === props.session_id) {
11289 return true;
11290 }
11291
11292 return hasSessionId(sessionId, rest);
11293}
11294
11295function isForbiddenError(err) {
11296 return typeof err.status === 'number' && Math.floor(err.status / 100) === 4;
11297}
11298
11299var STARTING_BACK_OFF = 0;
11300
11301function backOff(opts, returnValue, error, callback) {
11302 if (opts.retry === false) {
11303 returnValue.emit('error', error);
11304 returnValue.removeAllListeners();
11305 return;
11306 }
11307 /* istanbul ignore if */
11308 if (typeof opts.back_off_function !== 'function') {
11309 opts.back_off_function = defaultBackOff;
11310 }
11311 returnValue.emit('requestError', error);
11312 if (returnValue.state === 'active' || returnValue.state === 'pending') {
11313 returnValue.emit('paused', error);
11314 returnValue.state = 'stopped';
11315 var backOffSet = function backoffTimeSet() {
11316 opts.current_back_off = STARTING_BACK_OFF;
11317 };
11318 var removeBackOffSetter = function removeBackOffTimeSet() {
11319 returnValue.removeListener('active', backOffSet);
11320 };
11321 returnValue.once('paused', removeBackOffSetter);
11322 returnValue.once('active', backOffSet);
11323 }
11324
11325 opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF;
11326 opts.current_back_off = opts.back_off_function(opts.current_back_off);
11327 setTimeout(callback, opts.current_back_off);
11328}
11329
11330function sortObjectPropertiesByKey(queryParams) {
11331 return Object.keys(queryParams).sort(collate).reduce(function (result, key) {
11332 result[key] = queryParams[key];
11333 return result;
11334 }, {});
11335}
11336
11337// Generate a unique id particular to this replication.
11338// Not guaranteed to align perfectly with CouchDB's rep ids.
11339function generateReplicationId(src, target, opts) {
11340 var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : '';
11341 var filterFun = opts.filter ? opts.filter.toString() : '';
11342 var queryParams = '';
11343 var filterViewName = '';
11344 var selector = '';
11345
11346 // possibility for checkpoints to be lost here as behaviour of
11347 // JSON.stringify is not stable (see #6226)
11348 /* istanbul ignore if */
11349 if (opts.selector) {
11350 selector = JSON.stringify(opts.selector);
11351 }
11352
11353 if (opts.filter && opts.query_params) {
11354 queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
11355 }
11356
11357 if (opts.filter && opts.filter === '_view') {
11358 filterViewName = opts.view.toString();
11359 }
11360
11361 return Promise.all([src.id(), target.id()]).then(function (res) {
11362 var queryData = res[0] + res[1] + filterFun + filterViewName +
11363 queryParams + docIds + selector;
11364 return new Promise(function (resolve) {
11365 binaryMd5(queryData, resolve);
11366 });
11367 }).then(function (md5sum) {
11368 // can't use straight-up md5 alphabet, because
11369 // the char '/' is interpreted as being for attachments,
11370 // and + is also not url-safe
11371 md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
11372 return '_local/' + md5sum;
11373 });
11374}
11375
11376function replicate(src, target, opts, returnValue, result) {
11377 var batches = []; // list of batches to be processed
11378 var currentBatch; // the batch currently being processed
11379 var pendingBatch = {
11380 seq: 0,
11381 changes: [],
11382 docs: []
11383 }; // next batch, not yet ready to be processed
11384 var writingCheckpoint = false; // true while checkpoint is being written
11385 var changesCompleted = false; // true when all changes received
11386 var replicationCompleted = false; // true when replication has completed
11387 var last_seq = 0;
11388 var continuous = opts.continuous || opts.live || false;
11389 var batch_size = opts.batch_size || 100;
11390 var batches_limit = opts.batches_limit || 10;
11391 var changesPending = false; // true while src.changes is running
11392 var doc_ids = opts.doc_ids;
11393 var selector = opts.selector;
11394 var repId;
11395 var checkpointer;
11396 var changedDocs = [];
11397 // Like couchdb, every replication gets a unique session id
11398 var session = uuid();
11399
11400 result = result || {
11401 ok: true,
11402 start_time: new Date().toISOString(),
11403 docs_read: 0,
11404 docs_written: 0,
11405 doc_write_failures: 0,
11406 errors: []
11407 };
11408
11409 var changesOpts = {};
11410 returnValue.ready(src, target);
11411
11412 function initCheckpointer() {
11413 if (checkpointer) {
11414 return Promise.resolve();
11415 }
11416 return generateReplicationId(src, target, opts).then(function (res) {
11417 repId = res;
11418
11419 var checkpointOpts = {};
11420 if (opts.checkpoint === false) {
11421 checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: false };
11422 } else if (opts.checkpoint === 'source') {
11423 checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: false };
11424 } else if (opts.checkpoint === 'target') {
11425 checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: true };
11426 } else {
11427 checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: true };
11428 }
11429
11430 checkpointer = new Checkpointer(src, target, repId, returnValue, checkpointOpts);
11431 });
11432 }
11433
11434 function writeDocs() {
11435 changedDocs = [];
11436
11437 if (currentBatch.docs.length === 0) {
11438 return;
11439 }
11440 var docs = currentBatch.docs;
11441 var bulkOpts = {timeout: opts.timeout};
11442 return target.bulkDocs({docs: docs, new_edits: false}, bulkOpts).then(function (res) {
11443 /* istanbul ignore if */
11444 if (returnValue.cancelled) {
11445 completeReplication();
11446 throw new Error('cancelled');
11447 }
11448
11449 // `res` doesn't include full documents (which live in `docs`), so we create a map of
11450 // (id -> error), and check for errors while iterating over `docs`
11451 var errorsById = Object.create(null);
11452 res.forEach(function (res) {
11453 if (res.error) {
11454 errorsById[res.id] = res;
11455 }
11456 });
11457
11458 var errorsNo = Object.keys(errorsById).length;
11459 result.doc_write_failures += errorsNo;
11460 result.docs_written += docs.length - errorsNo;
11461
11462 docs.forEach(function (doc) {
11463 var error = errorsById[doc._id];
11464 if (error) {
11465 result.errors.push(error);
11466 // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
11467 var errorName = (error.name || '').toLowerCase();
11468 if (errorName === 'unauthorized' || errorName === 'forbidden') {
11469 returnValue.emit('denied', clone(error));
11470 } else {
11471 throw error;
11472 }
11473 } else {
11474 changedDocs.push(doc);
11475 }
11476 });
11477
11478 }, function (err) {
11479 result.doc_write_failures += docs.length;
11480 throw err;
11481 });
11482 }
11483
11484 function finishBatch() {
11485 if (currentBatch.error) {
11486 throw new Error('There was a problem getting docs.');
11487 }
11488 result.last_seq = last_seq = currentBatch.seq;
11489 var outResult = clone(result);
11490 if (changedDocs.length) {
11491 outResult.docs = changedDocs;
11492 // Attach 'pending' property if server supports it (CouchDB 2.0+)
11493 /* istanbul ignore if */
11494 if (typeof currentBatch.pending === 'number') {
11495 outResult.pending = currentBatch.pending;
11496 delete currentBatch.pending;
11497 }
11498 returnValue.emit('change', outResult);
11499 }
11500 writingCheckpoint = true;
11501 return checkpointer.writeCheckpoint(currentBatch.seq,
11502 session).then(function () {
11503 writingCheckpoint = false;
11504 /* istanbul ignore if */
11505 if (returnValue.cancelled) {
11506 completeReplication();
11507 throw new Error('cancelled');
11508 }
11509 currentBatch = undefined;
11510 getChanges();
11511 })["catch"](function (err) {
11512 onCheckpointError(err);
11513 throw err;
11514 });
11515 }
11516
11517 function getDiffs() {
11518 var diff = {};
11519 currentBatch.changes.forEach(function (change) {
11520 // Couchbase Sync Gateway emits these, but we can ignore them
11521 /* istanbul ignore if */
11522 if (change.id === "_user/") {
11523 return;
11524 }
11525 diff[change.id] = change.changes.map(function (x) {
11526 return x.rev;
11527 });
11528 });
11529 return target.revsDiff(diff).then(function (diffs) {
11530 /* istanbul ignore if */
11531 if (returnValue.cancelled) {
11532 completeReplication();
11533 throw new Error('cancelled');
11534 }
11535 // currentBatch.diffs elements are deleted as the documents are written
11536 currentBatch.diffs = diffs;
11537 });
11538 }
11539
11540 function getBatchDocs() {
11541 return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) {
11542 currentBatch.error = !got.ok;
11543 got.docs.forEach(function (doc) {
11544 delete currentBatch.diffs[doc._id];
11545 result.docs_read++;
11546 currentBatch.docs.push(doc);
11547 });
11548 });
11549 }
11550
11551 function startNextBatch() {
11552 if (returnValue.cancelled || currentBatch) {
11553 return;
11554 }
11555 if (batches.length === 0) {
11556 processPendingBatch(true);
11557 return;
11558 }
11559 currentBatch = batches.shift();
11560 getDiffs()
11561 .then(getBatchDocs)
11562 .then(writeDocs)
11563 .then(finishBatch)
11564 .then(startNextBatch)[
11565 "catch"](function (err) {
11566 abortReplication('batch processing terminated with error', err);
11567 });
11568 }
11569
11570
11571 function processPendingBatch(immediate) {
11572 if (pendingBatch.changes.length === 0) {
11573 if (batches.length === 0 && !currentBatch) {
11574 if ((continuous && changesOpts.live) || changesCompleted) {
11575 returnValue.state = 'pending';
11576 returnValue.emit('paused');
11577 }
11578 if (changesCompleted) {
11579 completeReplication();
11580 }
11581 }
11582 return;
11583 }
11584 if (
11585 immediate ||
11586 changesCompleted ||
11587 pendingBatch.changes.length >= batch_size
11588 ) {
11589 batches.push(pendingBatch);
11590 pendingBatch = {
11591 seq: 0,
11592 changes: [],
11593 docs: []
11594 };
11595 if (returnValue.state === 'pending' || returnValue.state === 'stopped') {
11596 returnValue.state = 'active';
11597 returnValue.emit('active');
11598 }
11599 startNextBatch();
11600 }
11601 }
11602
11603
11604 function abortReplication(reason, err) {
11605 if (replicationCompleted) {
11606 return;
11607 }
11608 if (!err.message) {
11609 err.message = reason;
11610 }
11611 result.ok = false;
11612 result.status = 'aborting';
11613 batches = [];
11614 pendingBatch = {
11615 seq: 0,
11616 changes: [],
11617 docs: []
11618 };
11619 completeReplication(err);
11620 }
11621
11622
11623 function completeReplication(fatalError) {
11624 if (replicationCompleted) {
11625 return;
11626 }
11627 /* istanbul ignore if */
11628 if (returnValue.cancelled) {
11629 result.status = 'cancelled';
11630 if (writingCheckpoint) {
11631 return;
11632 }
11633 }
11634 result.status = result.status || 'complete';
11635 result.end_time = new Date().toISOString();
11636 result.last_seq = last_seq;
11637 replicationCompleted = true;
11638
11639 if (fatalError) {
11640 // need to extend the error because Firefox considers ".result" read-only
11641 fatalError = createError(fatalError);
11642 fatalError.result = result;
11643
11644 // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
11645 var errorName = (fatalError.name || '').toLowerCase();
11646 if (errorName === 'unauthorized' || errorName === 'forbidden') {
11647 returnValue.emit('error', fatalError);
11648 returnValue.removeAllListeners();
11649 } else {
11650 backOff(opts, returnValue, fatalError, function () {
11651 replicate(src, target, opts, returnValue);
11652 });
11653 }
11654 } else {
11655 returnValue.emit('complete', result);
11656 returnValue.removeAllListeners();
11657 }
11658 }
11659
11660
11661 function onChange(change, pending, lastSeq) {
11662 /* istanbul ignore if */
11663 if (returnValue.cancelled) {
11664 return completeReplication();
11665 }
11666 // Attach 'pending' property if server supports it (CouchDB 2.0+)
11667 /* istanbul ignore if */
11668 if (typeof pending === 'number') {
11669 pendingBatch.pending = pending;
11670 }
11671
11672 var filter = filterChange(opts)(change);
11673 if (!filter) {
11674 return;
11675 }
11676 pendingBatch.seq = change.seq || lastSeq;
11677 pendingBatch.changes.push(change);
11678 nextTick(function () {
11679 processPendingBatch(batches.length === 0 && changesOpts.live);
11680 });
11681 }
11682
11683
11684 function onChangesComplete(changes) {
11685 changesPending = false;
11686 /* istanbul ignore if */
11687 if (returnValue.cancelled) {
11688 return completeReplication();
11689 }
11690
11691 // if no results were returned then we're done,
11692 // else fetch more
11693 if (changes.results.length > 0) {
11694 changesOpts.since = changes.results[changes.results.length - 1].seq;
11695 getChanges();
11696 processPendingBatch(true);
11697 } else {
11698
11699 var complete = function () {
11700 if (continuous) {
11701 changesOpts.live = true;
11702 getChanges();
11703 } else {
11704 changesCompleted = true;
11705 }
11706 processPendingBatch(true);
11707 };
11708
11709 // update the checkpoint so we start from the right seq next time
11710 if (!currentBatch && changes.results.length === 0) {
11711 writingCheckpoint = true;
11712 checkpointer.writeCheckpoint(changes.last_seq,
11713 session).then(function () {
11714 writingCheckpoint = false;
11715 result.last_seq = last_seq = changes.last_seq;
11716 complete();
11717 })[
11718 "catch"](onCheckpointError);
11719 } else {
11720 complete();
11721 }
11722 }
11723 }
11724
11725
11726 function onChangesError(err) {
11727 changesPending = false;
11728 /* istanbul ignore if */
11729 if (returnValue.cancelled) {
11730 return completeReplication();
11731 }
11732 abortReplication('changes rejected', err);
11733 }
11734
11735
11736 function getChanges() {
11737 if (!(
11738 !changesPending &&
11739 !changesCompleted &&
11740 batches.length < batches_limit
11741 )) {
11742 return;
11743 }
11744 changesPending = true;
11745 function abortChanges() {
11746 changes.cancel();
11747 }
11748 function removeListener() {
11749 returnValue.removeListener('cancel', abortChanges);
11750 }
11751
11752 if (returnValue._changes) { // remove old changes() and listeners
11753 returnValue.removeListener('cancel', returnValue._abortChanges);
11754 returnValue._changes.cancel();
11755 }
11756 returnValue.once('cancel', abortChanges);
11757
11758 var changes = src.changes(changesOpts)
11759 .on('change', onChange);
11760 changes.then(removeListener, removeListener);
11761 changes.then(onChangesComplete)[
11762 "catch"](onChangesError);
11763
11764 if (opts.retry) {
11765 // save for later so we can cancel if necessary
11766 returnValue._changes = changes;
11767 returnValue._abortChanges = abortChanges;
11768 }
11769 }
11770
11771
11772 function startChanges() {
11773 initCheckpointer().then(function () {
11774 /* istanbul ignore if */
11775 if (returnValue.cancelled) {
11776 completeReplication();
11777 return;
11778 }
11779 return checkpointer.getCheckpoint().then(function (checkpoint) {
11780 last_seq = checkpoint;
11781 changesOpts = {
11782 since: last_seq,
11783 limit: batch_size,
11784 batch_size: batch_size,
11785 style: 'all_docs',
11786 doc_ids: doc_ids,
11787 selector: selector,
11788 return_docs: true // required so we know when we're done
11789 };
11790 if (opts.filter) {
11791 if (typeof opts.filter !== 'string') {
11792 // required for the client-side filter in onChange
11793 changesOpts.include_docs = true;
11794 } else { // ddoc filter
11795 changesOpts.filter = opts.filter;
11796 }
11797 }
11798 if ('heartbeat' in opts) {
11799 changesOpts.heartbeat = opts.heartbeat;
11800 }
11801 if ('timeout' in opts) {
11802 changesOpts.timeout = opts.timeout;
11803 }
11804 if (opts.query_params) {
11805 changesOpts.query_params = opts.query_params;
11806 }
11807 if (opts.view) {
11808 changesOpts.view = opts.view;
11809 }
11810 getChanges();
11811 });
11812 })["catch"](function (err) {
11813 abortReplication('getCheckpoint rejected with ', err);
11814 });
11815 }
11816
11817 /* istanbul ignore next */
11818 function onCheckpointError(err) {
11819 writingCheckpoint = false;
11820 abortReplication('writeCheckpoint completed with error', err);
11821 }
11822
11823 /* istanbul ignore if */
11824 if (returnValue.cancelled) { // cancelled immediately
11825 completeReplication();
11826 return;
11827 }
11828
11829 if (!returnValue._addedListeners) {
11830 returnValue.once('cancel', completeReplication);
11831
11832 if (typeof opts.complete === 'function') {
11833 returnValue.once('error', opts.complete);
11834 returnValue.once('complete', function (result) {
11835 opts.complete(null, result);
11836 });
11837 }
11838 returnValue._addedListeners = true;
11839 }
11840
11841 if (typeof opts.since === 'undefined') {
11842 startChanges();
11843 } else {
11844 initCheckpointer().then(function () {
11845 writingCheckpoint = true;
11846 return checkpointer.writeCheckpoint(opts.since, session);
11847 }).then(function () {
11848 writingCheckpoint = false;
11849 /* istanbul ignore if */
11850 if (returnValue.cancelled) {
11851 completeReplication();
11852 return;
11853 }
11854 last_seq = opts.since;
11855 startChanges();
11856 })["catch"](onCheckpointError);
11857 }
11858}
11859
11860// We create a basic promise so the caller can cancel the replication possibly
11861// before we have actually started listening to changes etc
11862inherits(Replication, events.EventEmitter);
11863function Replication() {
11864 events.EventEmitter.call(this);
11865 this.cancelled = false;
11866 this.state = 'pending';
11867 var self = this;
11868 var promise = new Promise(function (fulfill, reject) {
11869 self.once('complete', fulfill);
11870 self.once('error', reject);
11871 });
11872 self.then = function (resolve, reject) {
11873 return promise.then(resolve, reject);
11874 };
11875 self["catch"] = function (reject) {
11876 return promise["catch"](reject);
11877 };
11878 // As we allow error handling via "error" event as well,
11879 // put a stub in here so that rejecting never throws UnhandledError.
11880 self["catch"](function () {});
11881}
11882
11883Replication.prototype.cancel = function () {
11884 this.cancelled = true;
11885 this.state = 'cancelled';
11886 this.emit('cancel');
11887};
11888
11889Replication.prototype.ready = function (src, target) {
11890 var self = this;
11891 if (self._readyCalled) {
11892 return;
11893 }
11894 self._readyCalled = true;
11895
11896 function onDestroy() {
11897 self.cancel();
11898 }
11899 src.once('destroyed', onDestroy);
11900 target.once('destroyed', onDestroy);
11901 function cleanup() {
11902 src.removeListener('destroyed', onDestroy);
11903 target.removeListener('destroyed', onDestroy);
11904 }
11905 self.once('complete', cleanup);
11906};
11907
11908function toPouch(db, opts) {
11909 var PouchConstructor = opts.PouchConstructor;
11910 if (typeof db === 'string') {
11911 return new PouchConstructor(db, opts);
11912 } else {
11913 return db;
11914 }
11915}
11916
11917function replicateWrapper(src, target, opts, callback) {
11918
11919 if (typeof opts === 'function') {
11920 callback = opts;
11921 opts = {};
11922 }
11923 if (typeof opts === 'undefined') {
11924 opts = {};
11925 }
11926
11927 if (opts.doc_ids && !Array.isArray(opts.doc_ids)) {
11928 throw createError(BAD_REQUEST,
11929 "`doc_ids` filter parameter is not a list.");
11930 }
11931
11932 opts.complete = callback;
11933 opts = clone(opts);
11934 opts.continuous = opts.continuous || opts.live;
11935 opts.retry = ('retry' in opts) ? opts.retry : false;
11936 /*jshint validthis:true */
11937 opts.PouchConstructor = opts.PouchConstructor || this;
11938 var replicateRet = new Replication(opts);
11939 var srcPouch = toPouch(src, opts);
11940 var targetPouch = toPouch(target, opts);
11941 replicate(srcPouch, targetPouch, opts, replicateRet);
11942 return replicateRet;
11943}
11944
11945inherits(Sync, events.EventEmitter);
11946function sync(src, target, opts, callback) {
11947 if (typeof opts === 'function') {
11948 callback = opts;
11949 opts = {};
11950 }
11951 if (typeof opts === 'undefined') {
11952 opts = {};
11953 }
11954 opts = clone(opts);
11955 /*jshint validthis:true */
11956 opts.PouchConstructor = opts.PouchConstructor || this;
11957 src = toPouch(src, opts);
11958 target = toPouch(target, opts);
11959 return new Sync(src, target, opts, callback);
11960}
11961
11962function Sync(src, target, opts, callback) {
11963 var self = this;
11964 this.canceled = false;
11965
11966 var optsPush = opts.push ? $inject_Object_assign({}, opts, opts.push) : opts;
11967 var optsPull = opts.pull ? $inject_Object_assign({}, opts, opts.pull) : opts;
11968
11969 this.push = replicateWrapper(src, target, optsPush);
11970 this.pull = replicateWrapper(target, src, optsPull);
11971
11972 this.pushPaused = true;
11973 this.pullPaused = true;
11974
11975 function pullChange(change) {
11976 self.emit('change', {
11977 direction: 'pull',
11978 change: change
11979 });
11980 }
11981 function pushChange(change) {
11982 self.emit('change', {
11983 direction: 'push',
11984 change: change
11985 });
11986 }
11987 function pushDenied(doc) {
11988 self.emit('denied', {
11989 direction: 'push',
11990 doc: doc
11991 });
11992 }
11993 function pullDenied(doc) {
11994 self.emit('denied', {
11995 direction: 'pull',
11996 doc: doc
11997 });
11998 }
11999 function pushPaused() {
12000 self.pushPaused = true;
12001 /* istanbul ignore if */
12002 if (self.pullPaused) {
12003 self.emit('paused');
12004 }
12005 }
12006 function pullPaused() {
12007 self.pullPaused = true;
12008 /* istanbul ignore if */
12009 if (self.pushPaused) {
12010 self.emit('paused');
12011 }
12012 }
12013 function pushActive() {
12014 self.pushPaused = false;
12015 /* istanbul ignore if */
12016 if (self.pullPaused) {
12017 self.emit('active', {
12018 direction: 'push'
12019 });
12020 }
12021 }
12022 function pullActive() {
12023 self.pullPaused = false;
12024 /* istanbul ignore if */
12025 if (self.pushPaused) {
12026 self.emit('active', {
12027 direction: 'pull'
12028 });
12029 }
12030 }
12031
12032 var removed = {};
12033
12034 function removeAll(type) { // type is 'push' or 'pull'
12035 return function (event, func) {
12036 var isChange = event === 'change' &&
12037 (func === pullChange || func === pushChange);
12038 var isDenied = event === 'denied' &&
12039 (func === pullDenied || func === pushDenied);
12040 var isPaused = event === 'paused' &&
12041 (func === pullPaused || func === pushPaused);
12042 var isActive = event === 'active' &&
12043 (func === pullActive || func === pushActive);
12044
12045 if (isChange || isDenied || isPaused || isActive) {
12046 if (!(event in removed)) {
12047 removed[event] = {};
12048 }
12049 removed[event][type] = true;
12050 if (Object.keys(removed[event]).length === 2) {
12051 // both push and pull have asked to be removed
12052 self.removeAllListeners(event);
12053 }
12054 }
12055 };
12056 }
12057
12058 if (opts.live) {
12059 this.push.on('complete', self.pull.cancel.bind(self.pull));
12060 this.pull.on('complete', self.push.cancel.bind(self.push));
12061 }
12062
12063 function addOneListener(ee, event, listener) {
12064 if (ee.listeners(event).indexOf(listener) == -1) {
12065 ee.on(event, listener);
12066 }
12067 }
12068
12069 this.on('newListener', function (event) {
12070 if (event === 'change') {
12071 addOneListener(self.pull, 'change', pullChange);
12072 addOneListener(self.push, 'change', pushChange);
12073 } else if (event === 'denied') {
12074 addOneListener(self.pull, 'denied', pullDenied);
12075 addOneListener(self.push, 'denied', pushDenied);
12076 } else if (event === 'active') {
12077 addOneListener(self.pull, 'active', pullActive);
12078 addOneListener(self.push, 'active', pushActive);
12079 } else if (event === 'paused') {
12080 addOneListener(self.pull, 'paused', pullPaused);
12081 addOneListener(self.push, 'paused', pushPaused);
12082 }
12083 });
12084
12085 this.on('removeListener', function (event) {
12086 if (event === 'change') {
12087 self.pull.removeListener('change', pullChange);
12088 self.push.removeListener('change', pushChange);
12089 } else if (event === 'denied') {
12090 self.pull.removeListener('denied', pullDenied);
12091 self.push.removeListener('denied', pushDenied);
12092 } else if (event === 'active') {
12093 self.pull.removeListener('active', pullActive);
12094 self.push.removeListener('active', pushActive);
12095 } else if (event === 'paused') {
12096 self.pull.removeListener('paused', pullPaused);
12097 self.push.removeListener('paused', pushPaused);
12098 }
12099 });
12100
12101 this.pull.on('removeListener', removeAll('pull'));
12102 this.push.on('removeListener', removeAll('push'));
12103
12104 var promise = Promise.all([
12105 this.push,
12106 this.pull
12107 ]).then(function (resp) {
12108 var out = {
12109 push: resp[0],
12110 pull: resp[1]
12111 };
12112 self.emit('complete', out);
12113 if (callback) {
12114 callback(null, out);
12115 }
12116 self.removeAllListeners();
12117 return out;
12118 }, function (err) {
12119 self.cancel();
12120 if (callback) {
12121 // if there's a callback, then the callback can receive
12122 // the error event
12123 callback(err);
12124 } else {
12125 // if there's no callback, then we're safe to emit an error
12126 // event, which would otherwise throw an unhandled error
12127 // due to 'error' being a special event in EventEmitters
12128 self.emit('error', err);
12129 }
12130 self.removeAllListeners();
12131 if (callback) {
12132 // no sense throwing if we're already emitting an 'error' event
12133 throw err;
12134 }
12135 });
12136
12137 this.then = function (success, err) {
12138 return promise.then(success, err);
12139 };
12140
12141 this["catch"] = function (err) {
12142 return promise["catch"](err);
12143 };
12144}
12145
12146Sync.prototype.cancel = function () {
12147 if (!this.canceled) {
12148 this.canceled = true;
12149 this.push.cancel();
12150 this.pull.cancel();
12151 }
12152};
12153
12154function replication(PouchDB) {
12155 PouchDB.replicate = replicateWrapper;
12156 PouchDB.sync = sync;
12157
12158 Object.defineProperty(PouchDB.prototype, 'replicate', {
12159 get: function () {
12160 var self = this;
12161 if (typeof this.replicateMethods === 'undefined') {
12162 this.replicateMethods = {
12163 from: function (other, opts, callback) {
12164 return self.constructor.replicate(other, self, opts, callback);
12165 },
12166 to: function (other, opts, callback) {
12167 return self.constructor.replicate(self, other, opts, callback);
12168 }
12169 };
12170 }
12171 return this.replicateMethods;
12172 }
12173 });
12174
12175 PouchDB.prototype.sync = function (dbName, opts, callback) {
12176 return this.constructor.sync(this, dbName, opts, callback);
12177 };
12178}
12179
12180PouchDB.plugin(IDBPouch)
12181 .plugin(HttpPouch$1)
12182 .plugin(mapreduce)
12183 .plugin(replication);
12184
12185// Pull from src because pouchdb-node/pouchdb-browser themselves
12186
12187module.exports = PouchDB;
12188
12189}).call(this,_dereq_(5),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
12190},{"1":1,"12":12,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}]},{},[13])(13)
12191});