-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpouchdb.js
More file actions
5475 lines (4806 loc) · 152 KB
/
pouchdb.js
File metadata and controls
5475 lines (4806 loc) · 152 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// PouchDB.nightly - 2013-07-03T22:00:42
(function() {
// BEGIN Math.uuid.js
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable values for each character.
*
* EXAMPLES:
* // No arguments - returns RFC4122, version 4 ID
* >>> Math.uuid()
* "92329D39-6F5C-4520-ABFC-AAB64544E172"
*
* // One argument - returns ID of the specified length
* >>> Math.uuid(15) // 15 character ID (default base=62)
* "VcydxgltxrVZSTV"
*
* // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
* >>> Math.uuid(8, 2) // 8 character ID (base=2)
* "01001010"
* >>> Math.uuid(8, 10) // 8 character ID (base=10)
* "47473046"
* >>> Math.uuid(8, 16) // 8 character ID (base=16)
* "098F4D35"
*/
(function() {
// Private array of chars to use
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
Math.uuid = function (len, radix) {
var chars = CHARS, uuid = [];
radix = radix || chars.length;
if (len) {
// Compact form
for (var i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (var i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
})();
// END Math.uuid.js
/**
*
* MD5 (Message-Digest Algorithm)
*
* For original source see http://www.webtoolkit.info/
* Download: 15.02.2009 from http://www.webtoolkit.info/javascript-md5.html
*
* Licensed under CC-BY 2.0 License
* (http://creativecommons.org/licenses/by/2.0/uk/)
*
**/
var Crypto = {};
(function() {
Crypto.MD5 = function(string) {
function RotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function AddUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function F(x,y,z) { return (x & y) | ((~x) & z); }
function G(x,y,z) { return (x & z) | (y & (~z)); }
function H(x,y,z) { return (x ^ y ^ z); }
function I(x,y,z) { return (y ^ (x | (~z))); }
function FF(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function GG(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function HH(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function II(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function ConvertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray=Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
};
function WordToHex(lValue) {
var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
}
return WordToHexValue;
};
//** function Utf8Encode(string) removed. Aready defined in pidcrypt_utils.js
var x=Array();
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
// string = Utf8Encode(string); #function call removed
x = ConvertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=GG(d,a,b,c,x[k+10],S22,0x2441453);
c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=II(a,b,c,d,x[k+0], S41,0xF4292244);
d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=II(c,d,a,b,x[k+6], S43,0xA3014314);
b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
a=AddUnsigned(a,AA);
b=AddUnsigned(b,BB);
c=AddUnsigned(c,CC);
d=AddUnsigned(d,DD);
}
var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
return temp.toLowerCase();
}
})();
// END Crypto.md5.js
//----------------------------------------------------------------------
//
// ECMAScript 5 Polyfills
// from www.calocomrmen./polyfill/
//
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// ES5 15.2 Object Objects
//----------------------------------------------------------------------
// ES 15.2.3.6 Object.defineProperty ( O, P, Attributes )
// Partial support for most common case - getters, setters, and values
(function() {
if (!Object.defineProperty ||
!(function () { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { return false; } } ())) {
var orig = Object.defineProperty;
Object.defineProperty = function (o, prop, desc) {
"use strict";
// In IE8 try built-in implementation for defining properties on DOM prototypes.
if (orig) { try { return orig(o, prop, desc); } catch (e) {} }
if (o !== Object(o)) { throw new TypeError("Object.defineProperty called on non-object"); }
if (Object.prototype.__defineGetter__ && ('get' in desc)) {
Object.prototype.__defineGetter__.call(o, prop, desc.get);
}
if (Object.prototype.__defineSetter__ && ('set' in desc)) {
Object.prototype.__defineSetter__.call(o, prop, desc.set);
}
if ('value' in desc) {
o[prop] = desc.value;
}
return o;
};
}
}());
// ES5 15.2.3.14 Object.keys ( O )
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
Object.keys = function (o) {
if (o !== Object(o)) { throw new TypeError('Object.keys called on non-object'); }
var ret = [], p;
for (p in o) {
if (Object.prototype.hasOwnProperty.call(o, p)) {
ret.push(p);
}
}
return ret;
};
}
//----------------------------------------------------------------------
// ES5 15.4 Array Objects
//----------------------------------------------------------------------
// ES5 15.4.4.18 Array.prototype.forEach ( callbackfn [ , thisArg ] )
// From https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fun /*, thisp */) {
"use strict";
if (this === void 0 || this === null) { throw new TypeError(); }
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function") { throw new TypeError(); }
var thisp = arguments[1], i;
for (i = 0; i < len; i++) {
if (i in t) {
fun.call(thisp, t[i], i, t);
}
}
};
}
// ES5 15.4.4.19 Array.prototype.map ( callbackfn [ , thisArg ] )
// From https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Map
if (!Array.prototype.map) {
Array.prototype.map = function (fun /*, thisp */) {
"use strict";
if (this === void 0 || this === null) { throw new TypeError(); }
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function") { throw new TypeError(); }
var res = []; res.length = len;
var thisp = arguments[1], i;
for (i = 0; i < len; i++) {
if (i in t) {
res[i] = fun.call(thisp, t[i], i, t);
}
}
return res;
};
}
// Extends method
// (taken from http://code.jquery.com/jquery-1.9.0.js)
// Populate the class2type map
var class2type = {};
var types = ["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object", "Error"];
for (var i = 0; i < types.length; i++) {
var typename = types[i];
class2type[ "[object " + typename + "]" ] = typename.toLowerCase();
}
var core_toString = class2type.toString;
var core_hasOwn = class2type.hasOwnProperty;
var type = function(obj) {
if (obj === null) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[core_toString.call(obj)] || "object" :
typeof obj;
};
var isWindow = function(obj) {
return obj !== null && obj === obj.window;
};
var isPlainObject = function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || type(obj) !== "object" || obj.nodeType || isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
};
var isFunction = function(obj) {
return type(obj) === "function";
};
var isArray = Array.isArray || function(obj) {
return type(obj) === "array";
};
var extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ((options = arguments[ i ]) != null) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = extend;
}
var ajax = function ajax(options, callback) {
if (typeof options === "function") {
callback = options;
options = {};
}
var call = function(fun) {
var args = Array.prototype.slice.call(arguments, 1);
if (typeof fun === typeof Function) {
fun.apply(this, args);
}
};
var defaultOptions = {
method : "GET",
headers: {},
json: true,
processData: true,
timeout: 10000
};
options = extend(true, defaultOptions, options);
if (options.auth) {
var token = btoa(options.auth.username + ':' + options.auth.password);
options.headers.Authorization = 'Basic ' + token;
}
var onSuccess = function(obj, resp, cb){
if (!options.binary && !options.json && options.processData && typeof obj !== 'string') {
obj = JSON.stringify(obj);
} else if (!options.binary && options.json && typeof obj === 'string') {
try {
obj = JSON.parse(obj);
} catch (e) {
// Probably a malformed JSON from server
call(cb, e);
return;
}
}
call(cb, null, obj, resp);
};
var onError = function(err, cb){
var errParsed;
var errObj = {status: err.status};
try{
errParsed = JSON.parse(err.responseText); //would prefer not to have a try/catch clause
errObj = extend(true, {}, errObj, errParsed);
} catch(e){}
call(cb, errObj);
};
if (typeof window !== 'undefined' && window.XMLHttpRequest) {
var timer,timedout = false;
var xhr = new XMLHttpRequest();
xhr.open(options.method, options.url);
if (options.json) {
options.headers.Accept = 'application/json';
options.headers['Content-Type'] = options.headers['Content-Type'] || 'application/json';
if (options.body && options.processData && typeof options.body !== "string") {
options.body = JSON.stringify(options.body);
}
}
if (options.binary) {
xhr.responseType = 'arraybuffer';
}
for (var key in options.headers){
xhr.setRequestHeader(key, options.headers[key]);
}
if (!("body" in options)) {
options.body = null;
}
var abortReq = function() {
timedout=true;
xhr.abort();
call(onError, xhr, callback);
};
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4 || timedout) {
return;
}
clearTimeout(timer);
if (xhr.status >= 200 && xhr.status < 300) {
var data;
if (options.binary) {
data = new Blob([xhr.response || ''], {type: xhr.getResponseHeader('Content-Type')});
} else {
data = xhr.responseText;
}
call(onSuccess, data, xhr, callback);
} else {
call(onError, xhr, callback);
}
};
if (options.timeout > 0) {
timer = setTimeout(abortReq, options.timeout);
}
xhr.send(options.body);
return {abort:abortReq};
} else {
if (options.json) {
if (!options.binary) {
options.headers.Accept = 'application/json';
}
options.headers['Content-Type'] = options.headers['Content-Type'] || 'application/json';
}
if (options.binary) {
options.encoding = null;
options.json = false;
}
if (!options.processData) {
options.json = false;
}
return request(options, function(err, response, body) {
if (err) {
err.status = response ? response.statusCode : 400;
return call(onError, err, callback);
}
var content_type = response.headers['content-type'];
var data = (body || '');
// CouchDB doesn't always return the right content-type for JSON data, so
// we check for ^{ and }$ (ignoring leading/trailing whitespace)
if (!options.binary && (options.json || !options.processData) && typeof data !== 'object' &&
(/json/.test(content_type) ||
(/^[\s]*\{/.test(data) && /\}[\s]*$/.test(data)))) {
data = JSON.parse(data);
}
if (response.statusCode >= 200 && response.statusCode < 300) {
call(onSuccess, data, response, callback);
}
else {
if (options.binary) {
var data = JSON.parse(data.toString());
}
data.status = response.statusCode;
call(callback, data);
}
});
}
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = ajax;
}
/*globals PouchAdapter: true, extend: true */
"use strict";
var Pouch = function Pouch(name, opts, callback) {
if (!(this instanceof Pouch)) {
return new Pouch(name, opts, callback);
}
if (typeof opts === 'function' || typeof opts === 'undefined') {
callback = opts;
opts = {};
}
if (typeof name === 'object') {
opts = name;
name = undefined;
}
if (typeof callback === 'undefined') {
callback = function() {};
}
var backend = Pouch.parseAdapter(opts.name || name);
opts.originalName = name;
opts.name = opts.name || backend.name;
opts.adapter = opts.adapter || backend.adapter;
if (!Pouch.adapters[opts.adapter]) {
throw 'Adapter is missing';
}
if (!Pouch.adapters[opts.adapter].valid()) {
throw 'Invalid Adapter';
}
var adapter = new PouchAdapter(opts, function(err, db) {
if (err) {
if (callback) {
callback(err);
}
return;
}
for (var plugin in Pouch.plugins) {
// In future these will likely need to be async to allow the plugin
// to initialise
var pluginObj = Pouch.plugins[plugin](db);
for (var api in pluginObj) {
// We let things like the http adapter use its own implementation
// as it shares a lot of code
if (!(api in db)) {
db[api] = pluginObj[api];
}
}
}
db.taskqueue.ready(true);
db.taskqueue.execute(db);
callback(null, db);
});
for (var j in adapter) {
this[j] = adapter[j];
}
for (var plugin in Pouch.plugins) {
// In future these will likely need to be async to allow the plugin
// to initialise
var pluginObj = Pouch.plugins[plugin](this);
for (var api in pluginObj) {
// We let things like the http adapter use its own implementation
// as it shares a lot of code
if (!(api in this)) {
this[api] = pluginObj[api];
}
}
}
};
Pouch.DEBUG = false;
Pouch.openReqList = {};
Pouch.adapters = {};
Pouch.plugins = {};
Pouch.prefix = '_pouch_';
Pouch.parseAdapter = function(name) {
var match = name.match(/([a-z\-]*):\/\/(.*)/);
var adapter;
if (match) {
// the http adapter expects the fully qualified name
name = /http(s?)/.test(match[1]) ? match[1] + '://' + match[2] : match[2];
adapter = match[1];
if (!Pouch.adapters[adapter].valid()) {
throw 'Invalid adapter';
}
return {name: name, adapter: match[1]};
}
var preferredAdapters = ['idb', 'leveldb', 'websql'];
for (var i = 0; i < preferredAdapters.length; ++i) {
if (preferredAdapters[i] in Pouch.adapters) {
adapter = Pouch.adapters[preferredAdapters[i]];
var use_prefix = 'use_prefix' in adapter ? adapter.use_prefix : true;
return {
name: use_prefix ? Pouch.prefix + name : name,
adapter: preferredAdapters[i]
};
}
}
throw 'No valid adapter found';
};
Pouch.destroy = function(name, callback) {
var opts = Pouch.parseAdapter(name);
var cb = function(err, response) {
if (err) {
callback(err);
return;
}
for (var plugin in Pouch.plugins) {
Pouch.plugins[plugin]._delete(name);
}
if (Pouch.DEBUG) {
console.log(name + ': Delete Database');
}
// call destroy method of the particular adaptor
Pouch.adapters[opts.adapter].destroy(opts.name, callback);
};
// remove Pouch from allDBs
Pouch.removeFromAllDbs(opts, cb);
};
Pouch.removeFromAllDbs = function(opts, callback) {
// Only execute function if flag is enabled
if (!Pouch.enableAllDbs) {
callback();
return;
}
// skip http and https adaptors for allDbs
var adapter = opts.adapter;
if (adapter === "http" || adapter === "https") {
callback();
return;
}
// remove db from Pouch.ALL_DBS
new Pouch(Pouch.allDBName(opts.adapter), function(err, db) {
if (err) {
// don't fail when allDbs fail
console.error(err);
callback();
return;
}
// check if db has been registered in Pouch.ALL_DBS
var dbname = Pouch.dbName(opts.adapter, opts.name);
db.get(dbname, function(err, doc) {
if (err) {
callback();
} else {
db.remove(doc, function(err, response) {
if (err) {
console.error(err);
}
callback();
});
}
});
});
};
Pouch.adapter = function (id, obj) {
if (obj.valid()) {
Pouch.adapters[id] = obj;
}
};
Pouch.plugin = function(id, obj) {
Pouch.plugins[id] = obj;
};
// flag to toggle allDbs (off by default)
Pouch.enableAllDbs = false;
// name of database used to keep track of databases
Pouch.ALL_DBS = "_allDbs";
Pouch.dbName = function(adapter, name) {
return [adapter, "-", name].join('');
};
Pouch.realDBName = function(adapter, name) {
return [adapter, "://", name].join('');
};
Pouch.allDBName = function(adapter) {
return [adapter, "://", Pouch.prefix + Pouch.ALL_DBS].join('');
};
Pouch.open = function(opts, callback) {
// Only register pouch with allDbs if flag is enabled
if (!Pouch.enableAllDbs) {
callback();
return;
}
var adapter = opts.adapter;
// skip http and https adaptors for allDbs
if (adapter === "http" || adapter === "https") {
callback();
return;
}
new Pouch(Pouch.allDBName(adapter), function(err, db) {
if (err) {
// don't fail when allDb registration fails
console.error(err);
callback();
return;
}
// check if db has been registered in Pouch.ALL_DBS
var dbname = Pouch.dbName(adapter, opts.name);
db.get(dbname, function(err, response) {
if (err && err.status === 404) {
db.put({
_id: dbname,
dbname: opts.originalName
}, function(err) {
if (err) {
console.error(err);
}
callback();
});
} else {
callback();
}
});
});
};
Pouch.allDbs = function(callback) {
var accumulate = function(adapters, all_dbs) {
if (adapters.length === 0) {
// remove duplicates
var result = [];
all_dbs.forEach(function(doc) {
var exists = result.some(function(db) {
return db.id === doc.id;
});
if (!exists) {
result.push(doc);
}
});
// return an array of dbname
callback(null, result.map(function(row) {
return row.doc.dbname;
}));
return;
}
var adapter = adapters.shift();
// skip http and https adaptors for allDbs
if (adapter === "http" || adapter === "https") {
accumulate(adapters, all_dbs);
return;
}
new Pouch(Pouch.allDBName(adapter), function(err, db) {
if (err) {
callback(err);
return;
}
db.allDocs({include_docs: true}, function(err, response) {
if (err) {
callback(err);
return;
}
// append from current adapter rows
all_dbs.unshift.apply(all_dbs, response.rows);
// code to clear allDbs.
// response.rows.forEach(function(row) {
// db.remove(row.doc, function() {
// console.log(arguments);
// });
// });
// recurse
accumulate(adapters, all_dbs);
});
});
};
var adapters = Object.keys(Pouch.adapters);
accumulate(adapters, []);
};
/*
Examples:
>>> Pouch.uuids()
"92329D39-6F5C-4520-ABFC-AAB64544E172"]
>>> Pouch.uuids(10, {length: 32, radix: 5})
[ '04422200002240221333300140323100',
'02304411022101001312440440020110',
'41432430322114143303343433433030',
'21234330022303431304443100330401',
'23044133434242034101422131301213',
'43142032223224403322031032232041',
'41121132424023141101403324200330',
'00341042023103204342124004122342',
'01001141433040113422403034004214',
'30221232324132303123433131020020' ]
*/
Pouch.uuids = function (count, options) {
if (typeof(options) !== 'object') {
options = {};
}
var length = options.length;
var radix = options.radix;
var uuids = [];
while (uuids.push(Math.uuid(length, radix)) < count) {
}
return uuids;
};
// Give back one UUID
Pouch.uuid = function (options) {
return Pouch.uuids(1, options)[0];
};
// Enumerate errors, add the status code so we can reflect the HTTP api
// in future
Pouch.Errors = {
MISSING_BULK_DOCS: {
status: 400,
error: 'bad_request',