(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 2 && arguments[2] !== undefined ? arguments[2] : {}; validators.validateAssetType(assetType); // If an empty array is given, explicitly set `none` to override API defaults var meta = opts.extract || undefined; if (meta && !meta.length) { meta = ['none']; } var dataset = validators.hasDataset(this.client.clientConfig); var assetEndpoint = assetType === 'image' ? 'images' : 'files'; var options = optionsFromFile(opts, body); var label = options.label, filename = options.filename; var query = { label: label, filename: filename, meta: meta }; var observable = this.client._requestObservable({ method: 'POST', timeout: options.timeout || 0, uri: "/assets/".concat(assetEndpoint, "/").concat(dataset), headers: options.contentType ? { 'Content-Type': options.contentType } : {}, query: query, body: body }); return this.client.isPromiseAPI() ? observable.pipe(filter(function (event) { return event.type === 'response'; }), map(function (event) { return toDocument(event.body); })).toPromise() : observable; }, delete: function _delete(type, id) { // eslint-disable-next-line no-console console.warn('client.assets.delete() is deprecated, please use client.delete()'); var docId = id || ''; if (!/^(image|file)-/.test(docId)) { docId = "".concat(type, "-").concat(docId); } else if (type._id) { // We could be passing an entire asset document instead of an ID docId = type._id; } validators.hasDataset(this.client.clientConfig); return this.client.delete(docId); }, getImageUrl: function getImageUrl(ref, query) { var id = ref._ref || ref; if (typeof id !== 'string') { throw new Error('getImageUrl() needs either an object with a _ref, or a string with an asset document ID'); } if (!/^image-[A-Za-z0-9_]+-\d+x\d+-[a-z]{1,5}$/.test(id)) { throw new Error("Unsupported asset ID \"".concat(id, "\". URL generation only works for auto-generated IDs.")); } var _id$split = id.split('-'), _id$split2 = _slicedToArray(_id$split, 4), assetId = _id$split2[1], size = _id$split2[2], format = _id$split2[3]; validators.hasDataset(this.client.clientConfig); var _this$client$clientCo = this.client.clientConfig, projectId = _this$client$clientCo.projectId, dataset = _this$client$clientCo.dataset; var qs = query ? queryString(query) : ''; return "https://cdn.sanity.io/images/".concat(projectId, "/").concat(dataset, "/").concat(assetId, "-").concat(size, ".").concat(format).concat(qs); } }); module.exports = AssetsClient; },{"../http/queryString":12,"../validators":22,"@sanity/observable/operators/filter":27,"@sanity/observable/operators/map":28,"object-assign":65}],2:[function(require,module,exports){ "use strict"; var assign = require('object-assign'); function AuthClient(client) { this.client = client; } assign(AuthClient.prototype, { getLoginProviders: function getLoginProviders() { return this.client.request({ uri: '/auth/providers' }); }, logout: function logout() { return this.client.request({ uri: '/auth/logout', method: 'POST' }); } }); module.exports = AuthClient; },{"object-assign":65}],3:[function(require,module,exports){ "use strict"; var generateHelpUrl = require('@sanity/generate-help-url'); var assign = require('object-assign'); var validate = require('./validators'); var once = require('./util/once'); var defaultCdnHost = 'apicdn.sanity.io'; var defaultConfig = { apiHost: 'https://api.sanity.io', useProjectHostname: true, gradientMode: false, isPromiseAPI: true }; var LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']; var isLocal = function isLocal(host) { return LOCALHOSTS.indexOf(host) !== -1; }; // eslint-disable-next-line no-console var createWarningPrinter = function createWarningPrinter(message) { return once(function () { return console.warn(message.join(' ')); }); }; var printCdnWarning = createWarningPrinter(['You are not using the Sanity CDN. That means your data is always fresh, but the CDN is faster and', "cheaper. Think about it! For more info, see ".concat(generateHelpUrl('js-client-cdn-configuration'), "."), 'To hide this warning, please set the `useCdn` option to either `true` or `false` when creating', 'the client.']); var printBrowserTokenWarning = createWarningPrinter(['You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.', "See ".concat(generateHelpUrl('js-client-browser-token'), " for more information and how to hide this warning.")]); var printCdnTokenWarning = createWarningPrinter(['You have set `useCdn` to `true` while also specifying a token. This is usually not what you', 'want. The CDN cannot be used with an authorization token, since private data cannot be cached.', "See ".concat(generateHelpUrl('js-client-usecdn-token'), " for more information.")]); exports.defaultConfig = defaultConfig; exports.initConfig = function (config, prevConfig) { var newConfig = assign({}, defaultConfig, prevConfig, config); var gradientMode = newConfig.gradientMode; var projectBased = !gradientMode && newConfig.useProjectHostname; if (typeof Promise === 'undefined') { var helpUrl = generateHelpUrl('js-client-promise-polyfill'); throw new Error("No native Promise-implementation found, polyfill needed - see ".concat(helpUrl)); } if (gradientMode && !newConfig.namespace) { throw new Error('Configuration must contain `namespace` when running in gradient mode'); } if (projectBased && !newConfig.projectId) { throw new Error('Configuration must contain `projectId`'); } var isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname; var isLocalhost = isBrowser && isLocal(window.location.hostname); if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) { printBrowserTokenWarning(); } else if ((!isBrowser || isLocalhost) && newConfig.useCdn && newConfig.token) { printCdnTokenWarning(); } else if (typeof newConfig.useCdn === 'undefined') { printCdnWarning(); } if (projectBased) { validate.projectId(newConfig.projectId); } if (!gradientMode && newConfig.dataset) { validate.dataset(newConfig.dataset, newConfig.gradientMode); } newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost; newConfig.useCdn = Boolean(newConfig.useCdn) && !newConfig.token && !newConfig.withCredentials; if (newConfig.gradientMode) { newConfig.url = newConfig.apiHost; newConfig.cdnUrl = newConfig.apiHost; } else { var hostParts = newConfig.apiHost.split('://', 2); var protocol = hostParts[0]; var host = hostParts[1]; var cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host; if (newConfig.useProjectHostname) { newConfig.url = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(host, "/v1"); newConfig.cdnUrl = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(cdnHost, "/v1"); } else { newConfig.url = "".concat(newConfig.apiHost, "/v1"); newConfig.cdnUrl = newConfig.url; } } return newConfig; }; },{"./util/once":20,"./validators":22,"@sanity/generate-help-url":24,"object-assign":65}],4:[function(require,module,exports){ "use strict"; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var assign = require('object-assign'); var _require = require('@sanity/observable/operators/filter'), filter = _require.filter; var _require2 = require('@sanity/observable/operators/map'), map = _require2.map; var validators = require('../validators'); var getSelection = require('../util/getSelection'); var encodeQueryString = require('./encodeQueryString'); var Transaction = require('./transaction'); var Patch = require('./patch'); var listen = require('./listen'); var excludeFalsey = function excludeFalsey(param, defValue) { var value = typeof param === 'undefined' ? defValue : param; return param === false ? undefined : value; }; var getMutationQuery = function getMutationQuery() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return { returnIds: true, returnDocuments: excludeFalsey(options.returnDocuments, true), visibility: options.visibility || 'sync' }; }; var isResponse = function isResponse(event) { return event.type === 'response'; }; var getBody = function getBody(event) { return event.body; }; var toPromise = function toPromise(observable) { return observable.toPromise(); }; var getQuerySizeLimit = 11264; module.exports = { listen: listen, getDataUrl: function getDataUrl(operation, path) { var config = this.clientConfig; var catalog = config.gradientMode ? config.namespace : validators.hasDataset(config); var baseUri = "/".concat(operation, "/").concat(catalog); var uri = path ? "".concat(baseUri, "/").concat(path) : baseUri; return (this.clientConfig.gradientMode ? uri : "/data".concat(uri)).replace(/\/($|\?)/, '$1'); }, fetch: function fetch(query, params) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var mapResponse = options.filterResponse === false ? function (res) { return res; } : function (res) { return res.result; }; var observable = this._dataRequest('query', { query: query, params: params }).pipe(map(mapResponse)); return this.isPromiseAPI() ? toPromise(observable) : observable; }, getDocument: function getDocument(id) { var options = { uri: this.getDataUrl('doc', id), json: true }; var observable = this._requestObservable(options).pipe(filter(isResponse), map(function (event) { return event.body.documents && event.body.documents[0]; })); return this.isPromiseAPI() ? toPromise(observable) : observable; }, create: function create(doc, options) { return this._create(doc, 'create', options); }, createIfNotExists: function createIfNotExists(doc, options) { validators.requireDocumentId('createIfNotExists', doc); return this._create(doc, 'createIfNotExists', options); }, createOrReplace: function createOrReplace(doc, options) { validators.requireDocumentId('createOrReplace', doc); return this._create(doc, 'createOrReplace', options); }, patch: function patch(selector, operations) { return new Patch(selector, operations, this); }, delete: function _delete(selection, options) { return this.dataRequest('mutate', { mutations: [{ delete: getSelection(selection) }] }, options); }, mutate: function mutate(mutations, options) { var mut = mutations instanceof Patch || mutations instanceof Transaction ? mutations.serialize() : mutations; var muts = Array.isArray(mut) ? mut : [mut]; var transactionId = options && options.transactionId; return this.dataRequest('mutate', { mutations: muts, transactionId: transactionId }, options); }, transaction: function transaction(operations) { return new Transaction(operations, this); }, dataRequest: function dataRequest(endpoint, body) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var request = this._dataRequest(endpoint, body, options); return this.isPromiseAPI() ? toPromise(request) : request; }, _dataRequest: function _dataRequest(endpoint, body) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var isMutation = endpoint === 'mutate'; // Check if the query string is within a configured threshold, // in which case we can use GET. Otherwise, use POST. var strQuery = !isMutation && encodeQueryString(body); var useGet = !isMutation && strQuery.length < getQuerySizeLimit; var stringQuery = useGet ? strQuery : ''; var returnFirst = options.returnFirst; var uri = this.getDataUrl(endpoint, stringQuery); var reqOptions = { method: useGet ? 'GET' : 'POST', uri: uri, json: true, body: useGet ? undefined : body, query: isMutation && getMutationQuery(options) }; return this._requestObservable(reqOptions).pipe(filter(isResponse), map(getBody), map(function (res) { if (!isMutation) { return res; } // Should we return documents? var results = res.results || []; if (options.returnDocuments) { return returnFirst ? results[0] && results[0].document : results.map(function (mut) { return mut.document; }); } // Return a reduced subset var key = returnFirst ? 'documentId' : 'documentIds'; var ids = returnFirst ? results[0] && results[0].id : results.map(function (mut) { return mut.id; }); return _defineProperty({ transactionId: res.transactionId, results: results }, key, ids); })); }, _create: function _create(doc, op) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var mutation = _defineProperty({}, op, doc); var opts = assign({ returnFirst: true, returnDocuments: true }, options); return this.dataRequest('mutate', { mutations: [mutation] }, opts); } }; },{"../util/getSelection":19,"../validators":22,"./encodeQueryString":5,"./listen":6,"./patch":7,"./transaction":8,"@sanity/observable/operators/filter":27,"@sanity/observable/operators/map":28,"object-assign":65}],5:[function(require,module,exports){ "use strict"; var enc = encodeURIComponent; module.exports = function (_ref) { var query = _ref.query, _ref$params = _ref.params, params = _ref$params === void 0 ? {} : _ref$params, _ref$options = _ref.options, options = _ref$options === void 0 ? {} : _ref$options; var base = "?query=".concat(enc(query)); var qString = Object.keys(params).reduce(function (qs, param) { return "".concat(qs, "&").concat(enc("$".concat(param)), "=").concat(enc(JSON.stringify(params[param]))); }, base); return Object.keys(options).reduce(function (qs, option) { // Only include the option if it is truthy return options[option] ? "".concat(qs, "&").concat(enc(option), "=").concat(enc(options[option])) : qs; }, qString); }; },{}],6:[function(require,module,exports){ "use strict"; var assign = require('object-assign'); var Observable = require('@sanity/observable/minimal'); var polyfilledEventSource = require('@sanity/eventsource'); var pick = require('../util/pick'); var defaults = require('../util/defaults'); var encodeQueryString = require('./encodeQueryString'); var generateHelpUrl = require('@sanity/generate-help-url'); var once = require('../util/once'); var tokenWarning = ['Using token with listeners is not supported in browsers. ', "For more info, see ".concat(generateHelpUrl('js-client-listener-tokens-browser'), ".")]; // eslint-disable-next-line no-console var printTokenWarning = once(function () { return console.warn(tokenWarning.join(' ')); }); var isWindowEventSource = Boolean(typeof window !== 'undefined' && window.EventSource); var EventSource = isWindowEventSource ? window.EventSource // Native browser EventSource : polyfilledEventSource; // Node.js, IE etc var possibleOptions = ['includePreviousRevision', 'includeResult']; var defaultOptions = { includeResult: true }; module.exports = function listen(query, params) { var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var options = defaults(opts, defaultOptions); var listenOpts = pick(options, possibleOptions); var qs = encodeQueryString({ query: query, params: params, options: listenOpts }); var _this$clientConfig = this.clientConfig, url = _this$clientConfig.url, token = _this$clientConfig.token, withCredentials = _this$clientConfig.withCredentials; var uri = "".concat(url).concat(this.getDataUrl('listen', qs)); var listenFor = options.events ? options.events : ['mutation']; var shouldEmitReconnect = listenFor.indexOf('reconnect') !== -1; if (token && isWindowEventSource) { printTokenWarning(); } var esOptions = {}; if (token || withCredentials) { esOptions.withCredentials = true; } if (token) { esOptions.headers = { Authorization: "Bearer ".concat(token) }; } return new Observable(function (observer) { var es = getEventSource(); var reconnectTimer; var stopped = false; function onError() { if (stopped) { return; } emitReconnect(); // Allow event handlers of `emitReconnect` to cancel/close the reconnect attempt if (stopped) { return; } // Unless we've explicitly stopped the ES (in which case `stopped` should be true), // we should never be in a disconnected state. By default, EventSource will reconnect // automatically, in which case it sets readyState to `CONNECTING`, but in some cases // (like when a laptop lid is closed), it closes the connection. In these cases we need // to explicitly reconnect. if (es.readyState === EventSource.CLOSED) { unsubscribe(); clearTimeout(reconnectTimer); reconnectTimer = setTimeout(open, 100); } } function onChannelError(err) { observer.error(cooerceError(err)); } function onMessage(evt) { var event = parseEvent(evt); return event instanceof Error ? observer.error(event) : observer.next(event); } function onDisconnect(evt) { stopped = true; unsubscribe(); observer.complete(); } function unsubscribe() { es.removeEventListener('error', onError, false); es.removeEventListener('channelError', onChannelError, false); es.removeEventListener('disconnect', onDisconnect, false); listenFor.forEach(function (type) { return es.removeEventListener(type, onMessage, false); }); es.close(); } function emitReconnect() { if (shouldEmitReconnect) { observer.next({ type: 'reconnect' }); } } function getEventSource() { var evs = new EventSource(uri, esOptions); evs.addEventListener('error', onError, false); evs.addEventListener('channelError', onChannelError, false); evs.addEventListener('disconnect', onDisconnect, false); listenFor.forEach(function (type) { return evs.addEventListener(type, onMessage, false); }); return evs; } function open() { es = getEventSource(); } function stop() { stopped = true; unsubscribe(); } return stop; }); }; function parseEvent(event) { try { var data = event.data && JSON.parse(event.data) || {}; return assign({ type: event.type }, data); } catch (err) { return err; } } function cooerceError(err) { if (err instanceof Error) { return err; } var evt = parseEvent(err); return evt instanceof Error ? evt : new Error(extractErrorMessage(evt)); } function extractErrorMessage(err) { if (!err.error) { return err.message || 'Unknown listener error'; } if (err.error.description) { return err.error.description; } return typeof err.error === 'string' ? err.error : JSON.stringify(err.error, null, 2); } },{"../util/defaults":18,"../util/once":20,"../util/pick":21,"./encodeQueryString":5,"@sanity/eventsource":23,"@sanity/generate-help-url":24,"@sanity/observable/minimal":26,"object-assign":65}],7:[function(require,module,exports){ "use strict"; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var deepAssign = require('deep-assign'); var assign = require('object-assign'); var getSelection = require('../util/getSelection'); var validate = require('../validators'); var validateObject = validate.validateObject; var validateInsert = validate.validateInsert; function Patch(selection) { var operations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var client = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; this.selection = selection; this.operations = assign({}, operations); this.client = client; } assign(Patch.prototype, { clone: function clone() { return new Patch(this.selection, assign({}, this.operations), this.client); }, merge: function merge(props) { validateObject('merge', props); var stack = new Error().stack.toString().split('\n').filter(function (str) { return str.trim(); }).slice(2); console.warn("The \"merge\" patch has been deprecated and will be removed in the future\n".concat(stack.join('\n'))); return this._assign('merge', deepAssign(this.operations.merge || {}, props)); }, set: function set(props) { return this._assign('set', props); }, diffMatchPatch: function diffMatchPatch(props) { validateObject('diffMatchPatch', props); return this._assign('diffMatchPatch', props); }, unset: function unset(attrs) { if (!Array.isArray(attrs)) { throw new Error('unset(attrs) takes an array of attributes to unset, non-array given'); } this.operations = assign({}, this.operations, { unset: attrs }); return this; }, setIfMissing: function setIfMissing(props) { return this._assign('setIfMissing', props); }, replace: function replace(props) { validateObject('replace', props); return this._set('set', { $: props }); // eslint-disable-line id-length }, inc: function inc(props) { return this._assign('inc', props); }, dec: function dec(props) { return this._assign('dec', props); }, insert: function insert(at, selector, items) { var _this$_assign; validateInsert(at, selector, items); return this._assign('insert', (_this$_assign = {}, _defineProperty(_this$_assign, at, selector), _defineProperty(_this$_assign, "items", items), _this$_assign)); }, append: function append(selector, items) { return this.insert('after', "".concat(selector, "[-1]"), items); }, prepend: function prepend(selector, items) { return this.insert('before', "".concat(selector, "[0]"), items); }, splice: function splice(selector, start, deleteCount, items) { // Negative indexes doesn't mean the same in Sanity as they do in JS; // -1 means "actually at the end of the array", which allows inserting // at the end of the array without knowing its length. We therefore have // to substract negative indexes by one to match JS. If you want Sanity- // behaviour, just use `insert('replace', selector, items)` directly var delAll = typeof deleteCount === 'undefined' || deleteCount === -1; var startIndex = start < 0 ? start - 1 : start; var delCount = delAll ? -1 : Math.max(0, start + deleteCount); var delRange = startIndex < 0 && delCount >= 0 ? '' : delCount; var rangeSelector = "".concat(selector, "[").concat(startIndex, ":").concat(delRange, "]"); return this.insert('replace', rangeSelector, items || []); }, ifRevisionId: function ifRevisionId(rev) { this.operations.ifRevisionID = rev; return this; }, serialize: function serialize() { return assign(getSelection(this.selection), this.operations); }, toJSON: function toJSON() { return this.serialize(); }, commit: function commit() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.client) { throw new Error('No `client` passed to patch, either provide one or pass the ' + 'patch to a clients `mutate()` method'); } var returnFirst = typeof this.selection === 'string'; var opts = assign({ returnFirst: returnFirst, returnDocuments: true }, options); return this.client.mutate({ patch: this.serialize() }, opts); }, reset: function reset() { this.operations = {}; return this; }, _set: function _set(op, props) { return this._assign(op, props, false); }, _assign: function _assign(op, props) { var merge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; validateObject(op, props); this.operations = assign({}, this.operations, _defineProperty({}, op, assign({}, merge && this.operations[op] || {}, props))); return this; } }); module.exports = Patch; },{"../util/getSelection":19,"../validators":22,"deep-assign":30,"object-assign":65}],8:[function(require,module,exports){ "use strict"; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var assign = require('object-assign'); var validators = require('../validators'); var Patch = require('./patch'); var defaultMutateOptions = { returnDocuments: false }; function Transaction() { var operations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var client = arguments.length > 1 ? arguments[1] : undefined; var transactionId = arguments.length > 2 ? arguments[2] : undefined; this.trxId = transactionId; this.operations = operations; this.client = client; } assign(Transaction.prototype, { clone: function clone() { return new Transaction(this.operations.slice(0), this.client, this.trxId); }, create: function create(doc) { validators.validateObject('create', doc); return this._add({ create: doc }); }, createIfNotExists: function createIfNotExists(doc) { var op = 'createIfNotExists'; validators.validateObject(op, doc); validators.requireDocumentId(op, doc); return this._add(_defineProperty({}, op, doc)); }, createOrReplace: function createOrReplace(doc) { var op = 'createOrReplace'; validators.validateObject(op, doc); validators.requireDocumentId(op, doc); return this._add(_defineProperty({}, op, doc)); }, delete: function _delete(documentId) { validators.validateDocumentId('delete', documentId); return this._add({ delete: { id: documentId } }); }, patch: function patch(documentId, patchOps) { var isBuilder = typeof patchOps === 'function'; var isPatch = documentId instanceof Patch; // transaction.patch(client.patch('documentId').inc({visits: 1})) if (isPatch) { return this._add({ patch: documentId.serialize() }); } // patch => patch.inc({visits: 1}).set({foo: 'bar'}) if (isBuilder) { var patch = patchOps(new Patch(documentId, {}, this.client)); if (!(patch instanceof Patch)) { throw new Error('function passed to `patch()` must return the patch'); } return this._add({ patch: patch.serialize() }); } return this._add({ patch: assign({ id: documentId }, patchOps) }); }, transactionId: function transactionId(id) { if (!id) { return this.trxId; } this.trxId = id; return this; }, serialize: function serialize() { return this.operations.slice(); }, toJSON: function toJSON() { return this.serialize(); }, commit: function commit(options) { if (!this.client) { throw new Error('No `client` passed to transaction, either provide one or pass the ' + 'transaction to a clients `mutate()` method'); } return this.client.mutate(this.serialize(), assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})); }, reset: function reset() { this.operations = []; return this; }, _add: function _add(mut) { this.operations.push(mut); return this; } }); module.exports = Transaction; },{"../validators":22,"./patch":7,"object-assign":65}],9:[function(require,module,exports){ "use strict"; var assign = require('object-assign'); var validate = require('../validators'); function DatasetsClient(client) { this.request = client.request.bind(client); } assign(DatasetsClient.prototype, { create: function create(name, options) { return this._modify('PUT', name, options); }, edit: function edit(name, options) { return this._modify('PATCH', name, options); }, delete: function _delete(name) { return this._modify('DELETE', name); }, list: function list() { return this.request({ uri: '/datasets' }); }, _modify: function _modify(method, name, body) { validate.dataset(name); return this.request({ method: method, uri: "/datasets/".concat(name), body: body }); } }); module.exports = DatasetsClient; },{"../validators":22,"object-assign":65}],10:[function(require,module,exports){ "use strict"; module.exports = []; },{}],11:[function(require,module,exports){ "use strict"; var makeError = require('make-error'); var assign = require('object-assign'); function ClientError(res) { var props = extractErrorProps(res); ClientError.super.call(this, props.message); assign(this, props); } function ServerError(res) { var props = extractErrorProps(res); ServerError.super.call(this, props.message); assign(this, props); } function extractErrorProps(res) { var body = res.body; var props = { response: res, statusCode: res.statusCode, responseBody: stringifyBody(body, res) // API/Boom style errors ({statusCode, error, message}) }; if (body.error && body.message) { props.message = "".concat(body.error, " - ").concat(body.message); return props; } // Query/database errors ({error: {description, other, arb, props}}) if (body.error && body.error.description) { props.message = body.error.description; props.details = body.error; return props; } // Other, more arbitrary errors props.message = body.error || body.message || httpErrorMessage(res); return props; } function httpErrorMessage(res) { var statusMessage = res.statusMessage ? " ".concat(res.statusMessage) : ''; return "".concat(res.method, "-request to ").concat(res.url, " resulted in HTTP ").concat(res.statusCode).concat(statusMessage); } function stringifyBody(body, res) { var contentType = (res.headers['content-type'] || '').toLowerCase(); var isJson = contentType.indexOf('application/json') !== -1; return isJson ? JSON.stringify(body, null, 2) : body; } makeError(ClientError); makeError(ServerError); exports.ClientError = ClientError; exports.ServerError = ServerError; },{"make-error":63,"object-assign":65}],12:[function(require,module,exports){ "use strict"; module.exports = function (params) { var qs = []; for (var key in params) { if (params.hasOwnProperty(key)) { qs.push("".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(params[key]))); } } return qs.length > 0 ? "?".concat(qs.join('&')) : ''; }; },{}],13:[function(require,module,exports){ "use strict"; /* eslint-disable no-empty-function, no-process-env */ var getIt = require('get-it'); var assign = require('object-assign'); var observable = require('get-it/lib/middleware/observable'); var jsonRequest = require('get-it/lib/middleware/jsonRequest'); var jsonResponse = require('get-it/lib/middleware/jsonResponse'); var progress = require('get-it/lib/middleware/progress'); var Observable = require('@sanity/observable/minimal'); var _require = require('./errors'), ClientError = _require.ClientError, ServerError = _require.ServerError; var httpError = { onResponse: function onResponse(res) { if (res.statusCode >= 500) { throw new ServerError(res); } else if (res.statusCode >= 400) { throw new ClientError(res); } return res; } // Environment-specific middleware. }; var envSpecific = require('./nodeMiddleware'); var middleware = envSpecific.concat([jsonRequest(), jsonResponse(), progress(), httpError, observable({ implementation: Observable })]); var request = getIt(middleware); function httpRequest(options) { var requester = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : request; return requester(assign({ maxRedirects: 0 }, options)); } httpRequest.defaultRequester = request; httpRequest.ClientError = ClientError; httpRequest.ServerError = ServerError; module.exports = httpRequest; },{"./errors":11,"./nodeMiddleware":10,"@sanity/observable/minimal":26,"get-it":45,"get-it/lib/middleware/jsonRequest":49,"get-it/lib/middleware/jsonResponse":50,"get-it/lib/middleware/observable":51,"get-it/lib/middleware/progress":53,"object-assign":65}],14:[function(require,module,exports){ "use strict"; var projectHeader = 'X-Sanity-Project-ID'; module.exports = function (config) { var headers = {}; if (config.token) { headers.Authorization = "Bearer ".concat(config.token); } if (!config.useProjectHostname && config.projectId) { headers[projectHeader] = config.projectId; } return { headers: headers, timeout: 'timeout' in config ? config.timeout : 30000, json: true, withCredentials: Boolean(config.token || config.withCredentials) }; }; },{}],15:[function(require,module,exports){ "use strict"; var assign = require('object-assign'); function ProjectsClient(client) { this.client = client; } assign(ProjectsClient.prototype, { list: function list() { return this.client.request({ uri: '/projects' }); }, getById: function getById(id) { return this.client.request({ uri: "/projects/".concat(id) }); } }); module.exports = ProjectsClient; },{"object-assign":65}],16:[function(require,module,exports){ "use strict"; var assign = require('object-assign'); var _require = require('@sanity/observable/operators/filter'), filter = _require.filter; var _require2 = require('@sanity/observable/operators/map'), map = _require2.map; var Patch = require('./data/patch'); var Transaction = require('./data/transaction'); var dataMethods = require('./data/dataMethods'); var DatasetsClient = require('./datasets/datasetsClient'); var ProjectsClient = require('./projects/projectsClient'); var AssetsClient = require('./assets/assetsClient'); var UsersClient = require('./users/usersClient'); var AuthClient = require('./auth/authClient'); var httpRequest = require('./http/request'); var getRequestOptions = require('./http/requestOptions'); var _require3 = require('./config'), defaultConfig = _require3.defaultConfig, initConfig = _require3.initConfig; var toPromise = function toPromise(observable) { return observable.toPromise(); }; function SanityClient() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultConfig; if (!(this instanceof SanityClient)) { return new SanityClient(config); } this.config(config); this.assets = new AssetsClient(this); this.datasets = new DatasetsClient(this); this.projects = new ProjectsClient(this); this.users = new UsersClient(this); this.auth = new AuthClient(this); if (this.clientConfig.isPromiseAPI) { var observableConfig = assign({}, this.clientConfig, { isPromiseAPI: false }); this.observable = new SanityClient(observableConfig); } } assign(SanityClient.prototype, dataMethods); assign(SanityClient.prototype, { clone: function clone() { return new SanityClient(this.config()); }, config: function config(newConfig) { if (typeof newConfig === 'undefined') { return assign({}, this.clientConfig); } if (this.observable) { var observableConfig = assign({}, newConfig, { isPromiseAPI: false }); this.observable.config(observableConfig); } this.clientConfig = initConfig(newConfig, this.clientConfig || {}); return this; }, getUrl: function getUrl(uri) { var canUseCdn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var base = canUseCdn ? this.clientConfig.cdnUrl : this.clientConfig.url; return "".concat(base, "/").concat(uri.replace(/^\//, '')); }, isPromiseAPI: function isPromiseAPI() { return this.clientConfig.isPromiseAPI; }, _requestObservable: function _requestObservable(options) { var uri = options.url || options.uri; var canUseCdn = this.clientConfig.useCdn && ['GET', 'HEAD'].indexOf(options.method || 'GET') >= 0 && uri.indexOf('/data/') === 0; return httpRequest(mergeOptions(getRequestOptions(this.clientConfig), options, { url: this.getUrl(uri, canUseCdn) }), this.clientConfig.requester); }, request: function request(options) { var observable = this._requestObservable(options).pipe(filter(function (event) { return event.type === 'response'; }), map(function (event) { return event.body; })); return this.isPromiseAPI() ? toPromise(observable) : observable; } }); // Merge http options and headers function mergeOptions() { for (var _len = arguments.length, opts = new Array(_len), _key = 0; _key < _len; _key++) { opts[_key] = arguments[_key]; } var headers = opts.reduce(function (merged, options) { if (!merged && !options.headers) { return null; } return assign(merged || {}, options.headers || {}); }, null); return assign.apply(void 0, opts.concat([headers ? { headers: headers } : {}])); } SanityClient.Patch = Patch; SanityClient.Transaction = Transaction; SanityClient.ClientError = httpRequest.ClientError; SanityClient.ServerError = httpRequest.ServerError; SanityClient.requester = httpRequest.defaultRequester; module.exports = SanityClient; },{"./assets/assetsClient":1,"./auth/authClient":2,"./config":3,"./data/dataMethods":4,"./data/patch":7,"./data/transaction":8,"./datasets/datasetsClient":9,"./http/request":13,"./http/requestOptions":14,"./projects/projectsClient":15,"./users/usersClient":17,"@sanity/observable/operators/filter":27,"@sanity/observable/operators/map":28,"object-assign":65}],17:[function(require,module,exports){ "use strict"; var assign = require('object-assign'); function UsersClient(client) { this.client = client; } assign(UsersClient.prototype, { getById: function getById(id) { return this.client.request({ uri: "/users/".concat(id) }); } }); module.exports = UsersClient; },{"object-assign":65}],18:[function(require,module,exports){ "use strict"; module.exports = function (obj, defaults) { return Object.keys(defaults).concat(Object.keys(obj)).reduce(function (target, prop) { target[prop] = typeof obj[prop] === 'undefined' ? defaults[prop] : obj[prop]; return target; }, {}); }; },{}],19:[function(require,module,exports){ "use strict"; module.exports = function getSelection(sel) { if (typeof sel === 'string' || Array.isArray(sel)) { return { id: sel }; } if (sel && sel.query) { return { query: sel.query }; } var selectionOpts = ['* Document ID ()', '* Array of document IDs', '* Object containing `query`'].join('\n'); throw new Error("Unknown selection - must be one of:\n\n".concat(selectionOpts)); }; },{}],20:[function(require,module,exports){ "use strict"; module.exports = function (fn) { var didCall = false; var returnValue; return function () { if (didCall) { return returnValue; } returnValue = fn.apply(void 0, arguments); didCall = true; return returnValue; }; }; },{}],21:[function(require,module,exports){ "use strict"; module.exports = function (obj, props) { return props.reduce(function (selection, prop) { if (typeof obj[prop] === 'undefined') { return selection; } selection[prop] = obj[prop]; return selection; }, {}); }; },{}],22:[function(require,module,exports){ "use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } var VALID_ASSET_TYPES = ['image', 'file']; var VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']; exports.dataset = function (name) { if (!/^[-\w]{1,128}$/.test(name)) { throw new Error('Datasets can only contain lowercase characters, numbers, underscores and dashes'); } }; exports.projectId = function (id) { if (!/^[-a-z0-9]+$/i.test(id)) { throw new Error('`projectId` can only contain only a-z, 0-9 and dashes'); } }; exports.validateAssetType = function (type) { if (VALID_ASSET_TYPES.indexOf(type) === -1) { throw new Error("Invalid asset type: ".concat(type, ". Must be one of ").concat(VALID_ASSET_TYPES.join(', '))); } }; exports.validateObject = function (op, val) { if (val === null || _typeof(val) !== 'object' || Array.isArray(val)) { throw new Error("".concat(op, "() takes an object of properties")); } }; exports.requireDocumentId = function (op, doc) { if (!doc._id) { throw new Error("".concat(op, "() requires that the document contains an ID (\"_id\" property)")); } exports.validateDocumentId(op, doc._id); }; exports.validateDocumentId = function (op, id) { if (typeof id !== 'string' || !/^[a-z0-9_.-]+$/i.test(id)) { throw new Error("".concat(op, "(): \"").concat(id, "\" is not a valid document ID")); } }; exports.validateInsert = function (at, selector, items) { var signature = 'insert(at, selector, items)'; if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) { var valid = VALID_INSERT_LOCATIONS.map(function (loc) { return "\"".concat(loc, "\""); }).join(', '); throw new Error("".concat(signature, " takes an \"at\"-argument which is one of: ").concat(valid)); } if (typeof selector !== 'string') { throw new Error("".concat(signature, " takes a \"selector\"-argument which must be a string")); } if (!Array.isArray(items)) { throw new Error("".concat(signature, " takes an \"items\"-argument which must be an array")); } }; exports.hasDataset = function (config) { if (!config.gradientMode && !config.dataset) { throw new Error('`dataset` must be provided to perform queries'); } return config.dataset || ''; }; },{}],23:[function(require,module,exports){ /* eslint-disable no-var */ var evs = require('eventsource-polyfill/dist/eventsource') module.exports = window.EventSource || evs.EventSource },{"eventsource-polyfill/dist/eventsource":41}],24:[function(require,module,exports){ var baseUrl = 'https://docs.sanity.io/help/' module.exports = function generateHelpUrl(slug) { return baseUrl + slug } },{}],25:[function(require,module,exports){ "use strict"; var _require = require('rxjs/internal/Observable'), Observable = _require.Observable; var assign = require('object-assign'); var _require2 = require('../operators/map'), map = _require2.map; var _require3 = require('../operators/filter'), filter = _require3.filter; var _require4 = require('../operators/reduce'), reduce = _require4.reduce; /* A minimal rxjs based observable that align as closely as possible with the current es-observable spec, without the static factory methods */ function SanityObservableMinimal() { Observable.apply(this, arguments); // eslint-disable-line prefer-rest-params } SanityObservableMinimal.prototype = Object.create(assign(Object.create(null), Observable.prototype)); Object.defineProperty(SanityObservableMinimal.prototype, 'constructor', { value: SanityObservableMinimal, enumerable: false, writable: true, configurable: true }); SanityObservableMinimal.prototype.lift = function lift(operator) { var observable = new SanityObservableMinimal(); observable.source = this; observable.operator = operator; return observable; }; function createDeprecatedMemberOp(name, op) { var hasWarned = false; return function deprecatedOperator() { if (!hasWarned) { hasWarned = true; console.warn(new Error("Calling observable.".concat(name, "(...) is deprecated. Please use observable.pipe(").concat(name, "(...)) instead"))); } return this.pipe(op.apply(this, arguments)); }; } SanityObservableMinimal.prototype.map = createDeprecatedMemberOp('map', map); SanityObservableMinimal.prototype.filter = createDeprecatedMemberOp('filter', filter); SanityObservableMinimal.prototype.reduce = createDeprecatedMemberOp('filter', reduce); module.exports = SanityObservableMinimal; },{"../operators/filter":27,"../operators/map":28,"../operators/reduce":29,"object-assign":65,"rxjs/internal/Observable":72}],26:[function(require,module,exports){ module.exports = require('./lib/SanityObservableMinimal') },{"./lib/SanityObservableMinimal":25}],27:[function(require,module,exports){ exports.filter = require('rxjs/internal/operators/filter').filter },{"rxjs/internal/operators/filter":79}],28:[function(require,module,exports){ exports.map = require('rxjs/internal/operators/map').map },{"rxjs/internal/operators/map":80}],29:[function(require,module,exports){ exports.reduce = require('rxjs/internal/operators/reduce').reduce },{"rxjs/internal/operators/reduce":81}],30:[function(require,module,exports){ 'use strict'; var isObj = require('is-obj'); var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Sources cannot be null or undefined'); } return Object(val); } function assignKey(to, from, key) { var val = from[key]; if (val === undefined || val === null) { return; } if (hasOwnProperty.call(to, key)) { if (to[key] === undefined || to[key] === null) { throw new TypeError('Cannot convert undefined or null to object (' + key + ')'); } } if (!hasOwnProperty.call(to, key) || !isObj(val)) { to[key] = val; } else { to[key] = assign(Object(to[key]), from[key]); } } function assign(to, from) { if (to === from) { return to; } from = Object(from); for (var key in from) { if (hasOwnProperty.call(from, key)) { assignKey(to, from, key); } } if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { assignKey(to, from, symbols[i]); } } } return to; } module.exports = function deepAssign(target) { target = toObject(target); for (var s = 1; s < arguments.length; s++) { assign(target, arguments[s]); } return target; }; },{"is-obj":60}],31:[function(require,module,exports){ 'use strict'; var keys = require('object-keys'); var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; var toStr = Object.prototype.toString; var concat = Array.prototype.concat; var origDefineProperty = Object.defineProperty; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { origDefineProperty(obj, 'x', { enumerable: false, value: obj }); // eslint-disable-next-line no-unused-vars, no-restricted-syntax for (var _ in obj) { // jscs:ignore disallowUnusedVariables return false; } return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { origDefineProperty(object, name, { configurable: true, enumerable: false, value: value, writable: true }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = concat.call(props, Object.getOwnPropertySymbols(map)); } for (var i = 0; i < props.length; i += 1) { defineProperty(object, props[i], map[props[i]], predicates[props[i]]); } }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; },{"object-keys":67}],32:[function(require,module,exports){ 'use strict'; /* globals Set, Map, WeakSet, WeakMap, Promise, Symbol, Proxy, Atomics, SharedArrayBuffer, ArrayBuffer, DataView, Uint8Array, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Uint8ClampedArray, Uint16Array, Uint32Array, */ var undefined; // eslint-disable-line no-shadow-restricted-names var ThrowTypeError = Object.getOwnPropertyDescriptor ? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }()) : function () { throw new TypeError(); }; var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto var generator; // = function * () {}; var generatorFunction = generator ? getProto(generator) : undefined; var asyncFn; // async function() {}; var asyncFunction = asyncFn ? asyncFn.constructor : undefined; var asyncGen; // async function * () {}; var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined; var asyncGenIterator = asyncGen ? asyncGen() : undefined; var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); var INTRINSICS = { '$ %Array%': Array, '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype, '$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, '$ %ArrayPrototype%': Array.prototype, '$ %ArrayProto_entries%': Array.prototype.entries, '$ %ArrayProto_forEach%': Array.prototype.forEach, '$ %ArrayProto_keys%': Array.prototype.keys, '$ %ArrayProto_values%': Array.prototype.values, '$ %AsyncFromSyncIteratorPrototype%': undefined, '$ %AsyncFunction%': asyncFunction, '$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined, '$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined, '$ %AsyncGeneratorFunction%': asyncGenFunction, '$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined, '$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined, '$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, '$ %Boolean%': Boolean, '$ %BooleanPrototype%': Boolean.prototype, '$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView, '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype, '$ %Date%': Date, '$ %DatePrototype%': Date.prototype, '$ %decodeURI%': decodeURI, '$ %decodeURIComponent%': decodeURIComponent, '$ %encodeURI%': encodeURI, '$ %encodeURIComponent%': encodeURIComponent, '$ %Error%': Error, '$ %ErrorPrototype%': Error.prototype, '$ %eval%': eval, // eslint-disable-line no-eval '$ %EvalError%': EvalError, '$ %EvalErrorPrototype%': EvalError.prototype, '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype, '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype, '$ %Function%': Function, '$ %FunctionPrototype%': Function.prototype, '$ %Generator%': generator ? getProto(generator()) : undefined, '$ %GeneratorFunction%': generatorFunction, '$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined, '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype, '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype, '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype, '$ %isFinite%': isFinite, '$ %isNaN%': isNaN, '$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, '$ %JSON%': JSON, '$ %JSONParse%': JSON.parse, '$ %Map%': typeof Map === 'undefined' ? undefined : Map, '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), '$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype, '$ %Math%': Math, '$ %Number%': Number, '$ %NumberPrototype%': Number.prototype, '$ %Object%': Object, '$ %ObjectPrototype%': Object.prototype, '$ %ObjProto_toString%': Object.prototype.toString, '$ %ObjProto_valueOf%': Object.prototype.valueOf, '$ %parseFloat%': parseFloat, '$ %parseInt%': parseInt, '$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise, '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype, '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then, '$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all, '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject, '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve, '$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, '$ %RangeError%': RangeError, '$ %RangeErrorPrototype%': RangeError.prototype, '$ %ReferenceError%': ReferenceError, '$ %ReferenceErrorPrototype%': ReferenceError.prototype, '$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, '$ %RegExp%': RegExp, '$ %RegExpPrototype%': RegExp.prototype, '$ %Set%': typeof Set === 'undefined' ? undefined : Set, '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), '$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype, '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype, '$ %String%': String, '$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, '$ %StringPrototype%': String.prototype, '$ %Symbol%': hasSymbols ? Symbol : undefined, '$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined, '$ %SyntaxError%': SyntaxError, '$ %SyntaxErrorPrototype%': SyntaxError.prototype, '$ %ThrowTypeError%': ThrowTypeError, '$ %TypedArray%': TypedArray, '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined, '$ %TypeError%': TypeError, '$ %TypeErrorPrototype%': TypeError.prototype, '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype, '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype, '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype, '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype, '$ %URIError%': URIError, '$ %URIErrorPrototype%': URIError.prototype, '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype, '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype }; module.exports = function GetIntrinsic(name, allowMissing) { if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new TypeError('"allowMissing" argument must be a boolean'); } var key = '$ ' + name; if (!(key in INTRINSICS)) { throw new SyntaxError('intrinsic ' + name + ' does not exist!'); } // istanbul ignore if // hopefully this is impossible to test :-) if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) { throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return INTRINSICS[key]; }; },{}],33:[function(require,module,exports){ 'use strict'; var GetIntrinsic = require('./GetIntrinsic'); var $Object = GetIntrinsic('%Object%'); var $TypeError = GetIntrinsic('%TypeError%'); var $String = GetIntrinsic('%String%'); var assertRecord = require('./helpers/assertRecord'); var $isNaN = require('./helpers/isNaN'); var $isFinite = require('./helpers/isFinite'); var sign = require('./helpers/sign'); var mod = require('./helpers/mod'); var IsCallable = require('is-callable'); var toPrimitive = require('es-to-primitive/es5'); var has = require('has'); // https://es5.github.io/#x9 var ES5 = { ToPrimitive: toPrimitive, ToBoolean: function ToBoolean(value) { return !!value; }, ToNumber: function ToNumber(value) { return +value; // eslint-disable-line no-implicit-coercion }, ToInteger: function ToInteger(value) { var number = this.ToNumber(value); if ($isNaN(number)) { return 0; } if (number === 0 || !$isFinite(number)) { return number; } return sign(number) * Math.floor(Math.abs(number)); }, ToInt32: function ToInt32(x) { return this.ToNumber(x) >> 0; }, ToUint32: function ToUint32(x) { return this.ToNumber(x) >>> 0; }, ToUint16: function ToUint16(value) { var number = this.ToNumber(value); if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } var posInt = sign(number) * Math.floor(Math.abs(number)); return mod(posInt, 0x10000); }, ToString: function ToString(value) { return $String(value); }, ToObject: function ToObject(value) { this.CheckObjectCoercible(value); return $Object(value); }, CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) { /* jshint eqnull:true */ if (value == null) { throw new $TypeError(optMessage || 'Cannot call method on ' + value); } return value; }, IsCallable: IsCallable, SameValue: function SameValue(x, y) { if (x === y) { // 0 === -0, but they are not identical. if (x === 0) { return 1 / x === 1 / y; } return true; } return $isNaN(x) && $isNaN(y); }, // https://www.ecma-international.org/ecma-262/5.1/#sec-8 Type: function Type(x) { if (x === null) { return 'Null'; } if (typeof x === 'undefined') { return 'Undefined'; } if (typeof x === 'function' || typeof x === 'object') { return 'Object'; } if (typeof x === 'number') { return 'Number'; } if (typeof x === 'boolean') { return 'Boolean'; } if (typeof x === 'string') { return 'String'; } }, // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type IsPropertyDescriptor: function IsPropertyDescriptor(Desc) { if (this.Type(Desc) !== 'Object') { return false; } var allowed = { '[[Configurable]]': true, '[[Enumerable]]': true, '[[Get]]': true, '[[Set]]': true, '[[Value]]': true, '[[Writable]]': true }; for (var key in Desc) { // eslint-disable-line if (has(Desc, key) && !allowed[key]) { return false; } } var isData = has(Desc, '[[Value]]'); var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]'); if (isData && IsAccessor) { throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); } return true; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1 IsAccessorDescriptor: function IsAccessorDescriptor(Desc) { if (typeof Desc === 'undefined') { return false; } assertRecord(this, 'Property Descriptor', 'Desc', Desc); if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { return false; } return true; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2 IsDataDescriptor: function IsDataDescriptor(Desc) { if (typeof Desc === 'undefined') { return false; } assertRecord(this, 'Property Descriptor', 'Desc', Desc); if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { return false; } return true; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3 IsGenericDescriptor: function IsGenericDescriptor(Desc) { if (typeof Desc === 'undefined') { return false; } assertRecord(this, 'Property Descriptor', 'Desc', Desc); if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) { return true; } return false; }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4 FromPropertyDescriptor: function FromPropertyDescriptor(Desc) { if (typeof Desc === 'undefined') { return Desc; } assertRecord(this, 'Property Descriptor', 'Desc', Desc); if (this.IsDataDescriptor(Desc)) { return { value: Desc['[[Value]]'], writable: !!Desc['[[Writable]]'], enumerable: !!Desc['[[Enumerable]]'], configurable: !!Desc['[[Configurable]]'] }; } else if (this.IsAccessorDescriptor(Desc)) { return { get: Desc['[[Get]]'], set: Desc['[[Set]]'], enumerable: !!Desc['[[Enumerable]]'], configurable: !!Desc['[[Configurable]]'] }; } else { throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor'); } }, // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 ToPropertyDescriptor: function ToPropertyDescriptor(Obj) { if (this.Type(Obj) !== 'Object') { throw new $TypeError('ToPropertyDescriptor requires an object'); } var desc = {}; if (has(Obj, 'enumerable')) { desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable); } if (has(Obj, 'configurable')) { desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable); } if (has(Obj, 'value')) { desc['[[Value]]'] = Obj.value; } if (has(Obj, 'writable')) { desc['[[Writable]]'] = this.ToBoolean(Obj.writable); } if (has(Obj, 'get')) { var getter = Obj.get; if (typeof getter !== 'undefined' && !this.IsCallable(getter)) { throw new TypeError('getter must be a function'); } desc['[[Get]]'] = getter; } if (has(Obj, 'set')) { var setter = Obj.set; if (typeof setter !== 'undefined' && !this.IsCallable(setter)) { throw new $TypeError('setter must be a function'); } desc['[[Set]]'] = setter; } if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); } return desc; } }; module.exports = ES5; },{"./GetIntrinsic":32,"./helpers/assertRecord":34,"./helpers/isFinite":35,"./helpers/isNaN":36,"./helpers/mod":37,"./helpers/sign":38,"es-to-primitive/es5":39,"has":58,"is-callable":59}],34:[function(require,module,exports){ 'use strict'; var GetIntrinsic = require('../GetIntrinsic'); var $TypeError = GetIntrinsic('%TypeError%'); var $SyntaxError = GetIntrinsic('%SyntaxError%'); var has = require('has'); var predicates = { // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type 'Property Descriptor': function isPropertyDescriptor(ES, Desc) { if (ES.Type(Desc) !== 'Object') { return false; } var allowed = { '[[Configurable]]': true, '[[Enumerable]]': true, '[[Get]]': true, '[[Set]]': true, '[[Value]]': true, '[[Writable]]': true }; for (var key in Desc) { // eslint-disable-line if (has(Desc, key) && !allowed[key]) { return false; } } var isData = has(Desc, '[[Value]]'); var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]'); if (isData && IsAccessor) { throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); } return true; } }; module.exports = function assertRecord(ES, recordType, argumentName, value) { var predicate = predicates[recordType]; if (typeof predicate !== 'function') { throw new $SyntaxError('unknown record type: ' + recordType); } if (!predicate(ES, value)) { throw new $TypeError(argumentName + ' must be a ' + recordType); } console.log(predicate(ES, value), value); }; },{"../GetIntrinsic":32,"has":58}],35:[function(require,module,exports){ var $isNaN = Number.isNaN || function (a) { return a !== a; }; module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; }; },{}],36:[function(require,module,exports){ module.exports = Number.isNaN || function isNaN(a) { return a !== a; }; },{}],37:[function(require,module,exports){ module.exports = function mod(number, modulo) { var remain = number % modulo; return Math.floor(remain >= 0 ? remain : remain + modulo); }; },{}],38:[function(require,module,exports){ module.exports = function sign(number) { return number >= 0 ? 1 : -1; }; },{}],39:[function(require,module,exports){ 'use strict'; var toStr = Object.prototype.toString; var isPrimitive = require('./helpers/isPrimitive'); var isCallable = require('is-callable'); // http://ecma-international.org/ecma-262/5.1/#sec-8.12.8 var ES5internalSlots = { '[[DefaultValue]]': function (O) { var actualHint; if (arguments.length > 1) { actualHint = arguments[1]; } else { actualHint = toStr.call(O) === '[object Date]' ? String : Number; } if (actualHint === String || actualHint === Number) { var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString']; var value, i; for (i = 0; i < methods.length; ++i) { if (isCallable(O[methods[i]])) { value = O[methods[i]](); if (isPrimitive(value)) { return value; } } } throw new TypeError('No default value'); } throw new TypeError('invalid [[DefaultValue]] hint supplied'); } }; // http://ecma-international.org/ecma-262/5.1/#sec-9.1 module.exports = function ToPrimitive(input) { if (isPrimitive(input)) { return input; } if (arguments.length > 1) { return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]); } return ES5internalSlots['[[DefaultValue]]'](input); }; },{"./helpers/isPrimitive":40,"is-callable":59}],40:[function(require,module,exports){ module.exports = function isPrimitive(value) { return value === null || (typeof value !== 'function' && typeof value !== 'object'); }; },{}],41:[function(require,module,exports){ /* * EventSource polyfill version 0.9.6 * Supported by sc AmvTek srl * :email: devel@amvtek.com */ ;(function (global) { if (global.EventSource && !global._eventSourceImportPrefix){ return; } var evsImportName = (global._eventSourceImportPrefix||'')+"EventSource"; var EventSource = function (url, options) { if (!url || typeof url != 'string') { throw new SyntaxError('Not enough arguments'); } this.URL = url; this.setOptions(options); var evs = this; setTimeout(function(){evs.poll()}, 0); }; EventSource.prototype = { CONNECTING: 0, OPEN: 1, CLOSED: 2, defaultOptions: { loggingEnabled: false, loggingPrefix: "eventsource", interval: 500, // milliseconds bufferSizeLimit: 256*1024, // bytes silentTimeout: 300000, // milliseconds getArgs:{ 'evs_buffer_size_limit': 256*1024 }, xhrHeaders:{ 'Accept': 'text/event-stream', 'Cache-Control': 'no-cache', 'X-Requested-With': 'XMLHttpRequest' } }, setOptions: function(options){ var defaults = this.defaultOptions; var option; // set all default options... for (option in defaults){ if ( defaults.hasOwnProperty(option) ){ this[option] = defaults[option]; } } // override with what is in options for (option in options){ if (option in defaults && options.hasOwnProperty(option)){ this[option] = options[option]; } } // if getArgs option is enabled // ensure evs_buffer_size_limit corresponds to bufferSizeLimit if (this.getArgs && this.bufferSizeLimit) { this.getArgs['evs_buffer_size_limit'] = this.bufferSizeLimit; } // if console is not available, force loggingEnabled to false if (typeof console === "undefined" || typeof console.log === "undefined") { this.loggingEnabled = false; } }, log: function(message) { if (this.loggingEnabled) { console.log("[" + this.loggingPrefix +"]:" + message) } }, poll: function() { try { if (this.readyState == this.CLOSED) { return; } this.cleanup(); this.readyState = this.CONNECTING; this.cursor = 0; this.cache = ''; this._xhr = new this.XHR(this); this.resetNoActivityTimer(); } catch (e) { // in an attempt to silence the errors this.log('There were errors inside the pool try-catch'); this.dispatchEvent('error', { type: 'error', data: e.message }); } }, pollAgain: function (interval) { // schedule poll to be called after interval milliseconds var evs = this; evs.readyState = evs.CONNECTING; evs.dispatchEvent('error', { type: 'error', data: "Reconnecting " }); this._pollTimer = setTimeout(function(){evs.poll()}, interval||0); }, cleanup: function() { this.log('evs cleaning up') if (this._pollTimer){ clearInterval(this._pollTimer); this._pollTimer = null; } if (this._noActivityTimer){ clearInterval(this._noActivityTimer); this._noActivityTimer = null; } if (this._xhr){ this._xhr.abort(); this._xhr = null; } }, resetNoActivityTimer: function(){ if (this.silentTimeout){ if (this._noActivityTimer){ clearInterval(this._noActivityTimer); } var evs = this; this._noActivityTimer = setTimeout( function(){ evs.log('Timeout! silentTImeout:'+evs.silentTimeout); evs.pollAgain(); }, this.silentTimeout ); } }, close: function () { this.readyState = this.CLOSED; this.log('Closing connection. readyState: '+this.readyState); this.cleanup(); }, ondata: function() { var request = this._xhr; if (request.isReady() && !request.hasError() ) { // reset the timer, as we have activity this.resetNoActivityTimer(); // move this EventSource to OPEN state... if (this.readyState == this.CONNECTING) { this.readyState = this.OPEN; this.dispatchEvent('open', { type: 'open' }); } var buffer = request.getBuffer(); if (buffer.length > this.bufferSizeLimit) { this.log('buffer.length > this.bufferSizeLimit'); this.pollAgain(); } if (this.cursor == 0 && buffer.length > 0){ // skip byte order mark \uFEFF character if it starts the stream if (buffer.substring(0,1) == '\uFEFF'){ this.cursor = 1; } } var lastMessageIndex = this.lastMessageIndex(buffer); if (lastMessageIndex[0] >= this.cursor){ var newcursor = lastMessageIndex[1]; var toparse = buffer.substring(this.cursor, newcursor); this.parseStream(toparse); this.cursor = newcursor; } // if request is finished, reopen the connection if (request.isDone()) { this.log('request.isDone(). reopening the connection'); this.pollAgain(this.interval); } } else if (this.readyState !== this.CLOSED) { this.log('this.readyState !== this.CLOSED'); this.pollAgain(this.interval); //MV: Unsure why an error was previously dispatched } }, parseStream: function(chunk) { // normalize line separators (\r\n,\r,\n) to \n // remove white spaces that may precede \n chunk = this.cache + this.normalizeToLF(chunk); var events = chunk.split('\n\n'); var i, j, eventType, datas, line, retry; for (i=0; i < (events.length - 1); i++) { eventType = 'message'; datas = []; parts = events[i].split('\n'); for (j=0; j < parts.length; j++) { line = this.trimWhiteSpace(parts[j]); if (line.indexOf('event') == 0) { eventType = line.replace(/event:?\s*/, ''); } else if (line.indexOf('retry') == 0) { retry = parseInt(line.replace(/retry:?\s*/, '')); if(!isNaN(retry)) { this.interval = retry; } } else if (line.indexOf('data') == 0) { datas.push(line.replace(/data:?\s*/, '')); } else if (line.indexOf('id:') == 0) { this.lastEventId = line.replace(/id:?\s*/, ''); } else if (line.indexOf('id') == 0) { // this resets the id this.lastEventId = null; } } if (datas.length) { // dispatch a new event var event = new MessageEvent(eventType, datas.join('\n'), window.location.origin, this.lastEventId); this.dispatchEvent(eventType, event); } } this.cache = events[events.length - 1]; }, dispatchEvent: function (type, event) { var handlers = this['_' + type + 'Handlers']; if (handlers) { for (var i = 0; i < handlers.length; i++) { handlers[i].call(this, event); } } if (this['on' + type]) { this['on' + type].call(this, event); } }, addEventListener: function (type, handler) { if (!this['_' + type + 'Handlers']) { this['_' + type + 'Handlers'] = []; } this['_' + type + 'Handlers'].push(handler); }, removeEventListener: function (type, handler) { var handlers = this['_' + type + 'Handlers']; if (!handlers) { return; } for (var i = handlers.length - 1; i >= 0; --i) { if (handlers[i] === handler) { handlers.splice(i, 1); break; } } }, _pollTimer: null, _noactivityTimer: null, _xhr: null, lastEventId: null, cache: '', cursor: 0, onerror: null, onmessage: null, onopen: null, readyState: 0, // =================================================================== // helpers functions // those are attached to prototype to ease reuse and testing... urlWithParams: function (baseURL, params) { var encodedArgs = []; if (params){ var key, urlarg; var urlize = encodeURIComponent; for (key in params){ if (params.hasOwnProperty(key)) { urlarg = urlize(key)+'='+urlize(params[key]); encodedArgs.push(urlarg); } } } if (encodedArgs.length > 0){ if (baseURL.indexOf('?') == -1) return baseURL + '?' + encodedArgs.join('&'); return baseURL + '&' + encodedArgs.join('&'); } return baseURL; }, lastMessageIndex: function(text) { var ln2 =text.lastIndexOf('\n\n'); var lr2 = text.lastIndexOf('\r\r'); var lrln2 = text.lastIndexOf('\r\n\r\n'); if (lrln2 > Math.max(ln2, lr2)) { return [lrln2, lrln2+4]; } return [Math.max(ln2, lr2), Math.max(ln2, lr2) + 2] }, trimWhiteSpace: function(str) { // to remove whitespaces left and right of string var reTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g; return str.replace(reTrim, ''); }, normalizeToLF: function(str) { // replace \r and \r\n with \n return str.replace(/\r\n|\r/g, '\n'); } }; if (!isOldIE()){ EventSource.isPolyfill = "XHR"; // EventSource will send request using XMLHttpRequest EventSource.prototype.XHR = function(evs) { request = new XMLHttpRequest(); this._request = request; evs._xhr = this; // set handlers request.onreadystatechange = function(){ if (request.readyState > 1 && evs.readyState != evs.CLOSED) { if (request.status == 200 || (request.status>=300 && request.status<400)){ evs.ondata(); } else { request._failed = true; evs.readyState = evs.CLOSED; evs.dispatchEvent('error', { type: 'error', data: "The server responded with "+request.status }); evs.close(); } } }; request.onprogress = function () { }; request.open('GET', evs.urlWithParams(evs.URL, evs.getArgs), true); var headers = evs.xhrHeaders; // maybe null for (var header in headers) { if (headers.hasOwnProperty(header)){ request.setRequestHeader(header, headers[header]); } } if (evs.lastEventId) { request.setRequestHeader('Last-Event-Id', evs.lastEventId); } request.send(); }; EventSource.prototype.XHR.prototype = { useXDomainRequest: false, _request: null, _failed: false, // true if we have had errors... isReady: function() { return this._request.readyState >= 2; }, isDone: function() { return (this._request.readyState == 4); }, hasError: function() { return (this._failed || (this._request.status >= 400)); }, getBuffer: function() { var rv = ''; try { rv = this._request.responseText || ''; } catch (e){} return rv; }, abort: function() { if ( this._request ) { this._request.abort(); } } }; } else { EventSource.isPolyfill = "IE_8-9"; // patch EventSource defaultOptions var defaults = EventSource.prototype.defaultOptions; defaults.xhrHeaders = null; // no headers will be sent defaults.getArgs['evs_preamble'] = 2048 + 8; // EventSource will send request using Internet Explorer XDomainRequest EventSource.prototype.XHR = function(evs) { request = new XDomainRequest(); this._request = request; // set handlers request.onprogress = function(){ request._ready = true; evs.ondata(); }; request.onload = function(){ this._loaded = true; evs.ondata(); }; request.onerror = function(){ this._failed = true; evs.readyState = evs.CLOSED; evs.dispatchEvent('error', { type: 'error', data: "XDomainRequest error" }); }; request.ontimeout = function(){ this._failed = true; evs.readyState = evs.CLOSED; evs.dispatchEvent('error', { type: 'error', data: "XDomainRequest timed out" }); }; // XDomainRequest does not allow setting custom headers // If EventSource has enabled the use of GET arguments // we add parameters to URL so that server can adapt the stream... var reqGetArgs = {}; if (evs.getArgs) { // copy evs.getArgs in reqGetArgs var defaultArgs = evs.getArgs; for (var key in defaultArgs) { if (defaultArgs.hasOwnProperty(key)){ reqGetArgs[key] = defaultArgs[key]; } } if (evs.lastEventId){ reqGetArgs['evs_last_event_id'] = evs.lastEventId; } } // send the request request.open('GET', evs.urlWithParams(evs.URL,reqGetArgs)); request.send(); }; EventSource.prototype.XHR.prototype = { useXDomainRequest: true, _request: null, _ready: false, // true when progress events are dispatched _loaded: false, // true when request has been loaded _failed: false, // true if when request is in error isReady: function() { return this._request._ready; }, isDone: function() { return this._request._loaded; }, hasError: function() { return this._request._failed; }, getBuffer: function() { var rv = ''; try { rv = this._request.responseText || ''; } catch (e){} return rv; }, abort: function() { if ( this._request){ this._request.abort(); } } }; } function MessageEvent(type, data, origin, lastEventId) { this.bubbles = false; this.cancelBubble = false; this.cancelable = false; this.data = data || null; this.origin = origin || ''; this.lastEventId = lastEventId || ''; this.type = type || 'message'; } function isOldIE () { //return true if we are in IE8 or IE9 return (window.XDomainRequest && (window.XMLHttpRequest && new XMLHttpRequest().responseType === undefined)) ? true : false; } global[evsImportName] = EventSource; })(this); },{}],42:[function(require,module,exports){ 'use strict'; var isCallable = require('is-callable'); var toStr = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var forEachArray = function forEachArray(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { if (receiver == null) { iterator(array[i], i, array); } else { iterator.call(receiver, array[i], i, array); } } } }; var forEachString = function forEachString(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. if (receiver == null) { iterator(string.charAt(i), i, string); } else { iterator.call(receiver, string.charAt(i), i, string); } } }; var forEachObject = function forEachObject(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { if (receiver == null) { iterator(object[k], k, object); } else { iterator.call(receiver, object[k], k, object); } } } }; var forEach = function forEach(list, iterator, thisArg) { if (!isCallable(iterator)) { throw new TypeError('iterator must be a function'); } var receiver; if (arguments.length >= 3) { receiver = thisArg; } if (toStr.call(list) === '[object Array]') { forEachArray(list, iterator, receiver); } else if (typeof list === 'string') { forEachString(list, iterator, receiver); } else { forEachObject(list, iterator, receiver); } }; module.exports = forEach; },{"is-callable":59}],43:[function(require,module,exports){ 'use strict'; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; },{}],44:[function(require,module,exports){ 'use strict'; var implementation = require('./implementation'); module.exports = Function.prototype.bind || implementation; },{"./implementation":43}],45:[function(require,module,exports){ module.exports = require('./lib-node') },{"./lib-node":46}],46:[function(require,module,exports){ 'use strict'; var pubsub = require('nano-pubsub'); var middlewareReducer = require('./util/middlewareReducer'); var processOptions = require('./middleware/defaultOptionsProcessor'); var validateOptions = require('./middleware/defaultOptionsValidator'); var httpRequest = require('./request'); // node-request in node, browser-request in browsers var channelNames = ['request', 'response', 'progress', 'error', 'abort']; var middlehooks = ['processOptions', 'validateOptions', 'interceptRequest', 'onRequest', 'onResponse', 'onError', 'onReturn', 'onHeaders']; module.exports = function createRequester() { var initMiddleware = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var loadedMiddleware = []; var middleware = middlehooks.reduce(function (ware, name) { ware[name] = ware[name] || []; return ware; }, { processOptions: [processOptions], validateOptions: [validateOptions] }); function request(opts) { var channels = channelNames.reduce(function (target, name) { target[name] = pubsub(); return target; }, {}); // Prepare a middleware reducer that can be reused throughout the lifecycle var applyMiddleware = middlewareReducer(middleware); // Parse the passed options var options = applyMiddleware('processOptions', opts); // Validate the options applyMiddleware('validateOptions', options); // Build a context object we can pass to child handlers var context = { options: options, channels: channels, applyMiddleware: applyMiddleware // We need to hold a reference to the current, ongoing request, // in order to allow cancellation. In the case of the retry middleware, // a new request might be triggered };var ongoingRequest = null; var unsubscribe = channels.request.subscribe(function (ctx) { // Let request adapters (node/browser) perform the actual request ongoingRequest = httpRequest(ctx, function (err, res) { return onResponse(err, res, ctx); }); }); // If we abort the request, prevent further requests from happening, // and be sure to cancel any ongoing request (obviously) channels.abort.subscribe(function () { unsubscribe(); if (ongoingRequest) { ongoingRequest.abort(); } }); // See if any middleware wants to modify the return value - for instance // the promise or observable middlewares var returnValue = applyMiddleware('onReturn', channels, context); // If return value has been modified by a middleware, we expect the middleware // to publish on the 'request' channel. If it hasn't been modified, we want to // trigger it right away if (returnValue === channels) { channels.request.publish(context); } return returnValue; function onResponse(reqErr, res, ctx) { var error = reqErr; var response = res; // We're processing non-errors first, in case a middleware converts the // response into an error (for instance, status >= 400 == HttpError) if (!error) { try { response = applyMiddleware('onResponse', res, ctx); } catch (err) { response = null; error = err; } } // Apply error middleware - if middleware return the same (or a different) error, // publish as an error event. If we *don't* return an error, assume it has been handled error = error && applyMiddleware('onError', error, ctx); // Figure out if we should publish on error/response channels if (error) { channels.error.publish(error); } else if (response) { channels.response.publish(response); } } } request.use = function use(newMiddleware) { if (!newMiddleware) { throw new Error('Tried to add middleware that resolved to falsey value'); } if (typeof newMiddleware === 'function') { throw new Error('Tried to add middleware that was a function. It probably expects you to pass options to it.'); } if (newMiddleware.onReturn && middleware.onReturn.length > 0) { throw new Error('Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event'); } middlehooks.forEach(function (key) { if (newMiddleware[key]) { middleware[key].push(newMiddleware[key]); } }); loadedMiddleware.push(newMiddleware); return request; }; request.clone = function clone() { return createRequester(loadedMiddleware); }; initMiddleware.forEach(request.use); return request; }; },{"./middleware/defaultOptionsProcessor":47,"./middleware/defaultOptionsValidator":48,"./request":55,"./util/middlewareReducer":57,"nano-pubsub":64}],47:[function(require,module,exports){ 'use strict'; var objectAssign = require('object-assign'); var urlParse = require('url-parse'); var isReactNative = typeof navigator === 'undefined' ? false : navigator.product === 'ReactNative'; var has = Object.prototype.hasOwnProperty; var defaultOptions = { timeout: isReactNative ? 60000 : 120000 }; module.exports = function (opts) { var options = typeof opts === 'string' ? objectAssign({ url: opts }, defaultOptions) : objectAssign({}, defaultOptions, opts); // Parse URL into parts var url = urlParse(options.url, {}, // Don't use current browser location true // Parse query strings ); // Normalize timeouts options.timeout = normalizeTimeout(options.timeout); // Shallow-merge (override) existing query params if (options.query) { url.query = objectAssign({}, url.query, removeUndefined(options.query)); } // Implicit POST if we have not specified a method but have a body options.method = options.body && !options.method ? 'POST' : (options.method || 'GET').toUpperCase(); // Stringify URL options.url = url.toString(stringifyQueryString); return options; }; function stringifyQueryString(obj) { var pairs = []; for (var key in obj) { if (has.call(obj, key)) { push(key, obj[key]); } } return pairs.length ? pairs.join('&') : ''; function push(key, val) { if (Array.isArray(val)) { val.forEach(function (item) { return push(key, item); }); } else { pairs.push([key, val].map(encodeURIComponent).join('=')); } } } function normalizeTimeout(time) { if (time === false || time === 0) { return false; } if (time.connect || time.socket) { return time; } var delay = Number(time); if (isNaN(delay)) { return normalizeTimeout(defaultOptions.timeout); } return { connect: delay, socket: delay }; } function removeUndefined(obj) { var target = {}; for (var key in obj) { if (obj[key] !== undefined) { target[key] = obj[key]; } } return target; } },{"object-assign":65,"url-parse":102}],48:[function(require,module,exports){ "use strict"; var validUrl = /^https?:\/\//i; module.exports = function (options) { if (!validUrl.test(options.url)) { throw new Error("\"" + options.url + "\" is not a valid URL"); } }; },{}],49:[function(require,module,exports){ 'use strict'; var _typeof = 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 objectAssign = require('object-assign'); var isPlainObject = require('is-plain-object'); var serializeTypes = ['boolean', 'string', 'number']; var isBuffer = function isBuffer(obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj); }; module.exports = function () { return { processOptions: function processOptions(options) { var body = options.body; if (!body) { return options; } var isStream = typeof body.pipe === 'function'; var shouldSerialize = !isStream && !isBuffer(body) && (serializeTypes.indexOf(typeof body === 'undefined' ? 'undefined' : _typeof(body)) !== -1 || Array.isArray(body) || isPlainObject(body)); if (!shouldSerialize) { return options; } return objectAssign({}, options, { body: JSON.stringify(options.body), headers: objectAssign({}, options.headers, { 'Content-Type': 'application/json' }) }); } }; }; },{"is-plain-object":61,"object-assign":65}],50:[function(require,module,exports){ 'use strict'; var objectAssign = require('object-assign'); module.exports = function (opts) { return { onResponse: function onResponse(response) { var contentType = response.headers['content-type'] || ''; var shouldDecode = opts && opts.force || contentType.indexOf('application/json') !== -1; if (!response.body || !contentType || !shouldDecode) { return response; } return objectAssign({}, response, { body: tryParse(response.body) }); }, processOptions: function processOptions(options) { return objectAssign({}, options, { headers: objectAssign({ Accept: 'application/json' }, options.headers) }); } }; }; function tryParse(body) { try { return JSON.parse(body); } catch (err) { err.message = 'Failed to parsed response body as JSON: ' + err.message; throw err; } } },{"object-assign":65}],51:[function(require,module,exports){ 'use strict'; var global = require('../util/global'); var objectAssign = require('object-assign'); module.exports = function () { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var Observable = opts.implementation || global.Observable; if (!Observable) { throw new Error('`Observable` is not available in global scope, and no implementation was passed'); } return { onReturn: function onReturn(channels, context) { return new Observable(function (observer) { channels.error.subscribe(function (err) { return observer.error(err); }); channels.progress.subscribe(function (event) { return observer.next(objectAssign({ type: 'progress' }, event)); }); channels.response.subscribe(function (response) { observer.next(objectAssign({ type: 'response' }, response)); observer.complete(); }); channels.request.publish(context); return function () { return channels.abort.publish(); }; }); } }; }; },{"../util/global":56,"object-assign":65}],52:[function(require,module,exports){ 'use strict'; module.exports = function () { return { onRequest: function onRequest(evt) { if (evt.adapter !== 'xhr') { return; } var xhr = evt.request; var context = evt.context; if ('upload' in xhr && 'onprogress' in xhr.upload) { xhr.upload.onprogress = handleProgress('upload'); } if ('onprogress' in xhr) { xhr.onprogress = handleProgress('download'); } function handleProgress(stage) { return function (event) { var percent = event.lengthComputable ? event.loaded / event.total * 100 : -1; context.channels.progress.publish({ stage: stage, percent: percent, total: event.total, loaded: event.loaded, lengthComputable: event.lengthComputable }); }; } } }; }; },{}],53:[function(require,module,exports){ 'use strict'; module.exports = require('./node-progress'); },{"./node-progress":52}],54:[function(require,module,exports){ 'use strict'; /* eslint max-depth: ["error", 4] */ var sameOrigin = require('same-origin'); var parseHeaders = require('parse-headers'); var noop = function noop() {/* intentional noop */}; var win = window; var XmlHttpRequest = win.XMLHttpRequest || noop; var hasXhr2 = 'withCredentials' in new XmlHttpRequest(); var XDomainRequest = hasXhr2 ? XmlHttpRequest : win.XDomainRequest; var adapter = 'xhr'; module.exports = function (context, callback) { var options = context.options; var timers = {}; // Deep-checking window.location because of react native, where `location` doesn't exist var cors = win && win.location && !sameOrigin(win.location.href, options.url); // Allow middleware to inject a response, for instance in the case of caching or mocking var injectedResponse = context.applyMiddleware('interceptRequest', undefined, { adapter: adapter, context: context }); // If middleware injected a response, treat it as we normally would and return it // Do note that the injected response has to be reduced to a cross-environment friendly response if (injectedResponse) { var cbTimer = setTimeout(callback, 0, null, injectedResponse); var cancel = function cancel() { return clearTimeout(cbTimer); }; return { abort: cancel }; } // We'll want to null out the request on success/failure var xhr = cors ? new XDomainRequest() : new XmlHttpRequest(); var isXdr = win.XDomainRequest && xhr instanceof win.XDomainRequest; var headers = options.headers; // Request state var aborted = false; var loaded = false; var timedOut = false; // Apply event handlers xhr.onerror = onError; xhr.ontimeout = onError; xhr.onabort = function () { aborted = true; }; // IE9 must have onprogress be set to a unique function xhr.onprogress = function () {/* intentional noop */}; var loadEvent = isXdr ? 'onload' : 'onreadystatechange'; xhr[loadEvent] = function () { // Prevent request from timing out resetTimers(); if (aborted || xhr.readyState !== 4 && !isXdr) { return; } // Will be handled by onError if (xhr.status === 0) { return; } onLoad(); }; // @todo two last options to open() is username/password xhr.open(options.method, options.url, true // Always async ); // Some options need to be applied after open xhr.withCredentials = !!options.withCredentials; // Set headers if (headers && xhr.setRequestHeader) { for (var key in headers) { if (headers.hasOwnProperty(key)) { xhr.setRequestHeader(key, headers[key]); } } } else if (headers && isXdr) { throw new Error('Headers cannot be set on an XDomainRequest object'); } if (options.rawBody) { xhr.responseType = 'arraybuffer'; } // Let middleware know we're about to do a request context.applyMiddleware('onRequest', { options: options, adapter: adapter, request: xhr, context: context }); xhr.send(options.body || null); // Figure out which timeouts to use (if any) var delays = options.timeout; if (delays) { timers.connect = setTimeout(function () { return timeoutRequest('ETIMEDOUT'); }, delays.connect); } return { abort: abort }; function abort() { aborted = true; if (xhr) { xhr.abort(); } } function timeoutRequest(code) { timedOut = true; xhr.abort(); var error = new Error(code === 'ESOCKETTIMEDOUT' ? 'Socket timed out on request to ' + options.url : 'Connection timed out on request to ' + options.url); error.code = code; context.channels.error.publish(error); } function resetTimers() { if (!delays) { return; } stopTimers(); timers.socket = setTimeout(function () { return timeoutRequest('ESOCKETTIMEDOUT'); }, delays.socket); } function stopTimers() { // Only clear the connect timeout if we've got a connection if (aborted || xhr.readyState >= 2 && timers.connect) { clearTimeout(timers.connect); } if (timers.socket) { clearTimeout(timers.socket); } } function onError() { if (loaded) { return; } // Clean up stopTimers(); loaded = true; xhr = null; // Annoyingly, details are extremely scarce and hidden from us. // We only really know that it is a network error var err = new Error('Network error while attempting to reach ' + options.url); err.isNetworkError = true; err.request = options; callback(err); } function reduceResponse() { var statusCode = xhr.status; var statusMessage = xhr.statusText; if (isXdr && statusCode === undefined) { // IE8 CORS GET successful response doesn't have a status field, but body is fine statusCode = 200; } else if (statusCode > 12000 && statusCode < 12156) { // Yet another IE quirk where it emits weird status codes on network errors // https://support.microsoft.com/en-us/kb/193625 return onError(); } else { // Another IE bug where HTTP 204 somehow ends up as 1223 statusCode = xhr.status === 1223 ? 204 : xhr.status; statusMessage = xhr.status === 1223 ? 'No Content' : statusMessage; } return { body: xhr.response || xhr.responseText, url: options.url, method: options.method, headers: isXdr ? {} : parseHeaders(xhr.getAllResponseHeaders()), statusCode: statusCode, statusMessage: statusMessage }; } function onLoad() { if (aborted || loaded || timedOut) { return; } if (xhr.status === 0) { onError(new Error('Unknown XHR error')); return; } // Prevent being called twice stopTimers(); loaded = true; callback(null, reduceResponse()); } }; },{"parse-headers":69,"same-origin":96}],55:[function(require,module,exports){ 'use strict'; module.exports = require('./node-request'); },{"./node-request":54}],56:[function(require,module,exports){ (function (global){ 'use strict'; /* eslint-disable no-negated-condition */ if (typeof window !== 'undefined') { module.exports = window; } else if (typeof global !== 'undefined') { module.exports = global; } else if (typeof self !== 'undefined') { module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],57:[function(require,module,exports){ "use strict"; module.exports = function (middleware) { var applyMiddleware = function applyMiddleware(hook, defaultValue) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } return middleware[hook].reduce(function (value, handler) { return handler.apply(undefined, [value].concat(args)); }, defaultValue); }; return applyMiddleware; }; },{}],58:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); },{"function-bind":44}],59:[function(require,module,exports){ 'use strict'; var fnToStr = Function.prototype.toString; var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { var fnStr = fnToStr.call(value); return constructorRegex.test(fnStr); } catch (e) { return false; // not a function } }; var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var fnClass = '[object Function]'; var genClass = '[object GeneratorFunction]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isCallable(value) { if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (typeof value === 'function' && !value.prototype) { return true; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr.call(value); return strClass === fnClass || strClass === genClass; }; },{}],60:[function(require,module,exports){ 'use strict'; module.exports = function (x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); }; },{}],61:[function(require,module,exports){ /*! * is-plain-object * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ 'use strict'; var isObject = require('isobject'); function isObjectObject(o) { return isObject(o) === true && Object.prototype.toString.call(o) === '[object Object]'; } module.exports = function isPlainObject(o) { var ctor,prot; if (isObjectObject(o) === false) return false; // If has modified constructor ctor = o.constructor; if (typeof ctor !== 'function') return false; // If has modified prototype prot = ctor.prototype; if (isObjectObject(prot) === false) return false; // If constructor does not have an Object-specific method if (prot.hasOwnProperty('isPrototypeOf') === false) { return false; } // Most likely a plain Object return true; }; },{"isobject":62}],62:[function(require,module,exports){ /*! * isobject * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ 'use strict'; module.exports = function isObject(val) { return val != null && typeof val === 'object' && Array.isArray(val) === false; }; },{}],63:[function(require,module,exports){ // ISC @ Julien Fontanet 'use strict' // =================================================================== var construct = typeof Reflect !== 'undefined' ? Reflect.construct : undefined var defineProperty = Object.defineProperty // ------------------------------------------------------------------- var captureStackTrace = Error.captureStackTrace if (captureStackTrace === undefined) { captureStackTrace = function captureStackTrace (error) { var container = new Error() defineProperty(error, 'stack', { configurable: true, get: function getStack () { var stack = container.stack // Replace property with value for faster future accesses. defineProperty(this, 'stack', { configurable: true, value: stack, writable: true }) return stack }, set: function setStack (stack) { defineProperty(error, 'stack', { configurable: true, value: stack, writable: true }) } }) } } // ------------------------------------------------------------------- function BaseError (message) { if (message !== undefined) { defineProperty(this, 'message', { configurable: true, value: message, writable: true }) } var cname = this.constructor.name if ( cname !== undefined && cname !== this.name ) { defineProperty(this, 'name', { configurable: true, value: cname, writable: true }) } captureStackTrace(this, this.constructor) } BaseError.prototype = Object.create(Error.prototype, { // See: https://github.com/JsCommunity/make-error/issues/4 constructor: { configurable: true, value: BaseError, writable: true } }) // ------------------------------------------------------------------- // Sets the name of a function if possible (depends of the JS engine). var setFunctionName = (function () { function setFunctionName (fn, name) { return defineProperty(fn, 'name', { configurable: true, value: name }) } try { var f = function () {} setFunctionName(f, 'foo') if (f.name === 'foo') { return setFunctionName } } catch (_) {} })() // ------------------------------------------------------------------- function makeError (constructor, super_) { if (super_ == null || super_ === Error) { super_ = BaseError } else if (typeof super_ !== 'function') { throw new TypeError('super_ should be a function') } var name if (typeof constructor === 'string') { name = constructor constructor = construct !== undefined ? function () { return construct(super_, arguments, this.constructor) } : function () { super_.apply(this, arguments) } // If the name can be set, do it once and for all. if (setFunctionName !== undefined) { setFunctionName(constructor, name) name = undefined } } else if (typeof constructor !== 'function') { throw new TypeError('constructor should be either a string or a function') } // Also register the super constructor also as `constructor.super_` just // like Node's `util.inherits()`. constructor.super_ = constructor['super'] = super_ var properties = { constructor: { configurable: true, value: constructor, writable: true } } // If the name could not be set on the constructor, set it on the // prototype. if (name !== undefined) { properties.name = { configurable: true, value: name, writable: true } } constructor.prototype = Object.create(super_.prototype, properties) return constructor } exports = module.exports = makeError exports.BaseError = BaseError },{}],64:[function(require,module,exports){ module.exports = function Pubsub() { var subscribers = [] return { subscribe: subscribe, publish: publish } function subscribe(subscriber) { subscribers.push(subscriber) return function unsubscribe() { var idx = subscribers.indexOf(subscriber) if (idx > -1) { subscribers.splice(idx, 1) } } } function publish() { for (var i = 0; i < subscribers.length; i++) { subscribers[i].apply(null, arguments) } } } },{}],65:[function(require,module,exports){ /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}],66:[function(require,module,exports){ 'use strict'; var keysShim; if (!Object.keys) { // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var isArgs = require('./isArguments'); // eslint-disable-line global-require var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $onmozfullscreenchange: true, $onmozfullscreenerror: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; } module.exports = keysShim; },{"./isArguments":68}],67:[function(require,module,exports){ 'use strict'; var slice = Array.prototype.slice; var isArgs = require('./isArguments'); var origKeys = Object.keys; var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); var originalKeys = Object.keys; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug var args = Object.keys(arguments); return args && args.length === arguments.length; }(1, 2)); if (!keysWorksWithArguments) { Object.keys = function keys(object) { // eslint-disable-line func-name-matching if (isArgs(object)) { return originalKeys(slice.call(object)); } return originalKeys(object); }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; },{"./implementation":66,"./isArguments":68}],68:[function(require,module,exports){ 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; },{}],69:[function(require,module,exports){ var trim = require('string.prototype.trim') , forEach = require('for-each') , isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } module.exports = function (headers) { if (!headers) return {} var result = {} forEach( trim(headers).split('\n') , function (row) { var index = row.indexOf(':') , key = trim(row.slice(0, index)).toLowerCase() , value = trim(row.slice(index + 1)) if (typeof(result[key]) === 'undefined') { result[key] = value } else if (isArray(result[key])) { result[key].push(value) } else { result[key] = [ result[key], value ] } } ) return result } },{"for-each":42,"string.prototype.trim":99}],70:[function(require,module,exports){ 'use strict'; var has = Object.prototype.hasOwnProperty , undef; /** * Decode a URI encoded string. * * @param {String} input The URI encoded string. * @returns {String|Null} The decoded string. * @api private */ function decode(input) { try { return decodeURIComponent(input.replace(/\+/g, ' ')); } catch (e) { return null; } } /** * Attempts to encode a given input. * * @param {String} input The string that needs to be encoded. * @returns {String|Null} The encoded string. * @api private */ function encode(input) { try { return encodeURIComponent(input); } catch (e) { return null; } } /** * Simple query string parser. * * @param {String} query The query string that needs to be parsed. * @returns {Object} * @api public */ function querystring(query) { var parser = /([^=?&]+)=?([^&]*)/g , result = {} , part; while (part = parser.exec(query)) { var key = decode(part[1]) , value = decode(part[2]); // // Prevent overriding of existing properties. This ensures that build-in // methods like `toString` or __proto__ are not overriden by malicious // querystrings. // // In the case if failed decoding, we want to omit the key/value pairs // from the result. // if (key === null || value === null || key in result) continue; result[key] = value; } return result; } /** * Transform a query string to an object. * * @param {Object} obj Object that should be transformed. * @param {String} prefix Optional prefix. * @returns {String} * @api public */ function querystringify(obj, prefix) { prefix = prefix || ''; var pairs = [] , value , key; // // Optionally prefix with a '?' if needed // if ('string' !== typeof prefix) prefix = '?'; for (key in obj) { if (has.call(obj, key)) { value = obj[key]; // // Edge cases where we actually want to encode the value to an empty // string instead of the stringified value. // if (!value && (value === null || value === undef || isNaN(value))) { value = ''; } key = encodeURIComponent(key); value = encodeURIComponent(value); // // If we failed to encode the strings, we should bail out as we don't // want to add invalid strings to the query. // if (key === null || value === null) continue; pairs.push(key +'='+ value); } } return pairs.length ? prefix + pairs.join('&') : ''; } // // Expose the module. // exports.stringify = querystringify; exports.parse = querystring; },{}],71:[function(require,module,exports){ 'use strict'; /** * Check if we're required to add a port number. * * @see https://url.spec.whatwg.org/#default-port * @param {Number|String} port Port number we need to check * @param {String} protocol Protocol we need to check against. * @returns {Boolean} Is it a default port for the given protocol * @api private */ module.exports = function required(port, protocol) { protocol = protocol.split(':')[0]; port = +port; if (!port) return false; switch (protocol) { case 'http': case 'ws': return port !== 80; case 'https': case 'wss': return port !== 443; case 'ftp': return port !== 21; case 'gopher': return port !== 70; case 'file': return false; } return port !== 0; }; },{}],72:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var canReportError_1 = require("./util/canReportError"); var toSubscriber_1 = require("./util/toSubscriber"); var observable_1 = require("./symbol/observable"); var pipe_1 = require("./util/pipe"); var config_1 = require("./config"); var Observable = (function () { function Observable(subscribe) { this._isScalar = false; if (subscribe) { this._subscribe = subscribe; } } Observable.prototype.lift = function (operator) { var observable = new Observable(); observable.source = this; observable.operator = operator; return observable; }; Observable.prototype.subscribe = function (observerOrNext, error, complete) { var operator = this.operator; var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete); if (operator) { sink.add(operator.call(sink, this.source)); } else { sink.add(this.source || (config_1.config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? this._subscribe(sink) : this._trySubscribe(sink)); } if (config_1.config.useDeprecatedSynchronousErrorHandling) { if (sink.syncErrorThrowable) { sink.syncErrorThrowable = false; if (sink.syncErrorThrown) { throw sink.syncErrorValue; } } } return sink; }; Observable.prototype._trySubscribe = function (sink) { try { return this._subscribe(sink); } catch (err) { if (config_1.config.useDeprecatedSynchronousErrorHandling) { sink.syncErrorThrown = true; sink.syncErrorValue = err; } if (canReportError_1.canReportError(sink)) { sink.error(err); } else { console.warn(err); } } }; Observable.prototype.forEach = function (next, promiseCtor) { var _this = this; promiseCtor = getPromiseCtor(promiseCtor); return new promiseCtor(function (resolve, reject) { var subscription; subscription = _this.subscribe(function (value) { try { next(value); } catch (err) { reject(err); if (subscription) { subscription.unsubscribe(); } } }, reject, resolve); }); }; Observable.prototype._subscribe = function (subscriber) { var source = this.source; return source && source.subscribe(subscriber); }; Observable.prototype[observable_1.observable] = function () { return this; }; Observable.prototype.pipe = function () { var operations = []; for (var _i = 0; _i < arguments.length; _i++) { operations[_i] = arguments[_i]; } if (operations.length === 0) { return this; } return pipe_1.pipeFromArray(operations)(this); }; Observable.prototype.toPromise = function (promiseCtor) { var _this = this; promiseCtor = getPromiseCtor(promiseCtor); return new promiseCtor(function (resolve, reject) { var value; _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); }); }; Observable.create = function (subscribe) { return new Observable(subscribe); }; return Observable; }()); exports.Observable = Observable; function getPromiseCtor(promiseCtor) { if (!promiseCtor) { promiseCtor = config_1.config.Promise || Promise; } if (!promiseCtor) { throw new Error('no Promise impl found'); } return promiseCtor; } },{"./config":76,"./symbol/observable":84,"./util/canReportError":88,"./util/pipe":94,"./util/toSubscriber":95}],73:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var config_1 = require("./config"); var hostReportError_1 = require("./util/hostReportError"); exports.empty = { closed: true, next: function (value) { }, error: function (err) { if (config_1.config.useDeprecatedSynchronousErrorHandling) { throw err; } else { hostReportError_1.hostReportError(err); } }, complete: function () { } }; },{"./config":76,"./util/hostReportError":89}],74:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var isFunction_1 = require("./util/isFunction"); var Observer_1 = require("./Observer"); var Subscription_1 = require("./Subscription"); var rxSubscriber_1 = require("../internal/symbol/rxSubscriber"); var config_1 = require("./config"); var hostReportError_1 = require("./util/hostReportError"); var Subscriber = (function (_super) { __extends(Subscriber, _super); function Subscriber(destinationOrNext, error, complete) { var _this = _super.call(this) || this; _this.syncErrorValue = null; _this.syncErrorThrown = false; _this.syncErrorThrowable = false; _this.isStopped = false; switch (arguments.length) { case 0: _this.destination = Observer_1.empty; break; case 1: if (!destinationOrNext) { _this.destination = Observer_1.empty; break; } if (typeof destinationOrNext === 'object') { if (destinationOrNext instanceof Subscriber) { _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; _this.destination = destinationOrNext; destinationOrNext.add(_this); } else { _this.syncErrorThrowable = true; _this.destination = new SafeSubscriber(_this, destinationOrNext); } break; } default: _this.syncErrorThrowable = true; _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); break; } return _this; } Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; }; Subscriber.create = function (next, error, complete) { var subscriber = new Subscriber(next, error, complete); subscriber.syncErrorThrowable = false; return subscriber; }; Subscriber.prototype.next = function (value) { if (!this.isStopped) { this._next(value); } }; Subscriber.prototype.error = function (err) { if (!this.isStopped) { this.isStopped = true; this._error(err); } }; Subscriber.prototype.complete = function () { if (!this.isStopped) { this.isStopped = true; this._complete(); } }; Subscriber.prototype.unsubscribe = function () { if (this.closed) { return; } this.isStopped = true; _super.prototype.unsubscribe.call(this); }; Subscriber.prototype._next = function (value) { this.destination.next(value); }; Subscriber.prototype._error = function (err) { this.destination.error(err); this.unsubscribe(); }; Subscriber.prototype._complete = function () { this.destination.complete(); this.unsubscribe(); }; Subscriber.prototype._unsubscribeAndRecycle = function () { var _parentOrParents = this._parentOrParents; this._parentOrParents = null; this.unsubscribe(); this.closed = false; this.isStopped = false; this._parentOrParents = _parentOrParents; return this; }; return Subscriber; }(Subscription_1.Subscription)); exports.Subscriber = Subscriber; var SafeSubscriber = (function (_super) { __extends(SafeSubscriber, _super); function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { var _this = _super.call(this) || this; _this._parentSubscriber = _parentSubscriber; var next; var context = _this; if (isFunction_1.isFunction(observerOrNext)) { next = observerOrNext; } else if (observerOrNext) { next = observerOrNext.next; error = observerOrNext.error; complete = observerOrNext.complete; if (observerOrNext !== Observer_1.empty) { context = Object.create(observerOrNext); if (isFunction_1.isFunction(context.unsubscribe)) { _this.add(context.unsubscribe.bind(context)); } context.unsubscribe = _this.unsubscribe.bind(_this); } } _this._context = context; _this._next = next; _this._error = error; _this._complete = complete; return _this; } SafeSubscriber.prototype.next = function (value) { if (!this.isStopped && this._next) { var _parentSubscriber = this._parentSubscriber; if (!config_1.config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { this.__tryOrUnsub(this._next, value); } else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { this.unsubscribe(); } } }; SafeSubscriber.prototype.error = function (err) { if (!this.isStopped) { var _parentSubscriber = this._parentSubscriber; var useDeprecatedSynchronousErrorHandling = config_1.config.useDeprecatedSynchronousErrorHandling; if (this._error) { if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { this.__tryOrUnsub(this._error, err); this.unsubscribe(); } else { this.__tryOrSetError(_parentSubscriber, this._error, err); this.unsubscribe(); } } else if (!_parentSubscriber.syncErrorThrowable) { this.unsubscribe(); if (useDeprecatedSynchronousErrorHandling) { throw err; } hostReportError_1.hostReportError(err); } else { if (useDeprecatedSynchronousErrorHandling) { _parentSubscriber.syncErrorValue = err; _parentSubscriber.syncErrorThrown = true; } else { hostReportError_1.hostReportError(err); } this.unsubscribe(); } } }; SafeSubscriber.prototype.complete = function () { var _this = this; if (!this.isStopped) { var _parentSubscriber = this._parentSubscriber; if (this._complete) { var wrappedComplete = function () { return _this._complete.call(_this._context); }; if (!config_1.config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { this.__tryOrUnsub(wrappedComplete); this.unsubscribe(); } else { this.__tryOrSetError(_parentSubscriber, wrappedComplete); this.unsubscribe(); } } else { this.unsubscribe(); } } }; SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { try { fn.call(this._context, value); } catch (err) { this.unsubscribe(); if (config_1.config.useDeprecatedSynchronousErrorHandling) { throw err; } else { hostReportError_1.hostReportError(err); } } }; SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { if (!config_1.config.useDeprecatedSynchronousErrorHandling) { throw new Error('bad call'); } try { fn.call(this._context, value); } catch (err) { if (config_1.config.useDeprecatedSynchronousErrorHandling) { parent.syncErrorValue = err; parent.syncErrorThrown = true; return true; } else { hostReportError_1.hostReportError(err); return true; } } return false; }; SafeSubscriber.prototype._unsubscribe = function () { var _parentSubscriber = this._parentSubscriber; this._context = null; this._parentSubscriber = null; _parentSubscriber.unsubscribe(); }; return SafeSubscriber; }(Subscriber)); exports.SafeSubscriber = SafeSubscriber; },{"../internal/symbol/rxSubscriber":85,"./Observer":73,"./Subscription":75,"./config":76,"./util/hostReportError":89,"./util/isFunction":91}],75:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var isArray_1 = require("./util/isArray"); var isObject_1 = require("./util/isObject"); var isFunction_1 = require("./util/isFunction"); var UnsubscriptionError_1 = require("./util/UnsubscriptionError"); var Subscription = (function () { function Subscription(unsubscribe) { this.closed = false; this._parentOrParents = null; this._subscriptions = null; if (unsubscribe) { this._unsubscribe = unsubscribe; } } Subscription.prototype.unsubscribe = function () { var errors; if (this.closed) { return; } var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; this.closed = true; this._parentOrParents = null; this._subscriptions = null; if (_parentOrParents instanceof Subscription) { _parentOrParents.remove(this); } else if (_parentOrParents !== null) { for (var index = 0; index < _parentOrParents.length; ++index) { var parent_1 = _parentOrParents[index]; parent_1.remove(this); } } if (isFunction_1.isFunction(_unsubscribe)) { try { _unsubscribe.call(this); } catch (e) { errors = e instanceof UnsubscriptionError_1.UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; } } if (isArray_1.isArray(_subscriptions)) { var index = -1; var len = _subscriptions.length; while (++index < len) { var sub = _subscriptions[index]; if (isObject_1.isObject(sub)) { try { sub.unsubscribe(); } catch (e) { errors = errors || []; if (e instanceof UnsubscriptionError_1.UnsubscriptionError) { errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); } else { errors.push(e); } } } } } if (errors) { throw new UnsubscriptionError_1.UnsubscriptionError(errors); } }; Subscription.prototype.add = function (teardown) { var subscription = teardown; if (!teardown) { return Subscription.EMPTY; } switch (typeof teardown) { case 'function': subscription = new Subscription(teardown); case 'object': if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { return subscription; } else if (this.closed) { subscription.unsubscribe(); return subscription; } else if (!(subscription instanceof Subscription)) { var tmp = subscription; subscription = new Subscription(); subscription._subscriptions = [tmp]; } break; default: { throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); } } var _parentOrParents = subscription._parentOrParents; if (_parentOrParents === null) { subscription._parentOrParents = this; } else if (_parentOrParents instanceof Subscription) { if (_parentOrParents === this) { return subscription; } subscription._parentOrParents = [_parentOrParents, this]; } else if (_parentOrParents.indexOf(this) === -1) { _parentOrParents.push(this); } else { return subscription; } var subscriptions = this._subscriptions; if (subscriptions === null) { this._subscriptions = [subscription]; } else { subscriptions.push(subscription); } return subscription; }; Subscription.prototype.remove = function (subscription) { var subscriptions = this._subscriptions; if (subscriptions) { var subscriptionIndex = subscriptions.indexOf(subscription); if (subscriptionIndex !== -1) { subscriptions.splice(subscriptionIndex, 1); } } }; Subscription.EMPTY = (function (empty) { empty.closed = true; return empty; }(new Subscription())); return Subscription; }()); exports.Subscription = Subscription; function flattenUnsubscriptionErrors(errors) { return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []); } },{"./util/UnsubscriptionError":87,"./util/isArray":90,"./util/isFunction":91,"./util/isObject":92}],76:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _enable_super_gross_mode_that_will_cause_bad_things = false; exports.config = { Promise: undefined, set useDeprecatedSynchronousErrorHandling(value) { if (value) { var error = new Error(); console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); } else if (_enable_super_gross_mode_that_will_cause_bad_things) { console.log('RxJS: Back to a better error behavior. Thank you. <3'); } _enable_super_gross_mode_that_will_cause_bad_things = value; }, get useDeprecatedSynchronousErrorHandling() { return _enable_super_gross_mode_that_will_cause_bad_things; }, }; },{}],77:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("../Observable"); exports.EMPTY = new Observable_1.Observable(function (subscriber) { return subscriber.complete(); }); function empty(scheduler) { return scheduler ? emptyScheduled(scheduler) : exports.EMPTY; } exports.empty = empty; function emptyScheduled(scheduler) { return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); }); } },{"../Observable":72}],78:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var Subscriber_1 = require("../Subscriber"); function defaultIfEmpty(defaultValue) { if (defaultValue === void 0) { defaultValue = null; } return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); }; } exports.defaultIfEmpty = defaultIfEmpty; var DefaultIfEmptyOperator = (function () { function DefaultIfEmptyOperator(defaultValue) { this.defaultValue = defaultValue; } DefaultIfEmptyOperator.prototype.call = function (subscriber, source) { return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue)); }; return DefaultIfEmptyOperator; }()); var DefaultIfEmptySubscriber = (function (_super) { __extends(DefaultIfEmptySubscriber, _super); function DefaultIfEmptySubscriber(destination, defaultValue) { var _this = _super.call(this, destination) || this; _this.defaultValue = defaultValue; _this.isEmpty = true; return _this; } DefaultIfEmptySubscriber.prototype._next = function (value) { this.isEmpty = false; this.destination.next(value); }; DefaultIfEmptySubscriber.prototype._complete = function () { if (this.isEmpty) { this.destination.next(this.defaultValue); } this.destination.complete(); }; return DefaultIfEmptySubscriber; }(Subscriber_1.Subscriber)); },{"../Subscriber":74}],79:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var Subscriber_1 = require("../Subscriber"); function filter(predicate, thisArg) { return function filterOperatorFunction(source) { return source.lift(new FilterOperator(predicate, thisArg)); }; } exports.filter = filter; var FilterOperator = (function () { function FilterOperator(predicate, thisArg) { this.predicate = predicate; this.thisArg = thisArg; } FilterOperator.prototype.call = function (subscriber, source) { return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); }; return FilterOperator; }()); var FilterSubscriber = (function (_super) { __extends(FilterSubscriber, _super); function FilterSubscriber(destination, predicate, thisArg) { var _this = _super.call(this, destination) || this; _this.predicate = predicate; _this.thisArg = thisArg; _this.count = 0; return _this; } FilterSubscriber.prototype._next = function (value) { var result; try { result = this.predicate.call(this.thisArg, value, this.count++); } catch (err) { this.destination.error(err); return; } if (result) { this.destination.next(value); } }; return FilterSubscriber; }(Subscriber_1.Subscriber)); },{"../Subscriber":74}],80:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var Subscriber_1 = require("../Subscriber"); function map(project, thisArg) { return function mapOperation(source) { if (typeof project !== 'function') { throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); } return source.lift(new MapOperator(project, thisArg)); }; } exports.map = map; var MapOperator = (function () { function MapOperator(project, thisArg) { this.project = project; this.thisArg = thisArg; } MapOperator.prototype.call = function (subscriber, source) { return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); }; return MapOperator; }()); exports.MapOperator = MapOperator; var MapSubscriber = (function (_super) { __extends(MapSubscriber, _super); function MapSubscriber(destination, project, thisArg) { var _this = _super.call(this, destination) || this; _this.project = project; _this.count = 0; _this.thisArg = thisArg || _this; return _this; } MapSubscriber.prototype._next = function (value) { var result; try { result = this.project.call(this.thisArg, value, this.count++); } catch (err) { this.destination.error(err); return; } this.destination.next(result); }; return MapSubscriber; }(Subscriber_1.Subscriber)); },{"../Subscriber":74}],81:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var scan_1 = require("./scan"); var takeLast_1 = require("./takeLast"); var defaultIfEmpty_1 = require("./defaultIfEmpty"); var pipe_1 = require("../util/pipe"); function reduce(accumulator, seed) { if (arguments.length >= 2) { return function reduceOperatorFunctionWithSeed(source) { return pipe_1.pipe(scan_1.scan(accumulator, seed), takeLast_1.takeLast(1), defaultIfEmpty_1.defaultIfEmpty(seed))(source); }; } return function reduceOperatorFunction(source) { return pipe_1.pipe(scan_1.scan(function (acc, value, index) { return accumulator(acc, value, index + 1); }), takeLast_1.takeLast(1))(source); }; } exports.reduce = reduce; },{"../util/pipe":94,"./defaultIfEmpty":78,"./scan":82,"./takeLast":83}],82:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var Subscriber_1 = require("../Subscriber"); function scan(accumulator, seed) { var hasSeed = false; if (arguments.length >= 2) { hasSeed = true; } return function scanOperatorFunction(source) { return source.lift(new ScanOperator(accumulator, seed, hasSeed)); }; } exports.scan = scan; var ScanOperator = (function () { function ScanOperator(accumulator, seed, hasSeed) { if (hasSeed === void 0) { hasSeed = false; } this.accumulator = accumulator; this.seed = seed; this.hasSeed = hasSeed; } ScanOperator.prototype.call = function (subscriber, source) { return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); }; return ScanOperator; }()); var ScanSubscriber = (function (_super) { __extends(ScanSubscriber, _super); function ScanSubscriber(destination, accumulator, _seed, hasSeed) { var _this = _super.call(this, destination) || this; _this.accumulator = accumulator; _this._seed = _seed; _this.hasSeed = hasSeed; _this.index = 0; return _this; } Object.defineProperty(ScanSubscriber.prototype, "seed", { get: function () { return this._seed; }, set: function (value) { this.hasSeed = true; this._seed = value; }, enumerable: true, configurable: true }); ScanSubscriber.prototype._next = function (value) { if (!this.hasSeed) { this.seed = value; this.destination.next(value); } else { return this._tryNext(value); } }; ScanSubscriber.prototype._tryNext = function (value) { var index = this.index++; var result; try { result = this.accumulator(this.seed, value, index); } catch (err) { this.destination.error(err); } this.seed = result; this.destination.next(result); }; return ScanSubscriber; }(Subscriber_1.Subscriber)); },{"../Subscriber":74}],83:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var Subscriber_1 = require("../Subscriber"); var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError"); var empty_1 = require("../observable/empty"); function takeLast(count) { return function takeLastOperatorFunction(source) { if (count === 0) { return empty_1.empty(); } else { return source.lift(new TakeLastOperator(count)); } }; } exports.takeLast = takeLast; var TakeLastOperator = (function () { function TakeLastOperator(total) { this.total = total; if (this.total < 0) { throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError; } } TakeLastOperator.prototype.call = function (subscriber, source) { return source.subscribe(new TakeLastSubscriber(subscriber, this.total)); }; return TakeLastOperator; }()); var TakeLastSubscriber = (function (_super) { __extends(TakeLastSubscriber, _super); function TakeLastSubscriber(destination, total) { var _this = _super.call(this, destination) || this; _this.total = total; _this.ring = new Array(); _this.count = 0; return _this; } TakeLastSubscriber.prototype._next = function (value) { var ring = this.ring; var total = this.total; var count = this.count++; if (ring.length < total) { ring.push(value); } else { var index = count % total; ring[index] = value; } }; TakeLastSubscriber.prototype._complete = function () { var destination = this.destination; var count = this.count; if (count > 0) { var total = this.count >= this.total ? this.total : this.count; var ring = this.ring; for (var i = 0; i < total; i++) { var idx = (count++) % total; destination.next(ring[idx]); } } destination.complete(); }; return TakeLastSubscriber; }(Subscriber_1.Subscriber)); },{"../Subscriber":74,"../observable/empty":77,"../util/ArgumentOutOfRangeError":86}],84:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.observable = typeof Symbol === 'function' && Symbol.observable || '@@observable'; },{}],85:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.rxSubscriber = typeof Symbol === 'function' ? Symbol('rxSubscriber') : '@@rxSubscriber_' + Math.random(); exports.$$rxSubscriber = exports.rxSubscriber; },{}],86:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function ArgumentOutOfRangeErrorImpl() { Error.call(this); this.message = 'argument out of range'; this.name = 'ArgumentOutOfRangeError'; return this; } ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype); exports.ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl; },{}],87:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function UnsubscriptionErrorImpl(errors) { Error.call(this); this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; this.name = 'UnsubscriptionError'; this.errors = errors; return this; } UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype); exports.UnsubscriptionError = UnsubscriptionErrorImpl; },{}],88:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Subscriber_1 = require("../Subscriber"); function canReportError(observer) { while (observer) { var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; if (closed_1 || isStopped) { return false; } else if (destination && destination instanceof Subscriber_1.Subscriber) { observer = destination; } else { observer = null; } } return true; } exports.canReportError = canReportError; },{"../Subscriber":74}],89:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function hostReportError(err) { setTimeout(function () { throw err; }, 0); } exports.hostReportError = hostReportError; },{}],90:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); },{}],91:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isFunction(x) { return typeof x === 'function'; } exports.isFunction = isFunction; },{}],92:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isObject(x) { return x !== null && typeof x === 'object'; } exports.isObject = isObject; },{}],93:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function noop() { } exports.noop = noop; },{}],94:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var noop_1 = require("./noop"); function pipe() { var fns = []; for (var _i = 0; _i < arguments.length; _i++) { fns[_i] = arguments[_i]; } return pipeFromArray(fns); } exports.pipe = pipe; function pipeFromArray(fns) { if (!fns) { return noop_1.noop; } if (fns.length === 1) { return fns[0]; } return function piped(input) { return fns.reduce(function (prev, fn) { return fn(prev); }, input); }; } exports.pipeFromArray = pipeFromArray; },{"./noop":93}],95:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Subscriber_1 = require("../Subscriber"); var rxSubscriber_1 = require("../symbol/rxSubscriber"); var Observer_1 = require("../Observer"); function toSubscriber(nextOrObserver, error, complete) { if (nextOrObserver) { if (nextOrObserver instanceof Subscriber_1.Subscriber) { return nextOrObserver; } if (nextOrObserver[rxSubscriber_1.rxSubscriber]) { return nextOrObserver[rxSubscriber_1.rxSubscriber](); } } if (!nextOrObserver && !error && !complete) { return new Subscriber_1.Subscriber(Observer_1.empty); } return new Subscriber_1.Subscriber(nextOrObserver, error, complete); } exports.toSubscriber = toSubscriber; },{"../Observer":73,"../Subscriber":74,"../symbol/rxSubscriber":85}],96:[function(require,module,exports){ 'use strict'; var url = require('url'); module.exports = function(uri1, uri2, ieMode) { if (uri1 === uri2) { return true; } var url1 = url.parse(uri1, false, true); var url2 = url.parse(uri2, false, true); var url1Port = url1.port|0 || (url1.protocol === 'https' ? 443 : 80); var url2Port = url2.port|0 || (url2.protocol === 'https' ? 443 : 80); var match = { proto: url1.protocol === url2.protocol, hostname: url1.hostname === url2.hostname, port: url1Port === url2Port }; return ((match.proto && match.hostname) && (match.port || ieMode)); }; },{"url":97}],97:[function(require,module,exports){ /** * This file is only used for the browser version of `same-origin`. * Used to bring down the size of the browser bundle. */ 'use strict'; var regex = /^(?:(?:(?:([^:\/#\?]+:)?(?:(?:\/\/)((?:((?:[^:@\/#\?]+)(?:\:(?:[^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((?:\/?(?:[^\/\?#]+\/+)*)(?:[^\?#]*)))?(\?[^#]+)?)(#.*)?/; module.exports = { regex: regex, parse: function(url) { var match = regex.exec(url); if (!match) { return {}; } return { protocol: (match[1] || '').toLowerCase() || undefined, hostname: (match[5] || '').toLowerCase() || undefined, port: match[6] || undefined }; } }; },{}],98:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); var ES = require('es-abstract/es5'); var replace = bind.call(Function.call, String.prototype.replace); /* eslint-disable no-control-regex */ var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/; var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/; /* eslint-enable no-control-regex */ module.exports = function trim() { var S = ES.ToString(ES.CheckObjectCoercible(this)); return replace(replace(S, leftWhitespace, ''), rightWhitespace, ''); }; },{"es-abstract/es5":33,"function-bind":44}],99:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); var define = require('define-properties'); var implementation = require('./implementation'); var getPolyfill = require('./polyfill'); var shim = require('./shim'); var boundTrim = bind.call(Function.call, getPolyfill()); define(boundTrim, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = boundTrim; },{"./implementation":98,"./polyfill":100,"./shim":101,"define-properties":31,"function-bind":44}],100:[function(require,module,exports){ 'use strict'; var implementation = require('./implementation'); var zeroWidthSpace = '\u200b'; module.exports = function getPolyfill() { if (String.prototype.trim && zeroWidthSpace.trim() === zeroWidthSpace) { return String.prototype.trim; } return implementation; }; },{"./implementation":98}],101:[function(require,module,exports){ 'use strict'; var define = require('define-properties'); var getPolyfill = require('./polyfill'); module.exports = function shimStringTrim() { var polyfill = getPolyfill(); define(String.prototype, { trim: polyfill }, { trim: function testTrim() { return String.prototype.trim !== polyfill; } }); return polyfill; }; },{"./polyfill":100,"define-properties":31}],102:[function(require,module,exports){ (function (global){ 'use strict'; var required = require('requires-port') , qs = require('querystringify') , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\// , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i , whitespace = '[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]' , left = new RegExp('^'+ whitespace +'+'); /** * Trim a given string. * * @param {String} str String to trim. * @public */ function trimLeft(str) { return (str ? str : '').toString().replace(left, ''); } /** * These are the parse rules for the URL parser, it informs the parser * about: * * 0. The char it Needs to parse, if it's a string it should be done using * indexOf, RegExp using exec and NaN means set as current value. * 1. The property we should set when parsing this value. * 2. Indication if it's backwards or forward parsing, when set as number it's * the value of extra chars that should be split off. * 3. Inherit from location if non existing in the parser. * 4. `toLowerCase` the resulting value. */ var rules = [ ['#', 'hash'], // Extract from the back. ['?', 'query'], // Extract from the back. function sanitize(address) { // Sanitize what is left of the address return address.replace('\\', '/'); }, ['/', 'pathname'], // Extract from the back. ['@', 'auth', 1], // Extract from the front. [NaN, 'host', undefined, 1, 1], // Set left over value. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back. [NaN, 'hostname', undefined, 1, 1] // Set left over. ]; /** * These properties should not be copied or inherited from. This is only needed * for all non blob URL's as a blob URL does not include a hash, only the * origin. * * @type {Object} * @private */ var ignore = { hash: 1, query: 1 }; /** * The location object differs when your code is loaded through a normal page, * Worker or through a worker using a blob. And with the blobble begins the * trouble as the location object will contain the URL of the blob, not the * location of the page where our code is loaded in. The actual origin is * encoded in the `pathname` so we can thankfully generate a good "default" * location from it so we can generate proper relative URL's again. * * @param {Object|String} loc Optional default location object. * @returns {Object} lolcation object. * @public */ function lolcation(loc) { var globalVar; if (typeof window !== 'undefined') globalVar = window; else if (typeof global !== 'undefined') globalVar = global; else if (typeof self !== 'undefined') globalVar = self; else globalVar = {}; var location = globalVar.location || {}; loc = loc || location; var finaldestination = {} , type = typeof loc , key; if ('blob:' === loc.protocol) { finaldestination = new Url(unescape(loc.pathname), {}); } else if ('string' === type) { finaldestination = new Url(loc, {}); for (key in ignore) delete finaldestination[key]; } else if ('object' === type) { for (key in loc) { if (key in ignore) continue; finaldestination[key] = loc[key]; } if (finaldestination.slashes === undefined) { finaldestination.slashes = slashes.test(loc.href); } } return finaldestination; } /** * @typedef ProtocolExtract * @type Object * @property {String} protocol Protocol matched in the URL, in lowercase. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`. * @property {String} rest Rest of the URL that is not part of the protocol. */ /** * Extract protocol information from a URL with/without double slash ("//"). * * @param {String} address URL we want to extract from. * @return {ProtocolExtract} Extracted information. * @private */ function extractProtocol(address) { address = trimLeft(address); var match = protocolre.exec(address); return { protocol: match[1] ? match[1].toLowerCase() : '', slashes: !!match[2], rest: match[3] }; } /** * Resolve a relative URL pathname against a base URL pathname. * * @param {String} relative Pathname of the relative URL. * @param {String} base Pathname of the base URL. * @return {String} Resolved pathname. * @private */ function resolve(relative, base) { if (relative === '') return base; var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) , i = path.length , last = path[i - 1] , unshift = false , up = 0; while (i--) { if (path[i] === '.') { path.splice(i, 1); } else if (path[i] === '..') { path.splice(i, 1); up++; } else if (up) { if (i === 0) unshift = true; path.splice(i, 1); up--; } } if (unshift) path.unshift(''); if (last === '.' || last === '..') path.push(''); return path.join('/'); } /** * The actual URL instance. Instead of returning an object we've opted-in to * create an actual constructor as it's much more memory efficient and * faster and it pleases my OCD. * * It is worth noting that we should not use `URL` as class name to prevent * clashes with the global URL instance that got introduced in browsers. * * @constructor * @param {String} address URL we want to parse. * @param {Object|String} [location] Location defaults for relative paths. * @param {Boolean|Function} [parser] Parser for the query string. * @private */ function Url(address, location, parser) { address = trimLeft(address); if (!(this instanceof Url)) { return new Url(address, location, parser); } var relative, extracted, parse, instruction, index, key , instructions = rules.slice() , type = typeof location , url = this , i = 0; // // The following if statements allows this module two have compatibility with // 2 different API: // // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments // where the boolean indicates that the query string should also be parsed. // // 2. The `URL` interface of the browser which accepts a URL, object as // arguments. The supplied object will be used as default values / fall-back // for relative paths. // if ('object' !== type && 'string' !== type) { parser = location; location = null; } if (parser && 'function' !== typeof parser) parser = qs.parse; location = lolcation(location); // // Extract protocol information before running the instructions. // extracted = extractProtocol(address || ''); relative = !extracted.protocol && !extracted.slashes; url.slashes = extracted.slashes || relative && location.slashes; url.protocol = extracted.protocol || location.protocol || ''; address = extracted.rest; // // When the authority component is absent the URL starts with a path // component. // if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname']; for (; i < instructions.length; i++) { instruction = instructions[i]; if (typeof instruction === 'function') { address = instruction(address); continue; } parse = instruction[0]; key = instruction[1]; if (parse !== parse) { url[key] = address; } else if ('string' === typeof parse) { if (~(index = address.indexOf(parse))) { if ('number' === typeof instruction[2]) { url[key] = address.slice(0, index); address = address.slice(index + instruction[2]); } else { url[key] = address.slice(index); address = address.slice(0, index); } } } else if ((index = parse.exec(address))) { url[key] = index[1]; address = address.slice(0, index.index); } url[key] = url[key] || ( relative && instruction[3] ? location[key] || '' : '' ); // // Hostname, host and protocol should be lowercased so they can be used to // create a proper `origin`. // if (instruction[4]) url[key] = url[key].toLowerCase(); } // // Also parse the supplied query string in to an object. If we're supplied // with a custom parser as function use that instead of the default build-in // parser. // if (parser) url.query = parser(url.query); // // If the URL is relative, resolve the pathname against the base URL. // if ( relative && location.slashes && url.pathname.charAt(0) !== '/' && (url.pathname !== '' || location.pathname !== '') ) { url.pathname = resolve(url.pathname, location.pathname); } // // We should not add port numbers if they are already the default port number // for a given protocol. As the host also contains the port number we're going // override it with the hostname which contains no port number. // if (!required(url.port, url.protocol)) { url.host = url.hostname; url.port = ''; } // // Parse down the `auth` for the username and password. // url.username = url.password = ''; if (url.auth) { instruction = url.auth.split(':'); url.username = instruction[0] || ''; url.password = instruction[1] || ''; } url.origin = url.protocol && url.host && url.protocol !== 'file:' ? url.protocol +'//'+ url.host : 'null'; // // The href is just the compiled result. // url.href = url.toString(); } /** * This is convenience method for changing properties in the URL instance to * insure that they all propagate correctly. * * @param {String} part Property we need to adjust. * @param {Mixed} value The newly assigned value. * @param {Boolean|Function} fn When setting the query, it will be the function * used to parse the query. * When setting the protocol, double slash will be * removed from the final url if it is true. * @returns {URL} URL instance for chaining. * @public */ function set(part, value, fn) { var url = this; switch (part) { case 'query': if ('string' === typeof value && value.length) { value = (fn || qs.parse)(value); } url[part] = value; break; case 'port': url[part] = value; if (!required(value, url.protocol)) { url.host = url.hostname; url[part] = ''; } else if (value) { url.host = url.hostname +':'+ value; } break; case 'hostname': url[part] = value; if (url.port) value += ':'+ url.port; url.host = value; break; case 'host': url[part] = value; if (/:\d+$/.test(value)) { value = value.split(':'); url.port = value.pop(); url.hostname = value.join(':'); } else { url.hostname = value; url.port = ''; } break; case 'protocol': url.protocol = value.toLowerCase(); url.slashes = !fn; break; case 'pathname': case 'hash': if (value) { var char = part === 'pathname' ? '/' : '#'; url[part] = value.charAt(0) !== char ? char + value : value; } else { url[part] = value; } break; default: url[part] = value; } for (var i = 0; i < rules.length; i++) { var ins = rules[i]; if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); } url.origin = url.protocol && url.host && url.protocol !== 'file:' ? url.protocol +'//'+ url.host : 'null'; url.href = url.toString(); return url; } /** * Transform the properties back in to a valid and full URL string. * * @param {Function} stringify Optional query stringify function. * @returns {String} Compiled version of the URL. * @public */ function toString(stringify) { if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; var query , url = this , protocol = url.protocol; if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; var result = protocol + (url.slashes ? '//' : ''); if (url.username) { result += url.username; if (url.password) result += ':'+ url.password; result += '@'; } result += url.host + url.pathname; query = 'object' === typeof url.query ? stringify(url.query) : url.query; if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; if (url.hash) result += url.hash; return result; } Url.prototype = { set: set, toString: toString }; // // Expose the URL parser and some additional properties that might be useful for // others or testing. // Url.extractProtocol = extractProtocol; Url.location = lolcation; Url.trimLeft = trimLeft; Url.qs = qs; module.exports = Url; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"querystringify":70,"requires-port":71}],103:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const sanityClient = require("@sanity/client"); const getClient = () => sanityClient({ projectId: 'v475t82f', dataset: 'production' }); const getReleaseNotes = () => { const query = '*[_type == "release"] | order(version desc)'; const client = getClient(); return client.fetch(query); }; const renderTemplate = (posts) => { return `${posts.reduce((acc, { version, title, fixed, new: newItems, breaking }) => acc.concat(`
${version}

${title}

    ${fixed.reduce((accc, src) => src.length > 0 ? accc.concat(`
  • ${src}
  • `) : '', '')} ${newItems.reduce((accc, src) => src.length > 0 ? accc.concat(`
  • ${src}
  • `) : '', '')} ${breaking.reduce((accc, src) => src.length > 0 ? accc.concat(`
  • ${src}
  • `) : '', '')}
`), '')}`; }; getReleaseNotes().then((res) => { const normalized = res.reduce((acc, src) => acc.concat(Object.assign({}, src, { fixed: src.fixed ? src.fixed.map(item => item.children[0].text) : [], new: src.new ? src.new.map(item => item.children[0].text) : [], breaking: src.breaking ? src.breaking.map(item => item.children[0].text) : [] })), []); document.querySelector('.Container').innerHTML = renderTemplate(normalized); }); },{"@sanity/client":16}]},{},[103]);