forked from mWater/minimongo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimongo.js
More file actions
14057 lines (12642 loc) · 446 KB
/
Copy pathminimongo.js
File metadata and controls
14057 lines (12642 loc) · 446 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
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 18);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
var async, booleanCrosses, booleanPointInPolygon, booleanWithin, bowser, compileDocumentSelector, compileSort, deg2rad, getDistanceFromLatLngInM, intersect, isLocalStorageSupported, pointInPolygon, polygonIntersection, processGeoIntersectsOperator, processNearOperator, _;
_ = __webpack_require__(1);
async = __webpack_require__(5);
bowser = __webpack_require__(22);
compileDocumentSelector = __webpack_require__(2).compileDocumentSelector;
compileSort = __webpack_require__(2).compileSort;
booleanPointInPolygon = __webpack_require__(9)["default"];
intersect = __webpack_require__(24)["default"];
booleanCrosses = __webpack_require__(26)["default"];
booleanWithin = __webpack_require__(33)["default"];
isLocalStorageSupported = function() {
var e;
if (!window.localStorage) {
return false;
}
try {
window.localStorage.setItem("test", "test");
window.localStorage.removeItem("test");
return true;
} catch (_error) {
e = _error;
return false;
}
};
exports.compileDocumentSelector = compileDocumentSelector;
exports.autoselectLocalDb = function(options, success, error) {
var IndexedDb, LocalStorageDb, MemoryDb, WebSQLDb, browser, _ref;
IndexedDb = __webpack_require__(12);
WebSQLDb = __webpack_require__(13);
LocalStorageDb = __webpack_require__(14);
MemoryDb = __webpack_require__(10);
browser = bowser.browser;
if (!isLocalStorageSupported()) {
return new MemoryDb(options, success);
}
if (window.cordova) {
if (((_ref = window.device) != null ? _ref.platform : void 0) === "iOS" && window.sqlitePlugin) {
console.log("Selecting WebSQLDb(sqlite) for Cordova");
options.storage = 'sqlite';
return new WebSQLDb(options, success, error);
} else {
console.log("Selecting else WebSQLDb for Cordova");
return new WebSQLDb(options, success, error);
}
}
if (browser.android || browser.ios || browser.chrome || browser.safari || browser.opera || browser.blackberry) {
console.log("Selecting WebSQLDb for browser");
return new WebSQLDb(options, success, (function(_this) {
return function(err) {
console.log("Failed to create WebSQLDb: " + (err ? err.message : void 0));
return new IndexedDb(options, success, function(err) {
console.log("Failed to create IndexedDb: " + (err ? err.message : void 0));
return new MemoryDb(options, success);
});
};
})(this));
}
if (browser.firefox && browser.version >= 16) {
console.log("Selecting IndexedDb for browser");
return new IndexedDb(options, success, (function(_this) {
return function(err) {
console.log("Failed to create IndexedDb: " + (err ? err.message : void 0));
return new MemoryDb(options, success);
};
})(this));
}
console.log("Selecting LocalStorageDb for fallback");
return new LocalStorageDb(options, success, error);
};
exports.migrateLocalDb = function(fromDb, toDb, success, error) {
var HybridDb, col, hybridDb, name, _ref;
HybridDb = __webpack_require__(15);
hybridDb = new HybridDb(fromDb, toDb);
_ref = fromDb.collections;
for (name in _ref) {
col = _ref[name];
if (toDb[name]) {
hybridDb.addCollection(name);
}
}
return hybridDb.upload(success, error);
};
exports.cloneLocalDb = function(fromDb, toDb, success, error) {
var col, name, _ref;
_ref = fromDb.collections;
for (name in _ref) {
col = _ref[name];
if (!toDb[name]) {
toDb.addCollection(name);
}
}
return async.each(_.values(fromDb.collections), (function(_this) {
return function(fromCol, cb) {
var toCol;
toCol = toDb[fromCol.name];
return fromCol.find({}).fetch(function(items) {
return toCol.seed(items, function() {
return fromCol.pendingUpserts(function(upserts) {
return toCol.upsert(_.pluck(upserts, "doc"), _.pluck(upserts, "base"), function() {
return fromCol.pendingRemoves(function(removes) {
return async.eachSeries(removes, function(remove, cb2) {
return toCol.remove(remove, function() {
return cb2();
}, cb2);
}, cb);
}, cb);
}, cb);
}, cb);
}, cb);
}, cb);
};
})(this), (function(_this) {
return function(err) {
if (err) {
return error(err);
}
return success();
};
})(this));
};
exports.cloneLocalCollection = function(fromCol, toCol, success, error) {
return fromCol.find({}).fetch((function(_this) {
return function(items) {
return toCol.seed(items, function() {
return fromCol.pendingUpserts(function(upserts) {
return toCol.upsert(_.pluck(upserts, "doc"), _.pluck(upserts, "base"), function() {
return fromCol.pendingRemoves(function(removes) {
return async.eachSeries(removes, function(remove, cb2) {
return toCol.remove(remove, function() {
return cb2();
}, cb2);
}, function(err) {
if (err) {
return error(err);
}
return success();
});
}, error);
}, error);
}, error);
}, error);
};
})(this), error);
};
exports.processFind = function(items, selector, options, count) {
var filtered;
if (count == null) {
count = {};
}
filtered = _.filter(items, compileDocumentSelector(selector));
filtered = processNearOperator(selector, filtered);
filtered = processGeoIntersectsOperator(selector, filtered);
count.filtered = filtered.length;
if (options && options.sort) {
filtered.sort(compileSort(options.sort));
}
if (options && options.skip) {
filtered = _.slice(filtered, options.skip);
}
if (options && options.limit) {
filtered = _.take(filtered, options.limit);
}
if (options && options.fields) {
filtered = exports.filterFields(filtered, options.fields);
}
return filtered;
};
exports.filterFields = function(items, fields) {
if (fields == null) {
fields = {};
}
if (_.keys(fields).length === 0) {
return items;
}
return _.map(items, function(item) {
var field, from, newItem, obj, path, pathElem, to, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref, _ref1, _ref2, _ref3;
newItem = {};
if (_.first(_.values(fields)) === 1) {
_ref = _.keys(fields).concat(["_id"]);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
field = _ref[_i];
path = field.split(".");
obj = item;
for (_j = 0, _len1 = path.length; _j < _len1; _j++) {
pathElem = path[_j];
if (obj) {
obj = obj[pathElem];
}
}
if (obj == null) {
continue;
}
from = item;
to = newItem;
_ref1 = _.initial(path);
for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
pathElem = _ref1[_k];
to[pathElem] = to[pathElem] || {};
to = to[pathElem];
from = from[pathElem];
}
to[_.last(path)] = from[_.last(path)];
}
return newItem;
} else {
item = _.cloneDeep(item);
_ref2 = _.keys(fields);
for (_l = 0, _len3 = _ref2.length; _l < _len3; _l++) {
field = _ref2[_l];
path = field.split(".");
obj = item;
_ref3 = _.initial(path);
for (_m = 0, _len4 = _ref3.length; _m < _len4; _m++) {
pathElem = _ref3[_m];
if (obj) {
obj = obj[pathElem];
}
}
if (obj == null) {
continue;
}
delete obj[_.last(path)];
}
return item;
}
});
};
exports.createUid = function() {
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r, v;
r = Math.random() * 16 | 0;
v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
};
processNearOperator = function(selector, list) {
var distances, geo, key, value;
for (key in selector) {
value = selector[key];
if ((value != null) && value['$near']) {
geo = value['$near']['$geometry'];
if (geo.type !== 'Point') {
break;
}
list = _.filter(list, function(doc) {
return doc[key] && doc[key].type === 'Point';
});
distances = _.map(list, function(doc) {
return {
doc: doc,
distance: getDistanceFromLatLngInM(geo.coordinates[1], geo.coordinates[0], doc[key].coordinates[1], doc[key].coordinates[0])
};
});
distances = _.filter(distances, function(item) {
return item.distance >= 0;
});
distances = _.sortBy(distances, 'distance');
if (value['$near']['$maxDistance']) {
distances = _.filter(distances, function(item) {
return item.distance <= value['$near']['$maxDistance'];
});
}
list = _.pluck(distances, 'doc');
}
}
return list;
};
pointInPolygon = function(point, polygon) {
return booleanPointInPolygon(point, polygon);
};
polygonIntersection = function(polygon1, polygon2) {
return intersect(polygon1, polygon2) != null;
};
getDistanceFromLatLngInM = function(lat1, lng1, lat2, lng2) {
var R, a, c, d, dLat, dLng;
R = 6370986;
dLat = deg2rad(lat2 - lat1);
dLng = deg2rad(lng2 - lng1);
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
d = R * c;
return d;
};
deg2rad = function(deg) {
return deg * (Math.PI / 180);
};
processGeoIntersectsOperator = function(selector, list) {
var geo, key, value;
for (key in selector) {
value = selector[key];
if ((value != null) && value['$geoIntersects']) {
geo = value['$geoIntersects']['$geometry'];
if (geo.type !== 'Polygon') {
break;
}
list = _.filter(list, function(doc) {
var line, lineGeo, _i, _len, _ref, _ref1;
if (!doc[key]) {
return false;
}
if (doc[key].type === 'Point') {
return pointInPolygon(doc[key], geo);
} else if ((_ref = doc[key].type) === "Polygon" || _ref === "MultiPolygon") {
return polygonIntersection(doc[key], geo);
} else if (doc[key].type === "LineString") {
return booleanCrosses(doc[key], geo) || booleanWithin(doc[key], geo);
} else if (doc[key].type === "MultiLineString") {
_ref1 = doc[key].coordinates;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
line = _ref1[_i];
lineGeo = {
type: "LineString",
coordinates: line
};
if (booleanCrosses(lineGeo, geo) || booleanWithin(lineGeo, geo)) {
return true;
}
}
return false;
}
});
}
}
return list;
};
exports.regularizeUpsert = function(docs, bases, success, error) {
var item, items, _i, _len, _ref;
if (_.isFunction(bases)) {
_ref = [void 0, bases, success], bases = _ref[0], success = _ref[1], error = _ref[2];
}
if (!_.isArray(docs)) {
docs = [docs];
bases = [bases];
} else {
bases = bases || [];
}
items = _.map(docs, function(doc, i) {
return {
doc: doc,
base: i < bases.length ? bases[i] : void 0
};
});
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (!item.doc._id) {
item.doc._id = exports.createUid();
}
if (item.base && !item.base._id) {
throw new Error("Base needs _id");
}
if (item.base && item.base._id !== item.doc._id) {
throw new Error("Base needs same _id");
}
}
return [items, success, error];
};
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = _;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
/*
========================================
Meteor is licensed under the MIT License
========================================
Copyright (C) 2011--2012 Meteor Development Group
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
====================================================================
This license applies to all code in Meteor that is not an externally
maintained library. Externally maintained libraries have their own
licenses, included below:
====================================================================
*/
LocalCollection = {};
EJSON = __webpack_require__(23);
var _ = __webpack_require__(1);
// Like _.isArray, but doesn't regard polyfilled Uint8Arrays on old browsers as
// arrays.
var isArray = function (x) {
return _.isArray(x) && !EJSON.isBinary(x);
};
var _anyIfArray = function (x, f) {
if (isArray(x))
return _.any(x, f);
return f(x);
};
var _anyIfArrayPlus = function (x, f) {
if (f(x))
return true;
return isArray(x) && _.any(x, f);
};
var hasOperators = function(valueSelector) {
var theseAreOperators = undefined;
for (var selKey in valueSelector) {
var thisIsOperator = selKey.substr(0, 1) === '$';
if (theseAreOperators === undefined) {
theseAreOperators = thisIsOperator;
} else if (theseAreOperators !== thisIsOperator) {
throw new Error("Inconsistent selector: " + valueSelector);
}
}
return !!theseAreOperators; // {} has no operators
};
var compileValueSelector = function (valueSelector) {
if (valueSelector == null) { // undefined or null
return function (value) {
return _anyIfArray(value, function (x) {
return x == null; // undefined or null
});
};
}
// Selector is a non-null primitive (and not an array or RegExp either).
if (!_.isObject(valueSelector)) {
return function (value) {
return _anyIfArray(value, function (x) {
return x === valueSelector;
});
};
}
if (valueSelector instanceof RegExp) {
return function (value) {
if (value === undefined)
return false;
return _anyIfArray(value, function (x) {
return valueSelector.test(x);
});
};
}
// Arrays match either identical arrays or arrays that contain it as a value.
if (isArray(valueSelector)) {
return function (value) {
if (!isArray(value))
return false;
return _anyIfArrayPlus(value, function (x) {
return LocalCollection._f._equal(valueSelector, x);
});
};
}
// It's an object, but not an array or regexp.
if (hasOperators(valueSelector)) {
var operatorFunctions = [];
_.each(valueSelector, function (operand, operator) {
if (!_.has(VALUE_OPERATORS, operator))
throw new Error("Unrecognized operator: " + operator);
operatorFunctions.push(VALUE_OPERATORS[operator](
operand, valueSelector.$options));
});
return function (value) {
return _.all(operatorFunctions, function (f) {
return f(value);
});
};
}
// It's a literal; compare value (or element of value array) directly to the
// selector.
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._equal(valueSelector, x);
});
};
};
// XXX can factor out common logic below
var LOGICAL_OPERATORS = {
"$and": function(subSelector) {
if (!isArray(subSelector) || _.isEmpty(subSelector))
throw Error("$and/$or/$nor must be nonempty array");
var subSelectorFunctions = _.map(
subSelector, compileDocumentSelector);
return function (doc) {
return _.all(subSelectorFunctions, function (f) {
return f(doc);
});
};
},
"$or": function(subSelector) {
if (!isArray(subSelector) || _.isEmpty(subSelector))
throw Error("$and/$or/$nor must be nonempty array");
var subSelectorFunctions = _.map(
subSelector, compileDocumentSelector);
return function (doc) {
return _.any(subSelectorFunctions, function (f) {
return f(doc);
});
};
},
"$nor": function(subSelector) {
if (!isArray(subSelector) || _.isEmpty(subSelector))
throw Error("$and/$or/$nor must be nonempty array");
var subSelectorFunctions = _.map(
subSelector, compileDocumentSelector);
return function (doc) {
return _.all(subSelectorFunctions, function (f) {
return !f(doc);
});
};
},
"$where": function(selectorValue) {
if (!(selectorValue instanceof Function)) {
selectorValue = Function("return " + selectorValue);
}
return function (doc) {
return selectorValue.call(doc);
};
}
};
var VALUE_OPERATORS = {
"$in": function (operand) {
if (!isArray(operand))
throw new Error("Argument to $in must be array");
// Create index if all strings
var index = null;
if (_.all(operand, _.isString))
index = _.indexBy(operand);
return function (value) {
return _anyIfArrayPlus(value, function (x) {
if (_.isString(x) && index !== null)
return index[x] != undefined;
return _.any(operand, function (operandElt) {
return LocalCollection._f._equal(operandElt, x);
});
});
};
},
"$all": function (operand) {
if (!isArray(operand))
throw new Error("Argument to $all must be array");
return function (value) {
if (!isArray(value))
return false;
return _.all(operand, function (operandElt) {
return _.any(value, function (valueElt) {
return LocalCollection._f._equal(operandElt, valueElt);
});
});
};
},
"$lt": function (operand) {
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._cmp(x, operand) < 0;
});
};
},
"$lte": function (operand) {
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._cmp(x, operand) <= 0;
});
};
},
"$gt": function (operand) {
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._cmp(x, operand) > 0;
});
};
},
"$gte": function (operand) {
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._cmp(x, operand) >= 0;
});
};
},
"$ne": function (operand) {
return function (value) {
return ! _anyIfArrayPlus(value, function (x) {
return LocalCollection._f._equal(x, operand);
});
};
},
"$nin": function (operand) {
if (!isArray(operand))
throw new Error("Argument to $nin must be array");
var inFunction = VALUE_OPERATORS.$in(operand);
return function (value) {
// Field doesn't exist, so it's not-in operand
if (value === undefined)
return true;
return !inFunction(value);
};
},
"$exists": function (operand) {
return function (value) {
return operand === (value !== undefined);
};
},
"$mod": function (operand) {
var divisor = operand[0],
remainder = operand[1];
return function (value) {
return _anyIfArray(value, function (x) {
return x % divisor === remainder;
});
};
},
"$size": function (operand) {
return function (value) {
return isArray(value) && operand === value.length;
};
},
"$type": function (operand) {
return function (value) {
// A nonexistent field is of no type.
if (value === undefined)
return false;
// Definitely not _anyIfArrayPlus: $type: 4 only matches arrays that have
// arrays as elements according to the Mongo docs.
return _anyIfArray(value, function (x) {
return LocalCollection._f._type(x) === operand;
});
};
},
"$regex": function (operand, options) {
if (options !== undefined) {
// Options passed in $options (even the empty string) always overrides
// options in the RegExp object itself.
// Be clear that we only support the JS-supported options, not extended
// ones (eg, Mongo supports x and s). Ideally we would implement x and s
// by transforming the regexp, but not today...
if (/[^gim]/.test(options))
throw new Error("Only the i, m, and g regexp options are supported");
var regexSource = operand instanceof RegExp ? operand.source : operand;
operand = new RegExp(regexSource, options);
} else if (!(operand instanceof RegExp)) {
operand = new RegExp(operand);
}
return function (value) {
if (value === undefined)
return false;
return _anyIfArray(value, function (x) {
return operand.test(x);
});
};
},
"$options": function (operand) {
// evaluation happens at the $regex function above
return function (value) { return true; };
},
"$elemMatch": function (operand) {
var matcher = compileDocumentSelector(operand);
return function (value) {
if (!isArray(value))
return false;
return _.any(value, function (x) {
return matcher(x);
});
};
},
"$not": function (operand) {
var matcher = compileValueSelector(operand);
return function (value) {
return !matcher(value);
};
},
"$near": function (operand) {
// Always returns true. Must be handled in post-filter/sort/limit
return function (value) {
return true;
}
},
"$geoIntersects": function (operand) {
// Always returns true. Must be handled in post-filter/sort/limit
return function (value) {
return true;
}
}
};
// helpers used by compiled selector code
LocalCollection._f = {
// XXX for _all and _in, consider building 'inquery' at compile time..
_type: function (v) {
if (typeof v === "number")
return 1;
if (typeof v === "string")
return 2;
if (typeof v === "boolean")
return 8;
if (isArray(v))
return 4;
if (v === null)
return 10;
if (v instanceof RegExp)
return 11;
if (typeof v === "function")
// note that typeof(/x/) === "function"
return 13;
if (v instanceof Date)
return 9;
if (EJSON.isBinary(v))
return 5;
return 3; // object
// XXX support some/all of these:
// 14, symbol
// 15, javascript code with scope
// 16, 18: 32-bit/64-bit integer
// 17, timestamp
// 255, minkey
// 127, maxkey
},
// deep equality test: use for literal document and array matches
_equal: function (a, b) {
return EJSON.equals(a, b, {keyOrderSensitive: true});
},
// maps a type code to a value that can be used to sort values of
// different types
_typeorder: function (t) {
// http://www.mongodb.org/display/DOCS/What+is+the+Compare+Order+for+BSON+Types
// XXX what is the correct sort position for Javascript code?
// ('100' in the matrix below)
// XXX minkey/maxkey
return [-1, // (not a type)
1, // number
2, // string
3, // object
4, // array
5, // binary
-1, // deprecated
6, // ObjectID
7, // bool
8, // Date
0, // null
9, // RegExp
-1, // deprecated
100, // JS code
2, // deprecated (symbol)
100, // JS code
1, // 32-bit int
8, // Mongo timestamp
1 // 64-bit int
][t];
},
// compare two values of unknown type according to BSON ordering
// semantics. (as an extension, consider 'undefined' to be less than
// any other value.) return negative if a is less, positive if b is
// less, or 0 if equal
_cmp: function (a, b) {
if (a === undefined)
return b === undefined ? 0 : -1;
if (b === undefined)
return 1;
var ta = LocalCollection._f._type(a);
var tb = LocalCollection._f._type(b);
var oa = LocalCollection._f._typeorder(ta);
var ob = LocalCollection._f._typeorder(tb);
if (oa !== ob)
return oa < ob ? -1 : 1;
if (ta !== tb)
// XXX need to implement this if we implement Symbol or integers, or
// Timestamp
throw Error("Missing type coercion logic in _cmp");
if (ta === 7) { // ObjectID
}
if (ta === 9) { // Date
// Convert to millis.
ta = tb = 1;
a = a.getTime();
b = b.getTime();
}
if (ta === 1) // double
return a - b;
if (tb === 2) // string
return a < b ? -1 : (a === b ? 0 : 1);
if (ta === 3) { // Object
// this could be much more efficient in the expected case ...
var to_array = function (obj) {
var ret = [];
for (var key in obj) {
ret.push(key);
ret.push(obj[key]);
}
return ret;
};
return LocalCollection._f._cmp(to_array(a), to_array(b));
}
if (ta === 4) { // Array
for (var i = 0; ; i++) {
if (i === a.length)
return (i === b.length) ? 0 : -1;
if (i === b.length)
return 1;
var s = LocalCollection._f._cmp(a[i], b[i]);
if (s !== 0)
return s;
}
}
if (ta === 5) { // binary
// Surprisingly, a small binary blob is always less than a large one in
// Mongo.
if (a.length !== b.length)
return a.length - b.length;
for (i = 0; i < a.length; i++) {
if (a[i] < b[i])
return -1;
if (a[i] > b[i])
return 1;
}
return 0;
}
if (ta === 8) { // boolean
if (a) return b ? 0 : 1;
return b ? -1 : 0;
}
if (ta === 10) // null
return 0;
if (ta === 11) // regexp
throw Error("Sorting not supported on regular expression"); // XXX
// 13: javascript code
// 14: symbol
// 15: javascript code with scope
// 16: 32-bit integer
// 17: timestamp
// 18: 64-bit integer
// 255: minkey
// 127: maxkey
if (ta === 13) // javascript code
throw Error("Sorting not supported on Javascript code"); // XXX
throw Error("Unknown type to sort");
}
};
// For unit tests. True if the given document matches the given
// selector.
LocalCollection._matches = function (selector, doc) {
return (LocalCollection._compileSelector(selector))(doc);
};
// _makeLookupFunction(key) returns a lookup function.
//
// A lookup function takes in a document and returns an array of matching
// values. This array has more than one element if any segment of the key other
// than the last one is an array. ie, any arrays found when doing non-final
// lookups result in this function "branching"; each element in the returned
// array represents the value found at this branch. If any branch doesn't have a
// final value for the full key, its element in the returned list will be
// undefined. It always returns a non-empty array.
//
// _makeLookupFunction('a.x')({a: {x: 1}}) returns [1]
// _makeLookupFunction('a.x')({a: {x: [1]}}) returns [[1]]
// _makeLookupFunction('a.x')({a: 5}) returns [undefined]
// _makeLookupFunction('a.x')({a: [{x: 1},