blast-graph-angular2
Version:
 **with** 
1,908 lines (1,893 loc) • 189 kB
JavaScript
import { Subject, BehaviorSubject } from 'rxjs/index';
import { __extends } from 'tslib';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var BlastHelpers = /** @class */ (function () {
function BlastHelpers() {
}
/**
* @param {?} obj
* @return {?}
*/
BlastHelpers.isPresent = /**
* @param {?} obj
* @return {?}
*/
function (obj) {
return obj !== undefined && obj !== null;
};
/**
* @param {?} obj
* @return {?}
*/
BlastHelpers.isString = /**
* @param {?} obj
* @return {?}
*/
function (obj) {
return typeof obj === 'string';
};
/**
* @param {?} obj
* @return {?}
*/
BlastHelpers.isArray = /**
* @param {?} obj
* @return {?}
*/
function (obj) {
return Array.isArray(obj);
};
/**
* @param {?} obj
* @return {?}
*/
BlastHelpers.isFunction = /**
* @param {?} obj
* @return {?}
*/
function (obj) {
return typeof obj === 'function';
};
/**
* @param {?} obj
* @return {?}
*/
BlastHelpers.isJson = /**
* @param {?} obj
* @return {?}
*/
function (obj) {
try {
JSON.parse(obj);
return true;
}
catch (exception) {
return false;
}
};
return BlastHelpers;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** @type {?} */
var BLAST_VERSION = '0.0.1';
/** @type {?} */
var LOG_LEVEL = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3
};
var BlastService = /** @class */ (function () {
function BlastService(url, connectNow, protocols, config) {
this.url = url;
this.protocols = protocols;
this.config = config;
this.reconnectAttempts = 0;
this.sendQueue = [];
this.onMessageCallbacks = [];
this.onOpenCallbacks = [];
this.onErrorCallbacks = [];
this.onCloseCallbacks = [];
this.readyStateConstants = {
'CONNECTING': 0,
'OPEN': 1,
'CLOSING': 2,
'CLOSED': 3,
'RECONNECT_ABORTED': 4
};
this.normalCloseCode = 1000;
this.reconnectableStatusCodes = [4000];
this.logLevel = LOG_LEVEL.ERROR;
/** @type {?} */
var match = new RegExp('wss?:\/\/').test(url);
if (!match) {
throw new Error('Invalid url provided');
}
this.config = config || { initialTimeout: 500, maxTimeout: 300000, reconnectIfNotNormalClose: true };
this.dataStream = new Subject();
if (connectNow === undefined || connectNow) {
this.connect(true);
}
}
/**
* @param {?=} force
* @return {?}
*/
BlastService.prototype.connect = /**
* @param {?=} force
* @return {?}
*/
function (force) {
var _this = this;
if (force === void 0) { force = false; }
/** @type {?} */
var self = this;
if (force || !this.socket || this.socket.readyState !== this.readyStateConstants.OPEN) {
self.socket = this.protocols ? new WebSocket(this.url, this.protocols) : new WebSocket(this.url);
self.socket.onopen = function (ev) {
_this.onOpenHandler(ev);
};
self.socket.onmessage = function (ev) {
if (BlastHelpers.isJson(ev.data)) {
/** @type {?} */
var message = JSON.parse(ev.data);
_this.debug('BlastService', 'jsonMessage', 'passing to handlers', ev.data);
// call a json message handler - if true, then message handled mustn't carry on
if (self.handleJsonMessage(message) === true) {
return;
}
}
self.onMessageHandler(ev.data);
_this.dataStream.next(ev.data);
};
this.socket.onclose = function (ev) {
self.onCloseHandler(ev);
};
this.socket.onerror = function (ev) {
self.onErrorHandler(ev);
_this.dataStream.error(ev);
};
}
};
/**
* Run in Block Mode
* Return true when can send and false in socket closed
* @param {?} data
* @param {?=} binary
* @return {?}
*/
BlastService.prototype.sendMessage = /**
* Run in Block Mode
* Return true when can send and false in socket closed
* @param {?} data
* @param {?=} binary
* @return {?}
*/
function (data, binary) {
/** @type {?} */
var self = this;
if (this.getReadyState() !== this.readyStateConstants.OPEN
&& this.getReadyState() !== this.readyStateConstants.CONNECTING) {
this.connect();
}
this.debug('BlastService', 'sendMessage', data);
self.sendQueue.push({ message: data, binary: binary });
if (self.socket.readyState === self.readyStateConstants.OPEN) {
self.fireQueue();
return true;
}
else {
return false;
}
};
/**
* Use {mode} mode to send {data} data
* If no specify, Default SendMode is Observable mode
* @param data
* @param mode
* @param binary
* @returns
*/
/**
* Use {mode} mode to send {data} data
* If no specify, Default SendMode is Observable mode
* @param {?} data
* @param {?=} binary
* @return {?}
*/
BlastService.prototype.send = /**
* Use {mode} mode to send {data} data
* If no specify, Default SendMode is Observable mode
* @param {?} data
* @param {?=} binary
* @return {?}
*/
function (data, binary) {
return this.sendMessage(data, binary);
};
/**
* @return {?}
*/
BlastService.prototype.getDataStream = /**
* @return {?}
*/
function () {
return this.dataStream;
};
/**
* @param {?} event
* @return {?}
*/
BlastService.prototype.notifyOpenCallbacks = /**
* @param {?} event
* @return {?}
*/
function (event) {
for (var i = 0; i < this.onOpenCallbacks.length; i++) {
this.onOpenCallbacks[i].call(this, event);
}
};
/**
* @return {?}
*/
BlastService.prototype.fireQueue = /**
* @return {?}
*/
function () {
while (this.sendQueue.length && this.socket.readyState === this.readyStateConstants.OPEN) {
/** @type {?} */
var data = this.sendQueue.shift();
if (data.binary) {
this.socket.send(data.message);
}
else {
this.socket.send(BlastHelpers.isString(data.message) ? data.message : JSON.stringify(data.message));
}
}
};
/**
* @param {?} event
* @return {?}
*/
BlastService.prototype.notifyCloseCallbacks = /**
* @param {?} event
* @return {?}
*/
function (event) {
for (var i = 0; i < this.onCloseCallbacks.length; i++) {
this.onCloseCallbacks[i].call(this, event);
}
};
/**
* @param {?} event
* @return {?}
*/
BlastService.prototype.notifyErrorCallbacks = /**
* @param {?} event
* @return {?}
*/
function (event) {
for (var i = 0; i < this.onErrorCallbacks.length; i++) {
this.onErrorCallbacks[i].call(this, event);
}
};
/**
* @param {?} cb
* @return {?}
*/
BlastService.prototype.onOpen = /**
* @param {?} cb
* @return {?}
*/
function (cb) {
this.onOpenCallbacks.push(cb);
return this;
};
/**
* @param {?} cb
* @return {?}
*/
BlastService.prototype.onClose = /**
* @param {?} cb
* @return {?}
*/
function (cb) {
this.onCloseCallbacks.push(cb);
return this;
};
/**
* @param {?} cb
* @return {?}
*/
BlastService.prototype.onError = /**
* @param {?} cb
* @return {?}
*/
function (cb) {
this.onErrorCallbacks.push(cb);
return this;
};
/**
* @param {?} callback
* @param {?=} options
* @return {?}
*/
BlastService.prototype.onMessage = /**
* @param {?} callback
* @param {?=} options
* @return {?}
*/
function (callback, options) {
if (!BlastHelpers.isFunction(callback)) {
throw new Error('Callback must be a function');
}
this.onMessageCallbacks.push({
fn: callback,
pattern: options ? options.filter : undefined,
autoApply: options ? options.autoApply : true
});
return this;
};
/**
* @param {?} message
* @return {?}
*/
BlastService.prototype.handleJsonMessage = /**
* @param {?} message
* @return {?}
*/
function (message) {
// as a default return false i.e. don't change message flow
// enables extended classes to override this function
return false;
};
/**
* @param {?} message
* @return {?}
*/
BlastService.prototype.onMessageHandler = /**
* @param {?} message
* @return {?}
*/
function (message) {
this.debug('BlastService', 'onMessageHandler', message.data);
/** @type {?} */
var self = this;
/** @type {?} */
var currentCallback;
for (var i = 0; i < self.onMessageCallbacks.length; i++) {
currentCallback = self.onMessageCallbacks[i];
currentCallback.fn.apply(self, [message]);
}
};
/**
* @param {?} event
* @return {?}
*/
BlastService.prototype.onOpenHandler = /**
* @param {?} event
* @return {?}
*/
function (event) {
this.debug('BlastService', 'connected');
this.reconnectAttempts = 0;
this.notifyOpenCallbacks(event);
this.fireQueue();
};
/**
* @param {?} event
* @return {?}
*/
BlastService.prototype.onCloseHandler = /**
* @param {?} event
* @return {?}
*/
function (event) {
this.debug('BlastService', 'closed');
this.notifyCloseCallbacks(event);
if ((this.config.reconnectIfNotNormalClose && event.code !== this.normalCloseCode)
|| this.reconnectableStatusCodes.indexOf(event.code) > -1) {
this.reconnect();
}
else {
this.sendQueue = [];
this.dataStream.complete();
}
};
/**
* @param {?} event
* @return {?}
*/
BlastService.prototype.onErrorHandler = /**
* @param {?} event
* @return {?}
*/
function (event) {
this.debug('BlastService', 'onErrorHandler', event);
this.notifyErrorCallbacks(event);
};
/**
* @return {?}
*/
BlastService.prototype.reconnect = /**
* @return {?}
*/
function () {
var _this = this;
this.close(true);
/** @type {?} */
var backoffDelay = this.getBackoffDelay(++this.reconnectAttempts);
// let backoffDelaySeconds = backoffDelay / 1000;
// // console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds');
this.debug('BlastService', 'reconnectDelay', backoffDelay);
setTimeout(function () { return _this.connect(); }, backoffDelay);
return this;
};
/**
* @param {?=} force
* @return {?}
*/
BlastService.prototype.close = /**
* @param {?=} force
* @return {?}
*/
function (force) {
if (force === void 0) { force = false; }
if (force || !this.socket.bufferedAmount) {
this.socket.close(this.normalCloseCode);
}
return this;
};
/**
* @param {?} attempt
* @return {?}
*/
BlastService.prototype.getBackoffDelay = /**
* @param {?} attempt
* @return {?}
*/
function (attempt) {
/** @type {?} */
var R = Math.random() + 1;
/** @type {?} */
var T = this.config.initialTimeout;
/** @type {?} */
var F = 2;
/** @type {?} */
var N = attempt;
/** @type {?} */
var M = this.config.maxTimeout;
return Math.floor(Math.min(R * T * Math.pow(F, N), M));
};
/**
* @param {?} state
* @return {?}
*/
BlastService.prototype.setInternalState = /**
* @param {?} state
* @return {?}
*/
function (state) {
if (Math.floor(state) !== state || state < 0 || state > 4) {
throw new Error('state must be an integer between 0 and 4, got: ' + state);
}
this.internalConnectionState = state;
};
/**
* Could be -1 if not initzialized yet
* @returns
*/
/**
* Could be -1 if not initzialized yet
* @return {?}
*/
BlastService.prototype.getReadyState = /**
* Could be -1 if not initzialized yet
* @return {?}
*/
function () {
if (this.socket == null) {
return -1;
}
return this.internalConnectionState || this.socket.readyState;
};
/**
* @return {?}
*/
BlastService.prototype.getVersion = /**
* @return {?}
*/
function () {
return BLAST_VERSION;
};
/**
* @return {?}
*/
BlastService.prototype.hasConsole = /**
* @return {?}
*/
function () {
if (console === undefined) {
return false;
}
return true;
};
/**
* @param {...?} args
* @return {?}
*/
BlastService.prototype.debug = /**
* @param {...?} args
* @return {?}
*/
function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this.hasConsole() && this.logLevel < 1) {
console.debug.apply(console, args);
}
};
/**
* @param {...?} args
* @return {?}
*/
BlastService.prototype.info = /**
* @param {...?} args
* @return {?}
*/
function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this.hasConsole() && this.logLevel < 2) {
console.debug.apply(console, args);
}
};
/**
* @param {...?} args
* @return {?}
*/
BlastService.prototype.warn = /**
* @param {...?} args
* @return {?}
*/
function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this.hasConsole() && this.logLevel < 4) {
console.debug.apply(console, args);
}
};
/**
* @param {...?} args
* @return {?}
*/
BlastService.prototype.error = /**
* @param {...?} args
* @return {?}
*/
function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
console.error.apply(console, args);
};
/**
* @param {?} level
* @return {?}
*/
BlastService.prototype.setLogLevel = /**
* @param {?} level
* @return {?}
*/
function (level) {
this.logLevel = level;
};
return BlastService;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var BlastException = /** @class */ (function () {
function BlastException(message) {
this.message = message;
}
return BlastException;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var PathDetails = /** @class */ (function () {
function PathDetails() {
}
/**
* @param {?} key
* @return {?}
*/
PathDetails.splitPath = /**
* @param {?} key
* @return {?}
*/
function (key) {
/** @type {?} */
var details = [];
if (key === null || key.trim().length === 0 || key === 'root') {
/** @type {?} */
var tmpPathDetails = new PathDetails();
tmpPathDetails.setRoot();
tmpPathDetails.setNotCollectionOnly();
details.push(tmpPathDetails);
return details;
}
if (key.startsWith('/')) {
throw new BlastException('key cannot start with / - must specify collection e.g. collection/keyname:value');
}
/** @type {?} */
var splits = key.split('/');
if (splits[0].includes(':')) {
throw new BlastException('must specify collection e.g. collection/keyname:value');
}
// check if it is collection only
if (splits.length === 1) {
/** @type {?} */
var tmpPathDetails = new PathDetails();
tmpPathDetails.setNotRoot();
tmpPathDetails.setCollection(key);
tmpPathDetails.setCollectionOnly();
details.push(tmpPathDetails);
return details;
}
/** @type {?} */
var pathDetails = new PathDetails();
pathDetails.setNotRoot();
pathDetails.setCollection(splits[0]);
details.push(pathDetails);
for (var x = 1; x < splits.length; x++) {
if (splits[x].includes(':')) {
/** @type {?} */
var keySplit = splits[x].split(':');
if (keySplit.length !== 2) {
throw new BlastException('look up must be in form keyname:value - found: ' + splits[x]);
}
pathDetails.setKeyField(keySplit[0]);
pathDetails.setKeyValue(keySplit[1]);
pathDetails.setNotCollectionOnly();
}
else {
if (splits[x].startsWith('?')) {
pathDetails.setQueryParams(splits[x].substring(1).split(','));
}
else {
pathDetails = new PathDetails();
pathDetails.setNotRoot();
pathDetails.setCollectionOnly();
pathDetails.setCollection(splits[x]);
details.push(pathDetails);
}
}
}
return details;
};
/**
* @return {?}
*/
PathDetails.prototype.setRoot = /**
* @return {?}
*/
function () {
this._isRoot = true;
this._collection = 'root';
};
/**
* @return {?}
*/
PathDetails.prototype.setNotRoot = /**
* @return {?}
*/
function () {
this._isRoot = false;
};
/**
* @param {?} collection
* @return {?}
*/
PathDetails.prototype.setCollection = /**
* @param {?} collection
* @return {?}
*/
function (collection) {
this._collection = collection;
};
/**
* @return {?}
*/
PathDetails.prototype.setCollectionOnly = /**
* @return {?}
*/
function () {
this._isCollectionOnly = true;
};
/**
* @return {?}
*/
PathDetails.prototype.setNotCollectionOnly = /**
* @return {?}
*/
function () {
this._isCollectionOnly = false;
};
/**
* @param {?} keyField
* @return {?}
*/
PathDetails.prototype.setKeyField = /**
* @param {?} keyField
* @return {?}
*/
function (keyField) {
this._keyField = keyField;
};
/**
* @param {?} keyValue
* @return {?}
*/
PathDetails.prototype.setKeyValue = /**
* @param {?} keyValue
* @return {?}
*/
function (keyValue) {
this._keyValue = keyValue;
};
/**
* @param {?} params
* @return {?}
*/
PathDetails.prototype.setQueryParams = /**
* @param {?} params
* @return {?}
*/
function (params) {
this._queryParams = params;
};
/**
* @return {?}
*/
PathDetails.prototype.getCollection = /**
* @return {?}
*/
function () {
return this._collection;
};
/**
* @return {?}
*/
PathDetails.prototype.getKeyField = /**
* @return {?}
*/
function () {
return this._keyField;
};
/**
* @return {?}
*/
PathDetails.prototype.getKeyValue = /**
* @return {?}
*/
function () {
return this._keyValue;
};
/**
* @return {?}
*/
PathDetails.prototype.getQueryParams = /**
* @return {?}
*/
function () {
return this._queryParams;
};
/**
* @return {?}
*/
PathDetails.prototype.isRoot = /**
* @return {?}
*/
function () {
return this._isRoot;
};
/**
* @return {?}
*/
PathDetails.prototype.isCollectionOnly = /**
* @return {?}
*/
function () {
return this._isCollectionOnly;
};
return PathDetails;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var GraphRequest = /** @class */ (function () {
function GraphRequest(command, key, data, pathParameters, attachmentId) {
if (!key) {
PathDetails.splitPath(key);
}
this._command = command;
this._key = key;
this._data = data;
this._pathParameters = pathParameters;
this._attachmentId = attachmentId;
}
/**
* @param {?} command
* @return {?}
*/
GraphRequest.prototype.setCommand = /**
* @param {?} command
* @return {?}
*/
function (command) {
this._command = command;
};
/**
* @param {?} key
* @return {?}
*/
GraphRequest.prototype.setKey = /**
* @param {?} key
* @return {?}
*/
function (key) {
this._key = key;
};
/**
* @param {?} pathParameters
* @return {?}
*/
GraphRequest.prototype.setParameters = /**
* @param {?} pathParameters
* @return {?}
*/
function (pathParameters) {
this._pathParameters = pathParameters;
};
/**
* @param {?} data
* @return {?}
*/
GraphRequest.prototype.setData = /**
* @param {?} data
* @return {?}
*/
function (data) {
this._data = data;
};
/**
* @param {?} collection
* @return {?}
*/
GraphRequest.prototype.setCollection = /**
* @param {?} collection
* @return {?}
*/
function (collection) {
this._collection = collection;
};
/**
* @param {?} collectionList
* @return {?}
*/
GraphRequest.prototype.setCollectionList = /**
* @param {?} collectionList
* @return {?}
*/
function (collectionList) {
this._collectionList = collectionList;
};
/**
* @param {?} correlationId
* @param {?} onFulFilled
* @param {?} onError
* @return {?}
*/
GraphRequest.prototype.setCorrelationInfo = /**
* @param {?} correlationId
* @param {?} onFulFilled
* @param {?} onError
* @return {?}
*/
function (correlationId, onFulFilled, onError) {
this._correlationId = correlationId;
this._onFulFilled = onFulFilled;
this._onError = onError;
this._requestTime = new Date().getTime();
};
/**
* @return {?}
*/
GraphRequest.prototype.getMessage = /**
* @return {?}
*/
function () {
/** @type {?} */
var message = {
cmd: this._command,
correlationId: this._correlationId
};
if (this._key) {
message['key'] = this._key;
}
if (this._pathParameters) {
message['parameters'] = this._pathParameters.getParameters();
}
if (this._attachmentId) {
message['attachmentId'] = this._attachmentId;
}
if (this._data) {
message['data'] = this._data;
}
return message;
};
return GraphRequest;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var CollectionTraversor = /** @class */ (function () {
function CollectionTraversor() {
}
/**
* @param {?} path
* @param {?} data
* @return {?}
*/
CollectionTraversor.findList = /**
* @param {?} path
* @param {?} data
* @return {?}
*/
function (path, data) {
// console.log('path',path,'data',data);
if (Object.prototype.toString.call(data) === '[object Array]') {
return this.traverseUntilFinalList(path, data);
}
else {
/** @type {?} */
var pathDetails = PathDetails.splitPath(path);
if (pathDetails.length === 1 && pathDetails[0].getKeyField() === undefined) {
return data[pathDetails[0].getCollection()];
}
/** @type {?} */
var resultList = [];
for (var index = 0; index < pathDetails.length; index++) {
if (pathDetails[index].getKeyField() === undefined) {
resultList = data[pathDetails[index].getCollection()];
}
else {
data = this.findARecord(index, pathDetails, data);
}
}
return resultList === undefined ? [] : resultList;
}
};
/**
* @param {?} path
* @param {?} data
* @return {?}
*/
CollectionTraversor.findRecord = /**
* @param {?} path
* @param {?} data
* @return {?}
*/
function (path, data) {
if (Object.prototype.toString.call(data) === '[object Array]') {
return this.traverseUntilFinalRecord(path, data);
}
else {
/** @type {?} */
var pathDetails = PathDetails.splitPath(path);
for (var index = 0; index < pathDetails.length; index++) {
data = this.findARecord(index, pathDetails, data);
}
return data;
}
};
/**
* @param {?} keyField
* @param {?} keyValue
* @param {?} list
* @return {?}
*/
CollectionTraversor.findRecordInList = /**
* @param {?} keyField
* @param {?} keyValue
* @param {?} list
* @return {?}
*/
function (keyField, keyValue, list) {
if (list !== undefined) {
for (var index = 0; index < list.length; index++) {
/** @type {?} */
var id = list[index][keyField];
if (id !== undefined) {
if (this.matches(id, keyValue)) {
return list[index];
}
}
}
}
throw new BlastException('[findRecordInList] failed to find record - field [' + keyField + ' ] value [' + keyValue + ']');
};
/**
* @param {?} keyField
* @param {?} keyValue
* @param {?} list
* @return {?}
*/
CollectionTraversor.findRecordIndexInList = /**
* @param {?} keyField
* @param {?} keyValue
* @param {?} list
* @return {?}
*/
function (keyField, keyValue, list) {
if (list !== undefined) {
for (var index = 0; index < list.length; index++) {
/** @type {?} */
var id = list[index][keyField];
if (id !== undefined) {
if (this.matches(id, keyValue)) {
return index;
}
}
}
}
throw new BlastException('[findRecordIndexInList] failed to find record - field [' + keyField + ' ] value [' + keyValue + ']');
};
/**
* @param {?} index
* @param {?} pathDetails
* @param {?} dataSubset
* @return {?}
*/
CollectionTraversor.findARecord = /**
* @param {?} index
* @param {?} pathDetails
* @param {?} dataSubset
* @return {?}
*/
function (index, pathDetails, dataSubset) {
/** @type {?} */
var list = dataSubset[pathDetails[index].getCollection()];
return this.findRecordInList(pathDetails[index].getKeyField(), pathDetails[index].getKeyValue(), list);
};
/**
* @param {?} path
* @param {?} list
* @return {?}
*/
CollectionTraversor.traverseUntilFinalRecord = /**
* @param {?} path
* @param {?} list
* @return {?}
*/
function (path, list) {
/** @type {?} */
var pathDetails = PathDetails.splitPath(path);
/** @type {?} */
var data = this.findRecordInList(pathDetails[0].getKeyField(), pathDetails[0].getKeyValue(), list);
for (var index = 1; index < pathDetails.length; index++) {
data = this.findARecord(index, pathDetails, data);
}
return data;
};
/**
* @param {?} path
* @param {?} list
* @return {?}
*/
CollectionTraversor.traverseUntilFinalList = /**
* @param {?} path
* @param {?} list
* @return {?}
*/
function (path, list) {
/** @type {?} */
var pathDetails = PathDetails.splitPath(path);
// asking for a list with no details so return original list
if (pathDetails[0].getKeyField() === undefined) {
return list;
}
/** @type {?} */
var resultList = [];
/** @type {?} */
var data = this.findRecordInList(pathDetails[0].getKeyField(), pathDetails[0].getKeyValue(), list);
for (var index = 1; index < pathDetails.length; index++) {
// there is no key field or we are on last path element
if (pathDetails[index].getKeyField() === undefined || index === pathDetails.length - 1) {
resultList = data[pathDetails[index].getCollection()];
}
else {
data = this.findARecord(index, pathDetails, data);
}
}
return resultList === undefined ? [] : resultList;
};
/**
* @param {?} one
* @param {?} two
* @return {?}
*/
CollectionTraversor.matches = /**
* @param {?} one
* @param {?} two
* @return {?}
*/
function (one, two) {
if (typeof (one) === 'number') {
if (typeof (two) === 'number') {
return one === two;
}
else {
return one === Number(two);
}
}
else {
if (typeof (two) === 'string') {
return one === two;
}
else {
return one === String(two);
}
}
};
return CollectionTraversor;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** @type {?} */
var Operation = {
ADD: 'ADD',
UPDATE: 'UPDATE',
REMOVE: 'REMOVE'
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var Instruction = /** @class */ (function () {
function Instruction(jsonObject) {
this._operation = jsonObject['operation'];
this._path = jsonObject['path'];
this._collection = jsonObject['collection'];
this._changes = jsonObject['changes'];
this._record = jsonObject['record'];
}
/**
* @return {?}
*/
Instruction.prototype.getOperation = /**
* @return {?}
*/
function () {
return this._operation;
};
/**
* @return {?}
*/
Instruction.prototype.getPath = /**
* @return {?}
*/
function () {
return this._path;
};
/**
* @return {?}
*/
Instruction.prototype.getCollection = /**
* @return {?}
*/
function () {
return this._collection;
};
/**
* @return {?}
*/
Instruction.prototype.getChanges = /**
* @return {?}
*/
function () {
return this._changes;
};
/**
* @return {?}
*/
Instruction.prototype.getRecord = /**
* @return {?}
*/
function () {
return this._record;
};
return Instruction;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** @type {?} */
var GraphMessageType = {
GRAPH_ADD_RESPONSE: 'graph-add',
GRAPH_UPDATE_RESPONSE: 'graph-update',
GRAPH_REMOVE_RESPONSE: 'graph-remove',
GRAPH_INITIAL_LOAD_RESPONSE: 'graph-attach',
GRAPH_FETCH_RESPONSE: 'graph-fetch',
GRAPH_SCHEMA_RESPONSE: 'graph-schema',
GRAPH_CLIENT_ATTACHMENTS_RESPONSE: 'graph-current_attachments',
GRAPH_OK_RESPONSE: 'ok',
GRAPH_FAIL_RESPONSE: 'fail',
GRAPH_DETACH_RESPONSE: 'graph-detach',
GRAPH_DETACH_ALL_RESPONSE: 'graph-detach_all'
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var GraphResponseMessage = /** @class */ (function () {
function GraphResponseMessage(jsonObject) {
if (jsonObject['graphMessageType'] === undefined) {
throw new BlastException('not a graph response message');
}
this._graphMessageType = jsonObject['graphMessageType'];
if (GraphMessageType[this._graphMessageType] === undefined) {
throw new BlastException('not a valid graph response message type');
}
this._correlationId = jsonObject['correlationId'];
this._key = jsonObject['key'];
if (jsonObject['instruction']) {
this._instruction = new Instruction(jsonObject['instruction']);
}
this._data = jsonObject['data'];
this._status = jsonObject['status'];
this._cmd = jsonObject['cmd'];
this._attachmentId = jsonObject['attachmentId'];
this._graphMessageType = jsonObject['graphMessageType'];
}
/**
* @return {?}
*/
GraphResponseMessage.prototype.getCorrelationId = /**
* @return {?}
*/
function () {
return this._correlationId;
};
/**
* @return {?}
*/
GraphResponseMessage.prototype.getKey = /**
* @return {?}
*/
function () {
return this._key;
};
/**
* @return {?}
*/
GraphResponseMessage.prototype.getInstruction = /**
* @return {?}
*/
function () {
return this._instruction;
};
/**
* @return {?}
*/
GraphResponseMessage.prototype.getData = /**
* @return {?}
*/
function () {
return this._data;
};
/**
* @return {?}
*/
GraphResponseMessage.prototype.getStatus = /**
* @return {?}
*/
function () {
return this._status;
};
/**
* @return {?}
*/
GraphResponseMessage.prototype.getGraphMessageType = /**
* @return {?}
*/
function () {
return this._graphMessageType;
};
/**
* @return {?}
*/
GraphResponseMessage.prototype.getCommand = /**
* @return {?}
*/
function () {
return this._cmd;
};
/**
* @return {?}
*/
GraphResponseMessage.prototype.getAttachmentId = /**
* @return {?}
*/
function () {
return this._attachmentId;
};
return GraphResponseMessage;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var Attachment = /** @class */ (function () {
function Attachment(attachmentId, key, logService) {
this._key = key;
this._attachmentId = attachmentId;
this._loadStream = new Subject();
this._addStream = new Subject();
this._changeStream = new Subject();
this._removeStream = new Subject();
this._tickStream = new Subject();
this._logService = logService;
}
/**
* @return {?}
*/
Attachment.prototype.isList = /**
* @return {?}
*/
function () {
return this._isList;
};
/**
* @return {?}
*/
Attachment.prototype.getAttachmentId = /**
* @return {?}
*/
function () {
return this._attachmentId;
};
/**
* @return {?}
*/
Attachment.prototype.getKey = /**
* @return {?}
*/
function () {
return this._key;
};
/**
* @return {?}
*/
Attachment.prototype.getData = /**
* @return {?}
*/
function () {
return this._data;
};
/**
* @return {?}
*/
Attachment.prototype.getListData = /**
* @return {?}
*/
function () {
return this._listData;
};
/**
* @param {?} data
* @return {?}
*/
Attachment.prototype.setData = /**
* @param {?} data
* @return {?}
*/
function (data) {
if (data === undefined) {
this._data = {};
}
else {
this._data = data;
}
this._isList = false;
};
/**
* @param {?} data
* @return {?}
*/
Attachment.prototype.setListData = /**
* @param {?} data
* @return {?}
*/
function (data) {
if (data === undefined) {
this._listData = [];
}
else {
this._listData = data;
}
this._isList = true;
};
/**
* @param {?} data
* @return {?}
*/
Attachment.prototype.load = /**
* @param {?} data
* @return {?}
*/
function (data) {
this._logService.log('attachment ' + this._key + ' loaded', data);
if (data !== undefined) {
this._loadStream.next(data);
}
else {
// we need to send back empty data if collection had nothing
if (this._isList) {
this._loadStream.next(undefined);
}
else {
this._loadStream.next(undefined);
}
}
this._tickStream.next(data);
};
/**
* @param {?} data
* @return {?}
*/
Attachment.prototype.added = /**
* @param {?} data
* @return {?}
*/
function (data) {
this._logService.log('attachment ' + this._key + ' added', data);
this._addStream.next(data);
this._tickStream.next(data);
};
/**
* @param {?} data
* @return {?}
*/
Attachment.prototype.changed = /**
* @param {?} data
* @return {?}
*/
function (data) {
this._logService.log('attachment ' + this._key + ' changed', data);
this._changeStream.next(data);
this._tickStream.next(data);
};
/**
* @param {?} data
* @return {?}
*/
Attachment.prototype.removed = /**
* @param {?} data
* @return {?}
*/
function (data) {
this._logService.log('attachment ' + this._key + ' removed', data);
this._removeStream.next(data);
this._tickStream.next(data);
};
/**
* @return {?}
*/
Attachment.prototype.loadStream = /**
* @return {?}
*/
function () {
return this._loadStream;
};
/**
* @return {?}
*/
Attachment.prototype.addedStream = /**
* @return {?}
*/
function () {
return this._addStream;
};
/**
* @return {?}
*/
Attachment.prototype.changedStream = /**
* @return {?}
*/
function () {
return this._changeStream;
};
/**
* @return {?}
*/
Attachment.prototype.removedStream = /**
* @return {?}
*/
function () {
return this._removeStream;
};
/**
* @return {?}
*/
Attachment.prototype.onTick = /**
* @return {?}
*/
function () {
return this._tickStream;
};
return Attachment;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* @param {?} val
* @return {?}
*/
function camelToKebabCase(val) {
/** @type {?} */
var result = val;
// Convert camelCase capitals to kebab-case.
result = result.replace(/([a-z][A-Z])/g, function (match) {
return match.substr(0, 1) + '-' + match.substr(1, 1).toLowerCase();
});
// Convert non-camelCase capitals to lowercase.
result = result.toLowerCase();
// Convert non-alphanumeric characters to hyphens
result = result.replace(/[^-a-z0-9]+/g, '-');
// Remove hyphens from both ends
result = result.replace(/^-+/, '').replace(/-$/, '');
return result;
}
/**
* @param {?} val
* @return {?}
*/
function kebabCaseToCamel(val) {
return val.replace(/-([a-z])/gi, function ($0, $1) {
return $1.toUpperCase();
});
}
/**
* @param {?} o
* @return {?}
*/
function encodeRequest(o) {
if (typeof o === 'string') {
return camelToKebabCase(o);
}
/** @type {?} */
var newO;
/** @type {?} */
var newKey;
/** @type {?} */
var value;
if (o instanceof Array) {
newO = [];
for (var origKey in o) {
if (o.hasOwnProperty(origKey)) {
value = o[origKey];
if (typeof value === 'object') {
value = encodeRequest(value);
}
newO.push(value);
}
}
}
else {
newO = {};
for (var origKey in o) {
if (o.hasOwnProperty(origKey)) {
newKey = camelToKebabCase(origKey);
value = o[origKey];
if (value !== null && value !== undefined && value.constructor === Object) {
value = encodeRequest(value);
}
newO[newKey] = value;
}
}
}
return newO;
}
/**
* @param {?} o
* @return {?}
*/
function decodeResponse(o) {
if (typeof o === 'string') {
return kebabCaseToCamel(o);
}
/** @type {?} */
var newO;
/** @type {?} */
var newKey;
/** @type {?} */
var value;
if (o instanceof Array) {
newO = [];
for (var origKey in o) {
if (o.hasOwnProperty(origKey)) {
value = o[origKey];
if (typeof value === 'object') {
value = decodeResponse(value);
}
newO.push(value);
}
}
}
else {
newO = {};
for (var origKey in o) {
if (o.hasOwnProperty(origKey)) {
newKey = kebabCaseToCamel(origKey);
value = o[origKey];
if (value !== null && value.constructor === Object) {
value = decodeResponse(value);
}
else if (value instanceof Array) {
value = decodeResponse(value);
}
newO[newKey] = value;
}
}
}
return newO;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var LogService = /** @class */ (function () {
function LogService() {
this.logging = new BehaviorSubject(false);
}
/**
* @param {?} value
* @return {?}
*/
LogService.prototype.setLog = /**
* @param {?} value
* @return {?}
*/
function (value) {
this.logging.next(value);
};
/**
* @param {?} message
* @param {?=} data
* @return {?}
*/
LogService.prototype.log = /**
* @param {?} message
* @param {?=} data
* @return {?}
*/
function (message, data) {
/** @type {?} */
var date = new Date();
if (this.logging.getValue()) {
if (data === undefined) {
console.log('Blast [' + date.getHours() +
':' + date.getMinutes() + ':' + date.getSeconds() + '.' +
date.getMilliseconds() + '] ' + message);
}
else {
console.log('Blast [' + date.getHours() +
':' + date.getMinutes() + ':' + date.getSeconds() + '.' +
date.getMilliseconds() + '] ' + message, data);
}
}
};
return LogService;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** @type {?} */
var useKebab = true;
var GraphBlastService = /** @class */ (function (_super) {
__extends(GraphBlastService, _super);
function GraphBlastService(_url, _logging, _connectNow, _protocols, _config) {
var _this = _super.call(this, _url, _connectNow, _protocols, _config) || this;
_this._url = _url;
_this._logging = _logging;
_this._connectNow = _connectNow;
_this._protocols = _protocols;
_this._config = _config;
_this._correlatedGraphRequestMap = [];
_this._collectionMap = {};
_this._correlationId = 0;
_this._logService = new LogService();
_this._logService.setLog(_logging);
return _this;
}
/**
* @param {?} collection
* @param {?} entity
* @return {?}
*/
GraphBlastService.prototype.add = /**
* @param {?} collection
* @param {?} entity
* @return {?}
*/
function (collection, entity) {
return this.sendGraphRequest(new GraphRequest('add', collection, entity));
};
/**
* @param {?} key
* @param {?} entity
* @return {?}
*/
GraphBlastService.prototype.update = /**
* @param {?} key
* @param {?} entity
* @return {?}
*/
function (key, entity) {
return this.sendGraphRequest(new GraphRequest('update', key, entity));
};
/**
* @param {?} key
* @return {?}
*/
GraphBlastService.prototype.remove = /**
* @param {?} key
* @return {?}
*/
function (key) {
return this.sendGraphRequest(new GraphRequest('remove', key));
};
/**
* @return {?}
*/
GraphBlastService.prototype.randomId = /**
* @return {?}
*/
function () {
/**
* @return {?}
*/
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
/**
* @param {?} key
* @param {?} data
* @param {?=} parameters
* @return {?}
*/
GraphBlastService.prototype.attach = /**
* @param {?} key
* @param {?} data
* @param {?=} parameters
* @return {?}
*/
function (key, data, parameters) {
// attach(key: string, data: any, parameters?: PathParameters): Promise<any> {
if (key.trim().length === 0) {
key = 'root';
}
/** @type {?} */
var isArray = false;
if (Object.prototype.toString.call(data) === '[object Array]') {
isArray = true;
}
/** @type {?} */
var pathDetails = PathDetails.splitPath(key);
if (pathDetails[pathDetails.length - 1].getKeyField() !== undefined && isArray) {
this.handlePromiseError(new BlastException('Can only attach to a type of {} when keyField:keyValue is last element of path'));
return;
}
if (pathDetails[pathDetails.length - 1].getKeyField() === undefined && !isArray) {
this.handlePromiseError(new BlastException('Can only attach to a type of [] when last element of path is a collection'));
return;
}
/** @type {?} */
var attachmentId = this.randomId();
/** @type {?} */
var attachment = new Attachment(attachmentId, key, this._logService);
if (isArray) {
attachment.setListData(data);
}
else {
attachment.setData(data);
}
this._collectionMap[attachmentId] = attachment;
// console.log('added to collection', key, clientCollection, this._collectionMap);
// return this.sendGraphRequest(new GraphRequest('attach', key, parameters, attachmentId));
this.sendGraphRequest(new GraphRequest('attach', key, null, parameters, attachmentId));
return attachment;
};
/**
* @param {?} blastException
* @return {?}
*/
GraphBlastService.prototype.handlePromiseError = /**
* @param {?} blastException
* @return {?}
*/
function (blastException) {
return new Promise(function (resolve, reject) {
reject(blastException.message);
});
// console.error('Exception:', blastException.message);
// const promise: Promise<any> = new Promise((onFulfilled, onRejected) => {
// onRejected(blastException.message);
// });
// return promise;
};
/**
* @param {?} key
* @return {?}
*/
GraphBlastService.prototype.detach = /**
* @param {?} key
* @return {?}
*/
function (key) {
return this.sendGraphRequest(new GraphRequest('detach', key));
};
/**
* @return {?}
*/
GraphBlastService.prototype.detachAll = /**
* @return {?}
*/
function () {
return this.sendGraphRequest(new GraphRequest('detachAll'));
};
/**
* @return {?}
*/
GraphBlastService.prototype.getAttachments = /**
* @return {?}
*/
function () {
return this.sendGraphRequest(new GraphRequest('attachments'));
};
/**
* @param {?} key
* @param {?=} parameters
* @return {?}
*/