-
Notifications
You must be signed in to change notification settings - Fork 3
/
minimongo.js
5846 lines (5837 loc) · 261 KB
/
minimongo.js
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(exports, global) {
global["Minimongo"] = exports;
var __meteor_runtime_config__ = {};
/**
* @summary The Meteor namespace
* @namespace Meteor
*/
Meteor = {
/**
* @summary Boolean variable. True if running in client environment.
* @locus Anywhere
* @static
* @type {Boolean}
*/
isClient: true,
/**
* @summary Boolean variable. True if running in server environment.
* @locus Anywhere
* @static
* @type {Boolean}
*/
isServer: false,
isCordova: false
};
if (typeof __meteor_runtime_config__ === "object" && __meteor_runtime_config__.PUBLIC_SETTINGS) {
/**
* @summary `Meteor.settings` contains deployment-specific configuration options. You can initialize settings by passing the `--settings` option (which takes the name of a file containing JSON data) to `meteor run` or `meteor deploy`. When running your server directly (e.g. from a bundle), you instead specify settings by putting the JSON directly into the `METEOR_SETTINGS` environment variable. If you don't provide any settings, `Meteor.settings` will be an empty object. If the settings object contains a key named `public`, then `Meteor.settings.public` will be available on the client as well as the server. All other properties of `Meteor.settings` are only defined on the server.
* @locus Anywhere
* @type {Object}
*/
Meteor.settings = {
"public": __meteor_runtime_config__.PUBLIC_SETTINGS
};
}
if (Meteor.isServer) var Future = Npm.require("fibers/future");
if (typeof __meteor_runtime_config__ === "object" && __meteor_runtime_config__.meteorRelease) {
/**
* @summary `Meteor.release` is a string containing the name of the [release](#meteorupdate) with which the project was built (for example, `"1.2.3"`). It is `undefined` if the project was built using a git checkout of Meteor.
* @locus Anywhere
* @type {String}
*/
Meteor.release = __meteor_runtime_config__.meteorRelease;
}
// XXX find a better home for these? Ideally they would be _.get,
// _.ensure, _.delete..
_.extend(Meteor, {
// _get(a,b,c,d) returns a[b][c][d], or else undefined if a[b] or
// a[b][c] doesn't exist.
//
_get: function(obj) {
for (var i = 1; i < arguments.length; i++) {
if (!(arguments[i] in obj)) return undefined;
obj = obj[arguments[i]];
}
return obj;
},
// _ensure(a,b,c,d) ensures that a[b][c][d] exists. If it does not,
// it is created and set to {}. Either way, it is returned.
//
_ensure: function(obj) {
for (var i = 1; i < arguments.length; i++) {
var key = arguments[i];
if (!(key in obj)) obj[key] = {};
obj = obj[key];
}
return obj;
},
// _delete(a, b, c, d) deletes a[b][c][d], then a[b][c] unless it
// isn't empty, then a[b] unless it isn't empty.
//
_delete: function(obj) {
var stack = [ obj ];
var leaf = true;
for (var i = 1; i < arguments.length - 1; i++) {
var key = arguments[i];
if (!(key in obj)) {
leaf = false;
break;
}
obj = obj[key];
if (typeof obj !== "object") break;
stack.push(obj);
}
for (var i = stack.length - 1; i >= 0; i--) {
var key = arguments[i + 1];
if (leaf) leaf = false; else for (var other in stack[i][key]) return;
// not empty -- we're done
delete stack[i][key];
}
},
// wrapAsync can wrap any function that takes some number of arguments that
// can't be undefined, followed by some optional arguments, where the callback
// is the last optional argument.
// e.g. fs.readFile(pathname, [callback]),
// fs.open(pathname, flags, [mode], [callback])
// For maximum effectiveness and least confusion, wrapAsync should be used on
// functions where the callback is the only argument of type Function.
/**
* @memberOf Meteor
* @summary Wrap a function that takes a callback function as its final parameter. On the server, the wrapped function can be used either synchronously (without passing a callback) or asynchronously (when a callback is passed). On the client, a callback is always required; errors will be logged if there is no callback. If a callback is provided, the environment captured when the original function was called will be restored in the callback.
* @locus Anywhere
* @param {Function} func A function that takes a callback as its final parameter
* @param {Object} [context] Optional `this` object against which the original function will be invoked
*/
wrapAsync: function(fn, context) {
return function() {
var self = context || this;
var newArgs = _.toArray(arguments);
var callback;
for (var i = newArgs.length - 1; i >= 0; --i) {
var arg = newArgs[i];
var type = typeof arg;
if (type !== "undefined") {
if (type === "function") {
callback = arg;
}
break;
}
}
if (!callback) {
if (Meteor.isClient) {
callback = logErr;
} else {
var fut = new Future();
callback = fut.resolver();
}
++i;
}
newArgs[i] = Meteor.bindEnvironment(callback);
var result = fn.apply(self, newArgs);
return fut ? fut.wait() : result;
};
},
// Sets child's prototype to a new object whose prototype is parent's
// prototype. Used as:
// Meteor._inherits(ClassB, ClassA).
// _.extend(ClassB.prototype, { ... })
// Inspired by CoffeeScript's `extend` and Google Closure's `goog.inherits`.
_inherits: function(Child, Parent) {
// copy Parent static properties
for (var key in Parent) {
// make sure we only copy hasOwnProperty properties vs. prototype
// properties
if (_.has(Parent, key)) Child[key] = Parent[key];
}
// a middle member of prototype chain: takes the prototype from the Parent
var Middle = function() {
this.constructor = Child;
};
Middle.prototype = Parent.prototype;
Child.prototype = new Middle();
Child.__super__ = Parent.prototype;
return Child;
}
});
var warnedAboutWrapAsync = false;
/**
* @deprecated in 0.9.3
*/
Meteor._wrapAsync = function(fn, context) {
if (!warnedAboutWrapAsync) {
Meteor._debug("Meteor._wrapAsync has been renamed to Meteor.wrapAsync");
warnedAboutWrapAsync = true;
}
return Meteor.wrapAsync.apply(Meteor, arguments);
};
function logErr(err) {
if (err) {
return Meteor._debug("Exception in callback of async function", err.stack ? err.stack : err);
}
}
// Chooses one of three setImmediate implementations:
//
// * Native setImmediate (IE 10, Node 0.9+)
//
// * postMessage (many browsers)
//
// * setTimeout (fallback)
//
// The postMessage implementation is based on
// https://github.com/NobleJS/setImmediate/tree/1.0.1
//
// Don't use `nextTick` for Node since it runs its callbacks before
// I/O, which is stricter than we're looking for.
//
// Not installed as a polyfill, as our public API is `Meteor.defer`.
// Since we're not trying to be a polyfill, we have some
// simplifications:
//
// If one invocation of a setImmediate callback pauses itself by a
// call to alert/prompt/showModelDialog, the NobleJS polyfill
// implementation ensured that no setImmedate callback would run until
// the first invocation completed. While correct per the spec, what it
// would mean for us in practice is that any reactive updates relying
// on Meteor.defer would be hung in the main window until the modal
// dialog was dismissed. Thus we only ensure that a setImmediate
// function is called in a later event loop.
//
// We don't need to support using a string to be eval'ed for the
// callback, arguments to the function, or clearImmediate.
"use strict";
var global = this;
// IE 10, Node >= 9.1
function useSetImmediate() {
if (!global.setImmediate) return null; else {
var setImmediate = function(fn) {
global.setImmediate(fn);
};
setImmediate.implementation = "setImmediate";
return setImmediate;
}
}
// Android 2.3.6, Chrome 26, Firefox 20, IE 8-9, iOS 5.1.1 Safari
function usePostMessage() {
// The test against `importScripts` prevents this implementation
// from being installed inside a web worker, where
// `global.postMessage` means something completely different and
// can't be used for this purpose.
if (!global.postMessage || global.importScripts) {
return null;
}
// Avoid synchronous post message implementations.
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function() {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
if (!postMessageIsAsynchronous) return null;
var funcIndex = 0;
var funcs = {};
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
// XXX use Random.id() here?
var MESSAGE_PREFIX = "Meteor._setImmediate." + Math.random() + ".";
function isStringAndStartsWith(string, putativeStart) {
return typeof string === "string" && string.substring(0, putativeStart.length) === putativeStart;
}
function onGlobalMessage(event) {
// This will catch all incoming messages (even from other
// windows!), so we need to try reasonably hard to avoid letting
// anyone else trick us into firing off. We test the origin is
// still this window, and that a (randomly generated)
// unpredictable identifying prefix is present.
if (event.source === global && isStringAndStartsWith(event.data, MESSAGE_PREFIX)) {
var index = event.data.substring(MESSAGE_PREFIX.length);
try {
if (funcs[index]) funcs[index]();
} finally {
delete funcs[index];
}
}
}
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
var setImmediate = function(fn) {
// Make `global` post a message to itself with the handle and
// identifying prefix, thus asynchronously invoking our
// onGlobalMessage listener above.
++funcIndex;
funcs[funcIndex] = fn;
global.postMessage(MESSAGE_PREFIX + funcIndex, "*");
};
setImmediate.implementation = "postMessage";
return setImmediate;
}
function useTimeout() {
var setImmediate = function(fn) {
global.setTimeout(fn, 0);
};
setImmediate.implementation = "setTimeout";
return setImmediate;
}
Meteor._setImmediate = useSetImmediate() || usePostMessage() || useTimeout();
var withoutInvocation = function(f) {
if (Package.ddp) {
var _CurrentInvocation = Package.ddp.DDP._CurrentInvocation;
if (_CurrentInvocation.get() && _CurrentInvocation.get().isSimulation) throw new Error("Can't set timers inside simulations");
return function() {
_CurrentInvocation.withValue(null, f);
};
} else return f;
};
var bindAndCatch = function(context, f) {
return Meteor.bindEnvironment(withoutInvocation(f), context);
};
_.extend(Meteor, {
// Meteor.setTimeout and Meteor.setInterval callbacks scheduled
// inside a server method are not part of the method invocation and
// should clear out the CurrentInvocation environment variable.
/**
* @memberOf Meteor
* @summary Call a function in the future after waiting for a specified delay.
* @locus Anywhere
* @param {Function} func The function to run
* @param {Number} delay Number of milliseconds to wait before calling function
*/
setTimeout: function(f, duration) {
return setTimeout(bindAndCatch("setTimeout callback", f), duration);
},
/**
* @memberOf Meteor
* @summary Call a function repeatedly, with a time delay between calls.
* @locus Anywhere
* @param {Function} func The function to run
* @param {Number} delay Number of milliseconds to wait between each function call.
*/
setInterval: function(f, duration) {
return setInterval(bindAndCatch("setInterval callback", f), duration);
},
/**
* @memberOf Meteor
* @summary Cancel a repeating function call scheduled by `Meteor.setInterval`.
* @locus Anywhere
* @param {Number} id The handle returned by `Meteor.setInterval`
*/
clearInterval: function(x) {
return clearInterval(x);
},
/**
* @memberOf Meteor
* @summary Cancel a function call scheduled by `Meteor.setTimeout`.
* @locus Anywhere
* @param {Number} id The handle returned by `Meteor.setTimeout`
*/
clearTimeout: function(x) {
return clearTimeout(x);
},
// XXX consider making this guarantee ordering of defer'd callbacks, like
// Tracker.afterFlush or Node's nextTick (in practice). Then tests can do:
// callSomethingThatDefersSomeWork();
// Meteor.defer(expect(somethingThatValidatesThatTheWorkHappened));
defer: function(f) {
Meteor._setImmediate(bindAndCatch("defer callback", f));
}
});
// Makes an error subclass which properly contains a stack trace in most
// environments. constructor can set fields on `this` (and should probably set
// `message`, which is what gets displayed at the top of a stack trace).
//
Meteor.makeErrorType = function(name, constructor) {
var errorClass = function() {
var self = this;
// Ensure we get a proper stack trace in most Javascript environments
if (Error.captureStackTrace) {
// V8 environments (Chrome and Node.js)
Error.captureStackTrace(self, errorClass);
} else {
// Firefox
var e = new Error();
e.__proto__ = errorClass.prototype;
if (e instanceof errorClass) self = e;
}
// Safari magically works.
constructor.apply(self, arguments);
self.errorType = name;
return self;
};
Meteor._inherits(errorClass, Error);
return errorClass;
};
// This should probably be in the livedata package, but we don't want
// to require you to use the livedata package to get it. Eventually we
// should probably rename it to DDP.Error and put it back in the
// 'livedata' package (which we should rename to 'ddp' also.)
//
// Note: The DDP server assumes that Meteor.Error EJSON-serializes as an object
// containing 'error' and optionally 'reason' and 'details'.
// The DDP client manually puts these into Meteor.Error objects. (We don't use
// EJSON.addType here because the type is determined by location in the
// protocol, not text on the wire.)
/**
* @summary This class represents a symbolic error thrown by a method.
* @locus Anywhere
* @class
* @param {String} error A string code uniquely identifying this kind of error.
* This string should be used by callers of the method to determine the
* appropriate action to take, instead of attempting to parse the reason
* or details fields. For example:
*
* ```
* // on the server, pick a code unique to this error
* // the reason field should be a useful debug message
* throw new Meteor.Error("logged-out",
* "The user must be logged in to post a comment.");
*
* // on the client
* Meteor.call("methodName", function (error) {
* // identify the error
* if (error.error === "logged-out") {
* // show a nice error message
* Session.set("errorMessage", "Please log in to post a comment.");
* }
* });
* ```
*
* For legacy reasons, some built-in Meteor functions such as `check` throw
* errors with a number in this field.
*
* @param {String} [reason] Optional. A short human-readable summary of the
* error, like 'Not Found'.
* @param {String} [details] Optional. Additional information about the error,
* like a textual stack trace.
*/
Meteor.Error = Meteor.makeErrorType("Meteor.Error", function(error, reason, details) {
var self = this;
// Currently, a numeric code, likely similar to a HTTP code (eg,
// 404, 500). That is likely to change though.
self.error = error;
// Optional: A short human-readable summary of the error. Not
// intended to be shown to end users, just developers. ("Not Found",
// "Internal Server Error")
self.reason = reason;
// Optional: Additional information about the error, say for
// debugging. It might be a (textual) stack trace if the server is
// willing to provide one. The corresponding thing in HTTP would be
// the body of a 404 or 500 response. (The difference is that we
// never expect this to be shown to end users, only developers, so
// it doesn't need to be pretty.)
self.details = details;
// This is what gets displayed at the top of a stack trace. Current
// format is "[404]" (if no reason is set) or "File not found [404]"
if (self.reason) self.message = self.reason + " [" + self.error + "]"; else self.message = "[" + self.error + "]";
});
// Meteor.Error is basically data and is sent over DDP, so you should be able to
// properly EJSON-clone it. This is especially important because if a
// Meteor.Error is thrown through a Future, the error, reason, and details
// properties become non-enumerable so a standard Object clone won't preserve
// them and they will be lost from DDP.
Meteor.Error.prototype.clone = function() {
var self = this;
return new Meteor.Error(self.error, self.reason, self.details);
};
// This file is a partial analogue to fiber_helpers.js, which allows the client
// to use a queue too, and also to call noYieldsAllowed.
// The client has no ability to yield, so noYieldsAllowed is a noop.
//
Meteor._noYieldsAllowed = function(f) {
return f();
};
// An even simpler queue of tasks than the fiber-enabled one. This one just
// runs all the tasks when you call runTask or flush, synchronously.
//
Meteor._SynchronousQueue = function() {
var self = this;
self._tasks = [];
self._running = false;
self._runTimeout = null;
};
_.extend(Meteor._SynchronousQueue.prototype, {
runTask: function(task) {
var self = this;
if (!self.safeToRunTask()) throw new Error("Could not synchronously run a task from a running task");
self._tasks.push(task);
var tasks = self._tasks;
self._tasks = [];
self._running = true;
if (self._runTimeout) {
// Since we're going to drain the queue, we can forget about the timeout
// which tries to run it. (But if one of our tasks queues something else,
// the timeout will be correctly re-created.)
clearTimeout(self._runTimeout);
self._runTimeout = null;
}
try {
while (!_.isEmpty(tasks)) {
var t = tasks.shift();
try {
t();
} catch (e) {
if (_.isEmpty(tasks)) {
// this was the last task, that is, the one we're calling runTask
// for.
throw e;
} else {
Meteor._debug("Exception in queued task: " + e.stack);
}
}
}
} finally {
self._running = false;
}
},
queueTask: function(task) {
var self = this;
self._tasks.push(task);
// Intentionally not using Meteor.setTimeout, because it doesn't like runing
// in stubs for now.
if (!self._runTimeout) {
self._runTimeout = setTimeout(_.bind(self.flush, self), 0);
}
},
flush: function() {
var self = this;
self.runTask(function() {});
},
drain: function() {
var self = this;
if (!self.safeToRunTask()) return;
while (!_.isEmpty(self._tasks)) {
self.flush();
}
},
safeToRunTask: function() {
var self = this;
return !self._running;
}
});
var suppress = 0;
// replacement for console.log. This is a temporary API. We should
// provide a real logging API soon (possibly just a polyfill for
// console?)
//
// NOTE: this is used on the server to print the warning about
// having autopublish enabled when you probably meant to turn it
// off. it's not really the proper use of something called
// _debug. the intent is for this message to go to the terminal and
// be very visible. if you change _debug to go someplace else, etc,
// please fix the autopublish code to do something reasonable.
//
Meteor._debug = function() {
if (suppress) {
suppress--;
return;
}
if (typeof console !== "undefined" && typeof console.log !== "undefined") {
if (arguments.length == 0) {
// IE Companion breaks otherwise
// IE10 PP4 requires at least one argument
console.log("");
} else {
// IE doesn't have console.log.apply, it's not a real Object.
// http://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9
// http://patik.com/blog/complete-cross-browser-console-log/
if (typeof console.log.apply === "function") {
// Most browsers
// Chrome and Safari only hyperlink URLs to source files in first argument of
// console.log, so try to call it with one argument if possible.
// Approach taken here: If all arguments are strings, join them on space.
// See https://github.com/meteor/meteor/pull/732#issuecomment-13975991
var allArgumentsOfTypeString = true;
for (var i = 0; i < arguments.length; i++) if (typeof arguments[i] !== "string") allArgumentsOfTypeString = false;
if (allArgumentsOfTypeString) console.log.apply(console, [ Array.prototype.join.call(arguments, " ") ]); else console.log.apply(console, arguments);
} else if (typeof Function.prototype.bind === "function") {
// IE9
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
} else {
// IE8
Function.prototype.call.call(console.log, console, Array.prototype.slice.call(arguments));
}
}
}
};
// Suppress the next 'count' Meteor._debug messsages. Use this to
// stop tests from spamming the console.
//
Meteor._suppress_log = function(count) {
suppress += count;
};
Meteor._supressed_log_expected = function() {
return suppress !== 0;
};
// Base 64 encoding
var BASE_64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var BASE_64_VALS = {};
for (var i = 0; i < BASE_64_CHARS.length; i++) {
BASE_64_VALS[BASE_64_CHARS.charAt(i)] = i;
}
Base64 = {};
Base64.encode = function(array) {
if (typeof array === "string") {
var str = array;
array = Base64.newBinary(str.length);
for (var i = 0; i < str.length; i++) {
var ch = str.charCodeAt(i);
if (ch > 255) {
throw new Error("Not ascii. Base64.encode can only take ascii strings.");
}
array[i] = ch;
}
}
var answer = [];
var a = null;
var b = null;
var c = null;
var d = null;
for (var i = 0; i < array.length; i++) {
switch (i % 3) {
case 0:
a = array[i] >> 2 & 63;
b = (array[i] & 3) << 4;
break;
case 1:
b = b | array[i] >> 4 & 15;
c = (array[i] & 15) << 2;
break;
case 2:
c = c | array[i] >> 6 & 3;
d = array[i] & 63;
answer.push(getChar(a));
answer.push(getChar(b));
answer.push(getChar(c));
answer.push(getChar(d));
a = null;
b = null;
c = null;
d = null;
break;
}
}
if (a != null) {
answer.push(getChar(a));
answer.push(getChar(b));
if (c == null) answer.push("="); else answer.push(getChar(c));
if (d == null) answer.push("=");
}
return answer.join("");
};
var getChar = function(val) {
return BASE_64_CHARS.charAt(val);
};
var getVal = function(ch) {
if (ch === "=") {
return -1;
}
return BASE_64_VALS[ch];
};
// XXX This is a weird place for this to live, but it's used both by
// this package and 'ejson', and we can't put it in 'ejson' without
// introducing a circular dependency. It should probably be in its own
// package or as a helper in a package that both 'base64' and 'ejson'
// use.
Base64.newBinary = function(len) {
if (typeof Uint8Array === "undefined" || typeof ArrayBuffer === "undefined") {
var ret = [];
for (var i = 0; i < len; i++) {
ret.push(0);
}
ret.$Uint8ArrayPolyfill = true;
return ret;
}
return new Uint8Array(new ArrayBuffer(len));
};
Base64.decode = function(str) {
var len = Math.floor(str.length * 3 / 4);
if (str.charAt(str.length - 1) == "=") {
len--;
if (str.charAt(str.length - 2) == "=") len--;
}
var arr = Base64.newBinary(len);
var one = null;
var two = null;
var three = null;
var j = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
var v = getVal(c);
switch (i % 4) {
case 0:
if (v < 0) throw new Error("invalid base64 string");
one = v << 2;
break;
case 1:
if (v < 0) throw new Error("invalid base64 string");
one = one | v >> 4;
arr[j++] = one;
two = (v & 15) << 4;
break;
case 2:
if (v >= 0) {
two = two | v >> 2;
arr[j++] = two;
three = (v & 3) << 6;
}
break;
case 3:
if (v >= 0) {
arr[j++] = three | v;
}
break;
}
}
return arr;
};
/**
* @namespace
* @summary Namespace for EJSON functions
*/
EJSON = {};
EJSONTest = {};
// Custom type interface definition
/**
* @class CustomType
* @instanceName customType
* @memberOf EJSON
* @summary The interface that a class must satisfy to be able to become an
* EJSON custom type via EJSON.addType.
*/
/**
* @function typeName
* @memberOf EJSON.CustomType
* @summary Return the tag used to identify this type. This must match the tag used to register this type with [`EJSON.addType`](#ejson_add_type).
* @locus Anywhere
* @instance
*/
/**
* @function toJSONValue
* @memberOf EJSON.CustomType
* @summary Serialize this instance into a JSON-compatible value.
* @locus Anywhere
* @instance
*/
/**
* @function clone
* @memberOf EJSON.CustomType
* @summary Return a value `r` such that `this.equals(r)` is true, and modifications to `r` do not affect `this` and vice versa.
* @locus Anywhere
* @instance
*/
/**
* @function equals
* @memberOf EJSON.CustomType
* @summary Return `true` if `other` has a value equal to `this`; `false` otherwise.
* @locus Anywhere
* @param {Object} other Another object to compare this to.
* @instance
*/
var customTypes = {};
// Add a custom type, using a method of your choice to get to and
// from a basic JSON-able representation. The factory argument
// is a function of JSON-able --> your object
// The type you add must have:
// - A toJSONValue() method, so that Meteor can serialize it
// - a typeName() method, to show how to look it up in our type table.
// It is okay if these methods are monkey-patched on.
// EJSON.clone will use toJSONValue and the given factory to produce
// a clone, but you may specify a method clone() that will be
// used instead.
// Similarly, EJSON.equals will use toJSONValue to make comparisons,
// but you may provide a method equals() instead.
/**
* @summary Add a custom datatype to EJSON.
* @locus Anywhere
* @param {String} name A tag for your custom type; must be unique among custom data types defined in your project, and must match the result of your type's `typeName` method.
* @param {Function} factory A function that deserializes a JSON-compatible value into an instance of your type. This should match the serialization performed by your type's `toJSONValue` method.
*/
EJSON.addType = function(name, factory) {
if (_.has(customTypes, name)) throw new Error("Type " + name + " already present");
customTypes[name] = factory;
};
var isInfOrNan = function(obj) {
return _.isNaN(obj) || obj === Infinity || obj === -Infinity;
};
var builtinConverters = [ {
// Date
matchJSONValue: function(obj) {
return _.has(obj, "$date") && _.size(obj) === 1;
},
matchObject: function(obj) {
return obj instanceof Date;
},
toJSONValue: function(obj) {
return {
$date: obj.getTime()
};
},
fromJSONValue: function(obj) {
return new Date(obj.$date);
}
}, {
// NaN, Inf, -Inf. (These are the only objects with typeof !== 'object'
// which we match.)
matchJSONValue: function(obj) {
return _.has(obj, "$InfNaN") && _.size(obj) === 1;
},
matchObject: isInfOrNan,
toJSONValue: function(obj) {
var sign;
if (_.isNaN(obj)) sign = 0; else if (obj === Infinity) sign = 1; else sign = -1;
return {
$InfNaN: sign
};
},
fromJSONValue: function(obj) {
return obj.$InfNaN / 0;
}
}, {
// Binary
matchJSONValue: function(obj) {
return _.has(obj, "$binary") && _.size(obj) === 1;
},
matchObject: function(obj) {
return typeof Uint8Array !== "undefined" && obj instanceof Uint8Array || obj && _.has(obj, "$Uint8ArrayPolyfill");
},
toJSONValue: function(obj) {
return {
$binary: Base64.encode(obj)
};
},
fromJSONValue: function(obj) {
return Base64.decode(obj.$binary);
}
}, {
// Escaping one level
matchJSONValue: function(obj) {
return _.has(obj, "$escape") && _.size(obj) === 1;
},
matchObject: function(obj) {
if (_.isEmpty(obj) || _.size(obj) > 2) {
return false;
}
return _.any(builtinConverters, function(converter) {
return converter.matchJSONValue(obj);
});
},
toJSONValue: function(obj) {
var newObj = {};
_.each(obj, function(value, key) {
newObj[key] = EJSON.toJSONValue(value);
});
return {
$escape: newObj
};
},
fromJSONValue: function(obj) {
var newObj = {};
_.each(obj.$escape, function(value, key) {
newObj[key] = EJSON.fromJSONValue(value);
});
return newObj;
}
}, {
// Custom
matchJSONValue: function(obj) {
return _.has(obj, "$type") && _.has(obj, "$value") && _.size(obj) === 2;
},
matchObject: function(obj) {
return EJSON._isCustomType(obj);
},
toJSONValue: function(obj) {
var jsonValue = Meteor._noYieldsAllowed(function() {
return obj.toJSONValue();
});
return {
$type: obj.typeName(),
$value: jsonValue
};
},
fromJSONValue: function(obj) {
var typeName = obj.$type;
if (!_.has(customTypes, typeName)) throw new Error("Custom EJSON type " + typeName + " is not defined");
var converter = customTypes[typeName];
return Meteor._noYieldsAllowed(function() {
return converter(obj.$value);
});
}
} ];
EJSON._isCustomType = function(obj) {
return obj && typeof obj.toJSONValue === "function" && typeof obj.typeName === "function" && _.has(customTypes, obj.typeName());
};
// for both arrays and objects, in-place modification.
var adjustTypesToJSONValue = EJSON._adjustTypesToJSONValue = function(obj) {
// Is it an atom that we need to adjust?
if (obj === null) return null;
var maybeChanged = toJSONValueHelper(obj);
if (maybeChanged !== undefined) return maybeChanged;
// Other atoms are unchanged.
if (typeof obj !== "object") return obj;
// Iterate over array or object structure.
_.each(obj, function(value, key) {
if (typeof value !== "object" && value !== undefined && !isInfOrNan(value)) return;
// continue
var changed = toJSONValueHelper(value);
if (changed) {
obj[key] = changed;
return;
}
// if we get here, value is an object but not adjustable
// at this level. recurse.
adjustTypesToJSONValue(value);
});
return obj;
};
// Either return the JSON-compatible version of the argument, or undefined (if
// the item isn't itself replaceable, but maybe some fields in it are)
var toJSONValueHelper = function(item) {
for (var i = 0; i < builtinConverters.length; i++) {
var converter = builtinConverters[i];
if (converter.matchObject(item)) {
return converter.toJSONValue(item);
}
}
return undefined;
};
/**
* @summary Serialize an EJSON-compatible value into its plain JSON representation.
* @locus Anywhere
* @param {EJSON} val A value to serialize to plain JSON.
*/
EJSON.toJSONValue = function(item) {
var changed = toJSONValueHelper(item);
if (changed !== undefined) return changed;
if (typeof item === "object") {
item = EJSON.clone(item);
adjustTypesToJSONValue(item);
}
return item;
};
// for both arrays and objects. Tries its best to just
// use the object you hand it, but may return something
// different if the object you hand it itself needs changing.
//
var adjustTypesFromJSONValue = EJSON._adjustTypesFromJSONValue = function(obj) {
if (obj === null) return null;
var maybeChanged = fromJSONValueHelper(obj);
if (maybeChanged !== obj) return maybeChanged;
// Other atoms are unchanged.
if (typeof obj !== "object") return obj;
_.each(obj, function(value, key) {
if (typeof value === "object") {
var changed = fromJSONValueHelper(value);
if (value !== changed) {
obj[key] = changed;
return;
}
// if we get here, value is an object but not adjustable
// at this level. recurse.
adjustTypesFromJSONValue(value);
}
});
return obj;
};
// Either return the argument changed to have the non-json
// rep of itself (the Object version) or the argument itself.
// DOES NOT RECURSE. For actually getting the fully-changed value, use
// EJSON.fromJSONValue
var fromJSONValueHelper = function(value) {
if (typeof value === "object" && value !== null) {
if (_.size(value) <= 2 && _.all(value, function(v, k) {
return typeof k === "string" && k.substr(0, 1) === "$";
})) {
for (var i = 0; i < builtinConverters.length; i++) {
var converter = builtinConverters[i];
if (converter.matchJSONValue(value)) {
return converter.fromJSONValue(value);
}
}
}
}
return value;
};
/**
* @summary Deserialize an EJSON value from its plain JSON representation.
* @locus Anywhere
* @param {JSONCompatible} val A value to deserialize into EJSON.
*/
EJSON.fromJSONValue = function(item) {
var changed = fromJSONValueHelper(item);
if (changed === item && typeof item === "object") {
item = EJSON.clone(item);
adjustTypesFromJSONValue(item);
return item;
} else {
return changed;
}
};
/**
* @summary Serialize a value to a string.
For EJSON values, the serialization fully represents the value. For non-EJSON values, serializes the same way as `JSON.stringify`.
* @locus Anywhere
* @param {EJSON} val A value to stringify.
* @param {Object} [options]
* @param {Boolean | Integer | String} options.indent Indents objects and arrays for easy readability. When `true`, indents by 2 spaces; when an integer, indents by that number of spaces; and when a string, uses the string as the indentation pattern.
* @param {Boolean} options.canonical When `true`, stringifies keys in an object in sorted order.
*/
EJSON.stringify = function(item, options) {
var json = EJSON.toJSONValue(item);
if (options && (options.canonical || options.indent)) {
return EJSON._canonicalStringify(json, options);
} else {
return JSON.stringify(json);
}
};
/**
* @summary Parse a string into an EJSON value. Throws an error if the string is not valid EJSON.
* @locus Anywhere
* @param {String} str A string to parse into an EJSON value.
*/