UNPKG

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