mongodb-stitch
Version:
[](https://gitter.im/mongodb/stitch?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
1,751 lines (1,437 loc) • 450 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("stitch", [], factory);
else if(typeof exports === 'object')
exports["stitch"] = factory();
else
root["stitch"] = factory();
})(this, function() {
return /******/ (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;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // 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 = 15);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.uriEncodeObject = exports.serviceResponse = undefined;
var _Base = __webpack_require__(12);
var base64 = _interopRequireWildcard(_Base);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* @namespace util
* @private
*/
/**
* Utility method for executing a service action as a function call.
*
* @memberof util
* @param {Object} service the service to execute the action on
* @param {String} action the service action to execute
* @param {Array} args the arguments to supply to the service action invocation
* @returns {Promise} the API response from the executed service action
*/
function serviceResponse(service, _ref) {
var _ref$serviceName = _ref.serviceName,
serviceName = _ref$serviceName === undefined ? service.serviceName : _ref$serviceName,
action = _ref.action,
args = _ref.args;
var client = service.client;
if (!client) {
throw new Error('Service has no client');
}
return client.executeServiceFunction(serviceName, action, args);
}
/**
* Utility function to encode a JSON object into a valid string that can be
* inserted in a URI. The object is first stringified, then encoded in base64,
* and finally encoded via the builtin encodeURIComponent function.
*
* @memberof util
* @param {Object} obj The object to encode
* @returns {String} The encoded object
*/
function uriEncodeObject(obj) {
return encodeURIComponent(base64.btoa(JSON.stringify(obj)));
}
exports.serviceResponse = serviceResponse;
exports.uriEncodeObject = uriEncodeObject;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var USER_AUTH_KEY = exports.USER_AUTH_KEY = '_baas_ua';
var REFRESH_TOKEN_KEY = exports.REFRESH_TOKEN_KEY = '_baas_rt';
var DEVICE_ID_KEY = exports.DEVICE_ID_KEY = '_baas_did';
var STATE_KEY = exports.STATE_KEY = '_baas_state';
var USER_AUTH_COOKIE_NAME = exports.USER_AUTH_COOKIE_NAME = 'baas_ua';
var STITCH_ERROR_KEY = exports.STITCH_ERROR_KEY = '_baas_error';
var STITCH_LINK_KEY = exports.STITCH_LINK_KEY = '_baas_link';
var USER_LOGGED_IN_PT_KEY = exports.USER_LOGGED_IN_PT_KEY = '_baas_pt';
var STITCH_REDIRECT_PROVIDER = exports.STITCH_REDIRECT_PROVIDER = '_baas_rp';
var DEFAULT_ACCESS_TOKEN_EXPIRE_WITHIN_SECS = exports.DEFAULT_ACCESS_TOKEN_EXPIRE_WITHIN_SECS = 10;
var APP_CLIENT_CODEC = exports.APP_CLIENT_CODEC = {
'accessToken': 'access_token',
'refreshToken': 'refresh_token',
'deviceId': 'device_id',
'userId': 'user_id'
};
var ADMIN_CLIENT_CODEC = exports.ADMIN_CLIENT_CODEC = {
'accessToken': 'access_token',
'refreshToken': 'refresh_token',
'deviceId': 'device_id',
'userId': 'user_id'
};
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.makeFetchArgs = exports.checkStatus = exports.SDK_VERSION = exports.DEFAULT_STITCH_SERVER_URL = exports.ADMIN_CLIENT_TYPE = exports.APP_CLIENT_TYPE = exports.JSONTYPE = undefined;
var _errors = __webpack_require__(3);
var JSONTYPE = exports.JSONTYPE = 'application/json';
var APP_CLIENT_TYPE = exports.APP_CLIENT_TYPE = 'app';
var ADMIN_CLIENT_TYPE = exports.ADMIN_CLIENT_TYPE = 'admin';
var DEFAULT_STITCH_SERVER_URL = exports.DEFAULT_STITCH_SERVER_URL = 'https://realm.mongodb.com';
// VERSION is substituted with the package.json version number at build time
var version = 'unknown';
if (true) {
version = "3.18.0";
}
var SDK_VERSION = exports.SDK_VERSION = version;
var checkStatus = exports.checkStatus = function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
if (response.headers.get('Content-Type') === JSONTYPE) {
return response.json().then(function (json) {
var error = new _errors.StitchError(json.error, json.error_code);
error.response = response;
error.json = json;
return Promise.reject(error);
});
}
var error = new Error(response.statusText);
error.response = response;
return Promise.reject(error);
};
var makeFetchArgs = exports.makeFetchArgs = function makeFetchArgs(method, body, options) {
var init = {
method: method,
headers: { 'Accept': JSONTYPE, 'Content-Type': JSONTYPE }
};
if (options && options.credentials) {
init.credentials = options.credentials;
}
if (body) {
init.body = body;
}
init.cors = true;
return init;
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _Error = function _Error(message, code) {
Error.call(this, message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
}
this.message = message;
this.name = this.constructor.name;
if (code !== undefined) {
this.code = code;
}
};
_Error.prototype = Object.create(Error.prototype);
var StitchError = function (_Error2) {
_inherits(StitchError, _Error2);
function StitchError() {
_classCallCheck(this, StitchError);
return _possibleConstructorReturn(this, (StitchError.__proto__ || Object.getPrototypeOf(StitchError)).apply(this, arguments));
}
return StitchError;
}(_Error);
var ErrAuthProviderNotFound = 'AuthProviderNotFound';
var ErrInvalidSession = 'InvalidSession';
var ErrUnauthorized = 'Unauthorized';
exports.StitchError = StitchError;
exports.ErrAuthProviderNotFound = ErrAuthProviderNotFound;
exports.ErrInvalidSession = ErrInvalidSession;
exports.ErrUnauthorized = ErrUnauthorized;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EJSON = exports.ObjectID = exports.setInternalBufferSize = exports.deserializeStream = exports.calculateObjectSize = exports.deserialize = exports.serializeWithBufferAndIndex = exports.serialize = exports.Decimal128 = exports.BSONRegExp = exports.MaxKey = exports.MinKey = exports.Int32 = exports.Double = exports.Timestamp = exports.Long = exports.ObjectId = exports.Binary = exports.DBRef = exports.BSONSymbol = exports.Code = exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_LONG = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_INT = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_CODE = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_REGEXP = exports.BSON_DATA_NULL = exports.BSON_DATA_DATE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_OID = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_DATA_OBJECT = exports.BSON_DATA_STRING = exports.BSON_DATA_NUMBER = exports.JS_INT_MIN = exports.JS_INT_MAX = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = undefined;
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _long2 = __webpack_require__(34);
var _long3 = _interopRequireDefault(_long2);
var _buffer2 = __webpack_require__(8);
var _buffer3 = _interopRequireDefault(_buffer2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var map = createCommonjsModule(function (module) {
if (typeof commonjsGlobal.Map !== 'undefined') {
module.exports = commonjsGlobal.Map;
module.exports.Map = commonjsGlobal.Map;
} else {
// We will return a polyfill
var Map = function Map(array) {
this._keys = [];
this._values = {};
for (var i = 0; i < array.length; i++) {
if (array[i] == null) continue; // skip null and undefined
var entry = array[i];
var key = entry[0];
var value = entry[1]; // Add the key to the list of keys in order
this._keys.push(key); // Add the key and value to the values dictionary with a point
// to the location in the ordered keys list
this._values[key] = {
v: value,
i: this._keys.length - 1
};
}
};
Map.prototype.clear = function () {
this._keys = [];
this._values = {};
};
Map.prototype["delete"] = function (key) {
var value = this._values[key];
if (value == null) return false; // Delete entry
delete this._values[key]; // Remove the key from the ordered keys list
this._keys.splice(value.i, 1);
return true;
};
Map.prototype.entries = function () {
var self = this;
var index = 0;
return {
next: function next() {
var key = self._keys[index++];
return {
value: key !== undefined ? [key, self._values[key].v] : undefined,
done: key !== undefined ? false : true
};
}
};
};
Map.prototype.forEach = function (callback, self) {
self = self || this;
for (var i = 0; i < this._keys.length; i++) {
var key = this._keys[i]; // Call the forEach callback
callback.call(self, this._values[key].v, key, self);
}
};
Map.prototype.get = function (key) {
return this._values[key] ? this._values[key].v : undefined;
};
Map.prototype.has = function (key) {
return this._values[key] != null;
};
Map.prototype.keys = function () {
var self = this;
var index = 0;
return {
next: function next() {
var key = self._keys[index++];
return {
value: key !== undefined ? key : undefined,
done: key !== undefined ? false : true
};
}
};
};
Map.prototype.set = function (key, value) {
if (this._values[key]) {
this._values[key].v = value;
return this;
} // Add the key to the list of keys in order
this._keys.push(key); // Add the key and value to the values dictionary with a point
// to the location in the ordered keys list
this._values[key] = {
v: value,
i: this._keys.length - 1
};
return this;
};
Map.prototype.values = function () {
var self = this;
var index = 0;
return {
next: function next() {
var key = self._keys[index++];
return {
value: key !== undefined ? self._values[key].v : undefined,
done: key !== undefined ? false : true
};
}
};
}; // Last ismaster
Object.defineProperty(Map.prototype, 'size', {
enumerable: true,
get: function get() {
return this._keys.length;
}
});
module.exports = Map;
}
});
var map_1 = map.Map;
/**
* @ignore
*/
_long3.default.prototype.toExtendedJSON = function (options) {
if (options && options.relaxed) return this.toNumber();
return {
$numberLong: this.toString()
};
};
/**
* @ignore
*/
_long3.default.fromExtendedJSON = function (doc, options) {
var result = _long3.default.fromString(doc.$numberLong);
return options && options.relaxed ? result.toNumber() : result;
};
Object.defineProperty(_long3.default.prototype, '_bsontype', {
value: 'Long'
});
var long_1 = _long3.default;
/**
* A class representation of the BSON Double type.
*/
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);if (staticProps) _defineProperties(Constructor, staticProps);return Constructor;
}
var Double =
/*#__PURE__*/
function () {
/**
* Create a Double type
*
* @param {number|Number} value the number we want to represent as a double.
* @return {Double}
*/
function Double(value) {
_classCallCheck(this, Double);
if (value instanceof Number) {
value = value.valueOf();
}
this.value = value;
}
/**
* Access the number value.
*
* @method
* @return {number} returns the wrapped double number.
*/
_createClass(Double, [{
key: "valueOf",
value: function valueOf() {
return this.value;
}
/**
* @ignore
*/
}, {
key: "toJSON",
value: function toJSON() {
return this.value;
}
/**
* @ignore
*/
}, {
key: "toExtendedJSON",
value: function toExtendedJSON(options) {
if (options && (options.legacy || options.relaxed && isFinite(this.value))) {
return this.value;
} // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
// explicitly provided `-0` then we need to ensure the sign makes it into the output
if (Object.is(Math.sign(this.value), -0)) {
return {
$numberDouble: "-".concat(this.value.toFixed(1))
};
}
return {
$numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
};
}
/**
* @ignore
*/
}], [{
key: "fromExtendedJSON",
value: function fromExtendedJSON(doc, options) {
var doubleValue = parseFloat(doc.$numberDouble);
return options && options.relaxed ? doubleValue : new Double(doubleValue);
}
}]);
return Double;
}();
Object.defineProperty(Double.prototype, '_bsontype', {
value: 'Double'
});
var double_1 = Double;
function _typeof(obj) {
if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
};
}return _typeof(obj);
}
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties$1(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass$1(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);if (staticProps) _defineProperties$1(Constructor, staticProps);return Constructor;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return self;
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};return _getPrototypeOf(o);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;return o;
};return _setPrototypeOf(o, p);
}
/**
* @class
* @param {number} low the low (signed) 32 bits of the Timestamp.
* @param {number} high the high (signed) 32 bits of the Timestamp.
* @return {Timestamp}
*/
var Timestamp =
/*#__PURE__*/
function (_Long) {
_inherits(Timestamp, _Long);
function Timestamp(low, high) {
var _this;
_classCallCheck$1(this, Timestamp);
if (long_1.isLong(low)) {
_this = _possibleConstructorReturn(this, _getPrototypeOf(Timestamp).call(this, low.low, low.high, true));
} else {
_this = _possibleConstructorReturn(this, _getPrototypeOf(Timestamp).call(this, low, high, true));
}
return _possibleConstructorReturn(_this);
}
/**
* Return the JSON value.
*
* @method
* @return {String} the JSON representation.
*/
_createClass$1(Timestamp, [{
key: "toJSON",
value: function toJSON() {
return {
$timestamp: this.toString()
};
}
/**
* Returns a Timestamp represented by the given (32-bit) integer value.
*
* @method
* @param {number} value the 32-bit integer in question.
* @return {Timestamp} the timestamp.
*/
}, {
key: "toExtendedJSON",
/**
* @ignore
*/
value: function toExtendedJSON() {
return {
$timestamp: {
t: this.high >>> 0,
i: this.low >>> 0
}
};
}
/**
* @ignore
*/
}], [{
key: "fromInt",
value: function fromInt(value) {
return new Timestamp(long_1.fromInt(value, true));
}
/**
* Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned.
*
* @method
* @param {number} value the number in question.
* @return {Timestamp} the timestamp.
*/
}, {
key: "fromNumber",
value: function fromNumber(value) {
return new Timestamp(long_1.fromNumber(value, true));
}
/**
* Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
*
* @method
* @param {number} lowBits the low 32-bits.
* @param {number} highBits the high 32-bits.
* @return {Timestamp} the timestamp.
*/
}, {
key: "fromBits",
value: function fromBits(lowBits, highBits) {
return new Timestamp(lowBits, highBits);
}
/**
* Returns a Timestamp from the given string, optionally using the given radix.
*
* @method
* @param {String} str the textual representation of the Timestamp.
* @param {number} [opt_radix] the radix in which the text is written.
* @return {Timestamp} the timestamp.
*/
}, {
key: "fromString",
value: function fromString(str, opt_radix) {
return new Timestamp(long_1.fromString(str, opt_radix, true));
}
}, {
key: "fromExtendedJSON",
value: function fromExtendedJSON(doc) {
return new Timestamp(doc.$timestamp.i, doc.$timestamp.t);
}
}]);
return Timestamp;
}(long_1);
Object.defineProperty(Timestamp.prototype, '_bsontype', {
value: 'Timestamp'
});
Timestamp.MAX_VALUE = Timestamp.MAX_UNSIGNED_VALUE;
var timestamp = Timestamp;
var require$$0 = {};
/* global window */
/**
* Normalizes our expected stringified form of a function across versions of node
* @param {Function} fn The function to stringify
*/
function normalizedFunctionString(fn) {
return fn.toString().replace('function(', 'function (');
}
function insecureRandomBytes(size) {
var result = new Uint8Array(size);
for (var i = 0; i < size; ++i) {
result[i] = Math.floor(Math.random() * 256);
}
return result;
}
var randomBytes = insecureRandomBytes;
if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
randomBytes = function randomBytes(size) {
return window.crypto.getRandomValues(new Uint8Array(size));
};
} else {
try {
randomBytes = require$$0.randomBytes;
} catch (e) {} // keep the fallback
// NOTE: in transpiled cases the above require might return null/undefined
if (randomBytes == null) {
randomBytes = insecureRandomBytes;
}
}
var utils = {
normalizedFunctionString: normalizedFunctionString,
randomBytes: randomBytes
};
// shim for using process in browser
// based off https://github.com/defunctzombie/node-process/blob/master/browser.js
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
var cachedSetTimeout = defaultSetTimout;
var cachedClearTimeout = defaultClearTimeout;
if (typeof global.setTimeout === 'function') {
cachedSetTimeout = setTimeout;
}
if (typeof global.clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
}
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
} // if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
} // if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
function nextTick(fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
} // v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
var title = 'browser';
var platform = 'browser';
var browser = true;
var env = {};
var argv = [];
var version = ''; // empty string to avoid regexp issues
var versions = {};
var release = {};
var config = {};
function noop() {}
var on = noop;
var addListener = noop;
var once = noop;
var off = noop;
var removeListener = noop;
var removeAllListeners = noop;
var emit = noop;
function binding(name) {
throw new Error('process.binding is not supported');
}
function cwd() {
return '/';
}
function chdir(dir) {
throw new Error('process.chdir is not supported');
}
function umask() {
return 0;
} // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
var performance = global.performance || {};
var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
return new Date().getTime();
}; // generate timestamp or delta
// see http://nodejs.org/api/process.html#process_process_hrtime
function hrtime(previousTimestamp) {
var clocktime = performanceNow.call(performance) * 1e-3;
var seconds = Math.floor(clocktime);
var nanoseconds = Math.floor(clocktime % 1 * 1e9);
if (previousTimestamp) {
seconds = seconds - previousTimestamp[0];
nanoseconds = nanoseconds - previousTimestamp[1];
if (nanoseconds < 0) {
seconds--;
nanoseconds += 1e9;
}
}
return [seconds, nanoseconds];
}
var startTime = new Date();
function uptime() {
var currentTime = new Date();
var dif = currentTime - startTime;
return dif / 1000;
}
var process = {
nextTick: nextTick,
title: title,
browser: browser,
env: env,
argv: argv,
version: version,
versions: versions,
on: on,
addListener: addListener,
once: once,
off: off,
removeListener: removeListener,
removeAllListeners: removeAllListeners,
emit: emit,
binding: binding,
cwd: cwd,
chdir: chdir,
umask: umask,
hrtime: hrtime,
platform: platform,
release: release,
config: config,
uptime: uptime
};
var inherits;
if (typeof Object.create === 'function') {
inherits = function inherits(ctor, superCtor) {
// implementation from standard node.js 'util' module
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
inherits = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function TempCtor() {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
};
}
var inherits$1 = inherits;
function _typeof$1(obj) {
if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
_typeof$1 = function _typeof(obj) {
return typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
};
} else {
_typeof$1 = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
};
}return _typeof$1(obj);
}
var formatRegExp = /%[sdj%]/g;
function format(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function (x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s':
return String(args[i++]);
case '%d':
return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
}
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
function deprecate(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function () {
return deprecate(fn, msg).apply(this, arguments);
};
}
var warned = false;
function deprecated() {
if (!warned) {
{
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
var debugs = {};
var debugEnviron;
function debuglog(set) {
if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = 0;
debugs[set] = function () {
var msg = format.apply(null, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function () {};
}
}
return debugs[set];
}
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
}; // legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
_extend(ctx, opts);
} // set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
} // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold': [1, 22],
'italic': [3, 23],
'underline': [4, 24],
'inverse': [7, 27],
'white': [37, 39],
'grey': [90, 39],
'black': [30, 39],
'blue': [34, 39],
'cyan': [36, 39],
'green': [32, 39],
'magenta': [35, 39],
'red': [31, 39],
'yellow': [33, 39]
}; // Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function (val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special
value.inspect !== inspect && // Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
} // Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
} // Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
} // IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
} // Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '',
array = false,
braces = ['{', '}']; // Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
} // Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
} // Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
} // Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
} // Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function (key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value)) return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value)) return ctx.stylize('' + value, 'number');
if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here.
if (isNull(value)) return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
} else {
output.push('');
}
}
keys.forEach(function (key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || {
value: value[key]
};
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function (line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function (line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var length = output.reduce(function (prev, cur) {
if (cur.indexOf('\n') >= 0) ;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
} // NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
function isBoolean(arg) {
return typeof arg === 'boolean';
}
function isNull(arg) {
return arg === null;
}
function isNullOrUndefined(arg) {
return arg == null;
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isString(arg) {
return typeof arg === 'string';
}
function isSymbol(arg) {
return _typeof$1(arg) === 'symbol';
}
function isUndefined(arg) {
return arg === void 0;
}
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
function isObject(arg) {
return _typeof$1(arg) === 'object' && arg !== null;
}
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
function isError(e) {
return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error);
}
function isFunction(arg) {
return typeof arg === 'function';
}
function isPrimitive(arg) {
return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || _typeof$1(arg) === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
function isBuffer(maybeBuf) {
return Buffer.isBuffer(maybeBuf);
}
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34
function timestamp$1() {
var d = new Date();
var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
} // log is just a thin wrapper to console.log that prepends a timestamp
function log() {
console.log('%s - %s', timestamp$1(), format.apply(null, arguments));
}
function _extend(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
var util = {
inherits: inherits$1,
_extend: _extend,
log: log,
isBuffer: isBuffer,
isPrimitive: isPrimitive,
isFunction: isFunction,
isError: isError,
isDate: isDate,
isObject: isObject,
isRegExp: isRegExp,
isUndefined: isUndefined,
isSymbol: isSymbol,
isString: isString,
isNumber: isNumber,
isNullOrUndefined: isNullOrUndefined,
isNull: isNull,
isBoolean: isBoolean,
isArray: isArray,
inspect: inspect,
deprecate: deprecate,
format: format,
debuglog: debuglog
};
function _classCallCheck$2(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties$2(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass$2(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties$2(Constructor.prototype, protoProps);if (staticProps) _defineProperties$2(Constructor, staticProps);return Constructor;
}
var Buffer$1 = _buffer3.default.Buffer;
var randomBytes$1 = utils.randomBytes;
var deprecate$1 = util.deprecate; // constants
var PROCESS_UNIQUE = randomBytes$1(5); // Regular expression that checks for hex value
var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
var hasBufferType = false; // Check if buffer exists
try {
if (Buffer$1 && Buffer$1.from) hasBufferType = true;
} catch (err) {
hasBufferType = false;
} // Precomputed hex table enables speedy hex string conversion
var hexTable = [];
for (var _i = 0; _i < 256; _i++) {
hexTable[_i] = (_i <= 15 ? '0' : '') + _i.toString(16);
} // Lookup tables
var decodeLookup = [];
var i = 0;
while (i < 10) {
decodeLookup[0x30 + i] = i++;
}
while (i < 16) {
decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;
}
var _Buffer = Buffer$1;
function convertToHex(bytes) {
return bytes.toString('hex');
}
function makeObjectIdError(invalidString, index) {
var invalidCharacter = invalidString[index];
return new TypeError("ObjectId string \"".concat(invalidString, "\" contains invalid character \"").concat(invalidCharacter, "\" with character code (").concat(invalidString.charCodeAt(index), "). All character codes for a non-hex string must be less than 256."));
}
/**
* A class representation of the BSON ObjectId type.
*/
var ObjectId =
/*#__PURE__*/
function () {
/**
* Create an ObjectId type
*
* @param {(string|Buffer|number)} id Can be a 24 byte hex string, 12 byte binary Buffer, or a Number.
* @property {number} generationTime The generation time of this ObjectId instance
* @return {ObjectId} instance of ObjectId.
*/
function ObjectId(id) {
_classCallCheck$2(this, ObjectId);
// Duck-typing to support ObjectId from different npm packages
if (id instanceof ObjectId) return id; // The most common usecase (blank id, new objectId instance)
if (id == null || typeof id === 'number') {
// Generate a new id
this.id = ObjectId.generate(id); // If we are caching the hex string
if (ObjectId.cacheHexString) this.__id = this.toString('hex'); // Return the object
return;
} // Check if the passed in id is valid
var valid = ObjectId.isValid(id); // Throw an error if it's not a valid setup
if (!valid && id != null) {
throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
} else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {
return new ObjectId(Buffer$1.from(id, 'hex'));
} else if (valid && typeof id === 'string' && id.length === 24) {
return ObjectId.createFromHexString(id);
} else if (id != null && id.length === 12) {
// assume 12 byte string
this.id = id;
} else if (id != null && id.toHexString) {
// Duck-typing to support ObjectId from different npm packages
return ObjectId.createFromHexString(id.toHexString());
} else {
throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
}
if (ObjectId.cacheHexString) this.__id = this.toString('hex');
}
/**
* Return the ObjectId id as a 24 byte hex string representation
*
* @method
* @return {string} return the 24 byte hex string representation.
*/
_createClass$2(ObjectId, [{
key: "toHexString",
value: function toHexString() {
if (ObjectId.cacheHexString && this.__id) return this.__id;
var hexString = '';
if (!this.id || !this.id.length) {
throw new TypeError('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']');
}
if (this.id instanceof _Buffer) {
hexString = convertToHex(this.id);
if (ObjectId.cacheHexString) this.__id = hexString;
return hexString;
}
for (var _i2 = 0; _i2 < th