Socket
Socket
Sign inDemoInstall

pubnub

Package Overview
Dependencies
Maintainers
4
Versions
224
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pubnub - npm Package Compare versions

Comparing version 4.0.0-beta1 to 4.0.0

lib/core/components/endpoint.js

4

bower.json
{
"name": "pubnub",
"version": "4.0.0-beta1",
"version": "4.0.0",
"main": "dist/web/pubnub.min.js",
"license": "https://github.com/pubnub/javascript/blob/master/LICENSE",
"ignore" : [ "**/*", "!dist/**/*", "!web/dist/pubnub.min.js"],
"ignore" : [ "**/*", "!dist/**/*"],
"keywords": [

@@ -8,0 +8,0 @@ "pubnub",

@@ -6,3 +6,3 @@ /* eslint no-console: 0, arrow-body-style: 0 */

const clean = require('gulp-clean');
const gulpWebpack = require('gulp-webpack');
const gulpWebpack = require('webpack-stream');
const webpackConfig = require('./webpack.config');

@@ -21,2 +21,3 @@ const eslint = require('gulp-eslint');

const packageJSON = require('./package.json');
const gzip = require('gulp-gzip');

@@ -45,5 +46,11 @@ gulp.task('clean', () => {

.pipe(rename('pubnub.' + packageJSON.version + '.js'))
.pipe(gulp.dest('upload'));
.pipe(gulp.dest('upload/normal'));
});
gulp.task('create_version_gzip', () => {
return gulp.src('upload/normal/*.js')
.pipe(gzip({ append: true }))
.pipe(gulp.dest('upload/gzip'));
});
gulp.task('uglify', () => {

@@ -57,3 +64,3 @@ return gulp.src('dist/web/pubnub.js')

.pipe(rename('pubnub.' + packageJSON.version + '.min.js'))
.pipe(gulp.dest('upload'));
.pipe(gulp.dest('upload/normal'));
});

@@ -97,3 +104,3 @@

return gulp.src(['lib/**/*.js'])
.pipe(gulpIstanbul({ instrumenter: isparta.Instrumenter }))
.pipe(gulpIstanbul({ instrumenter: isparta.Instrumenter, includeAllSources: true }))
.pipe(gulpIstanbul.hookRequire());

@@ -126,3 +133,3 @@ });

gulp.task('compile', (done) => {
runSequence('clean', 'babel', 'webpack', 'uglify', 'create_version', done);
runSequence('clean', 'babel', 'webpack', 'uglify', 'create_version', 'create_version_gzip', done);
});

@@ -129,0 +136,0 @@

@@ -36,2 +36,4 @@ 'use strict';

this.setFilterExpression(setup.filterExpression);
this.origin = setup.origin || 'pubsub.pubnub.com';

@@ -96,2 +98,12 @@ this.secure = setup.ssl || false;

}, {
key: 'getFilterExpression',
value: function getFilterExpression() {
return this.filterExpression;
}
}, {
key: 'setFilterExpression',
value: function setFilterExpression(val) {
this.filterExpression = val;return this;
}
}, {
key: 'getPresenceTimeout',

@@ -98,0 +110,0 @@ value: function getPresenceTimeout() {

@@ -27,5 +27,10 @@ 'use strict';

key: 'removeListener',
value: function removeListener(deprecatedListeners) {
var listenerPosition = this._listeners.indexOf(deprecatedListeners);
if (listenerPosition > -1) this._listeners = this._listeners.splice(listenerPosition, 1);
value: function removeListener(deprecatedListener) {
var newListeners = [];
this._listeners.forEach(function (listener) {
if (listener !== deprecatedListener) newListeners.push(listener);
});
this._listeners = newListeners;
}

@@ -32,0 +37,0 @@ }, {

@@ -85,3 +85,3 @@ 'use strict';

var superagentConstruct = _superagent2.default.post(this.getStandardOrigin() + endpoint.url).query(params).send(body);
return this._abstractedXDR(superagentConstruct, endpoint.timeout, callback);
return this._abstractedXDR(superagentConstruct, endpoint, callback);
}

@@ -92,16 +92,17 @@ }, {

var superagentConstruct = _superagent2.default.get(this.getStandardOrigin() + endpoint.url).query(params);
return this._abstractedXDR(superagentConstruct, endpoint.timeout, callback);
return this._abstractedXDR(superagentConstruct, endpoint, callback);
}
}, {
key: '_abstractedXDR',
value: function _abstractedXDR(superagentConstruct, timeout, callback) {
value: function _abstractedXDR(superagentConstruct, endpoint, callback) {
var _this = this;
if (this._config.logVerbosity) {
superagentConstruct = superagentConstruct.use(this._logger());
superagentConstruct = superagentConstruct.use(this._attachSuperagentLogger);
}
return superagentConstruct.type('json').timeout(timeout || this._config.getTransactionTimeout()).end(function (err, resp) {
return superagentConstruct.timeout(endpoint.timeout).end(function (err, resp) {
var status = {};
status.error = err !== null;
status.operation = endpoint.operation;

@@ -115,3 +116,2 @@ if (resp && resp.status) {

status.category = _this._detectErrorCategory(err);
return callback(status, null);

@@ -138,15 +138,16 @@ }

}, {
key: '_logger',
value: function _logger(options) {
if (!options) options = {};
return this._attachSuperagentLogger.bind(null, options);
}
}, {
key: '_attachSuperagentLogger',
value: function _attachSuperagentLogger(options, req) {
value: function _attachSuperagentLogger(req) {
var _pickLogger = function _pickLogger() {
if (console && console.log) return console;
if (window && window.console && window.console.log) return window.console;
return console;
};
var start = new Date().getTime();
var timestamp = new Date().toISOString();
console.log('<<<<<');
console.log('[' + timestamp + ']', '\n', req.url, '\n', req.qs);
console.log('-----');
var logger = _pickLogger();
logger.log('<<<<<');
logger.log('[' + timestamp + ']', '\n', req.url, '\n', req.qs);
logger.log('-----');

@@ -158,5 +159,5 @@ req.on('response', function (res) {

console.log('>>>>>>');
console.log('[' + timestampDone + ' / ' + elapsed + ']', '\n', req.url, '\n', req.qs, '\n', res.text);
console.log('-----');
logger.log('>>>>>>');
logger.log('[' + timestampDone + ' / ' + elapsed + ']', '\n', req.url, '\n', req.qs, '\n', res.text);
logger.log('-----');
});

@@ -163,0 +164,0 @@ }

@@ -21,7 +21,7 @@ 'use strict';

function _class(_ref) {
var timeEndpoints = _ref.timeEndpoints;
var timeEndpoint = _ref.timeEndpoint;
_classCallCheck(this, _class);
this._timeEndpoints = timeEndpoints;
this._timeEndpoint = timeEndpoint;
}

@@ -44,3 +44,3 @@

this._timeEndpoints.fetch(function (status) {
this._timeEndpoint.fetch(function (status) {
if (!status.error) {

@@ -47,0 +47,0 @@ clearInterval(_this._timeTimer);

@@ -13,6 +13,2 @@ 'use strict';

var _presence = require('../endpoints/presence');
var _presence2 = _interopRequireDefault(_presence);
var _time = require('../endpoints/time');

@@ -52,5 +48,7 @@

var subscribeEndpoints = _ref.subscribeEndpoints;
var presenceEndpoints = _ref.presenceEndpoints;
var timeEndpoints = _ref.timeEndpoints;
var subscribeEndpoint = _ref.subscribeEndpoint;
var leaveEndpoint = _ref.leaveEndpoint;
var heartbeatEndpoint = _ref.heartbeatEndpoint;
var setStateEndpoint = _ref.setStateEndpoint;
var timeEndpoint = _ref.timeEndpoint;
var config = _ref.config;

@@ -64,5 +62,8 @@ var crypto = _ref.crypto;

this._config = config;
this._subscribeEndpoints = subscribeEndpoints;
this._presenceEndpoints = presenceEndpoints;
this._timeEndpoints = timeEndpoints;
this._leaveEndpoint = leaveEndpoint;
this._heartbeatEndpoint = heartbeatEndpoint;
this._setStateEndpoint = setStateEndpoint;
this._subscribeEndpoint = subscribeEndpoint;
this._crypto = crypto;

@@ -77,6 +78,11 @@

this._timetoken = 0;
this._subscriptionStatusAnnounced = false;
this._reconnectionManager = new _reconnection_manager2.default({ timeEndpoints: timeEndpoints });
this._reconnectionManager = new _reconnection_manager2.default({ timeEndpoint: timeEndpoint });
this._reconnectionManager.onReconnection(function () {
_this.reconnect();
var reconnectedStatus = {};
reconnectedStatus.category = 'PNReconnectedCategory';
_this._subscriptionStatusAnnounced = true;
_this._listenerManager.announceStatus(status);
});

@@ -105,3 +111,3 @@ }

this._presenceEndpoints.setState({ state: state, channels: channels, channelGroups: channelGroups }, callback);
this._setStateEndpoint({ state: state, channels: channels, channelGroups: channelGroups }, callback);
}

@@ -134,2 +140,3 @@ }, {

this._subscriptionStatusAnnounced = false;
this.reconnect();

@@ -159,3 +166,3 @@ }

if (this._config.suppressLeaveEvents === false) {
this._presenceEndpoints.leave({ channels: channels, channelGroups: channelGroups }, function (status) {
this._leaveEndpoint({ channels: channels, channelGroups: channelGroups }, function (status) {
_this4._listenerManager.announceStatus(status);

@@ -183,2 +190,3 @@ });

this._stopHeartbeatTimer();
this._performHeartbeatLoop();
this._heartbeatTimer = setInterval(this._performHeartbeatLoop.bind(this), this._config.getHeartbeatInterval() * 1000);

@@ -209,8 +217,8 @@ }

var channelState = _this5._channels[channel].state;
if (channelState) presenceState[channel] = channelState;
if (Object.keys(channelState).length) presenceState[channel] = channelState;
});
presenceChannelGroups.forEach(function (channelGroup) {
var channelGroupState = _this5.channelGroup[channelGroup].state;
if (channelGroupState) presenceState[channelGroup] = channelGroupState;
var channelGroupState = _this5._channelGroups[channelGroup].state;
if (Object.keys(channelGroupState).length) presenceState[channelGroup] = channelGroupState;
});

@@ -228,3 +236,3 @@

this._presenceEndpoints.heartbeat({
this._heartbeatEndpoint({
channels: presenceChannels,

@@ -267,3 +275,3 @@ channelGroups: presenceChannelGroups,

this._subscribeCall = this._subscribeEndpoints.subscribe(subscribeArgs, this._processSubscribeResponse.bind(this));
this._subscribeCall = this._subscribeEndpoint(subscribeArgs, this._processSubscribeResponse.bind(this));
}

@@ -288,2 +296,10 @@ }, {

if (!this._subscriptionStatusAnnounced) {
var connectedAnnounce = {};
connectedAnnounce.category = 'PNConnectedCategory';
connectedAnnounce.operation = status.operation;
this._subscriptionStatusAnnounced = true;
this._listenerManager.announceStatus(connectedAnnounce);
}
payload.messages.forEach(function (message) {

@@ -290,0 +306,0 @@ var channel = message.channel;

@@ -6,140 +6,99 @@ 'use strict';

});
exports.getOperation = getOperation;
exports.validateParams = validateParams;
exports.getURL = getURL;
exports.getRequestTimeout = getRequestTimeout;
exports.isAuthSupported = isAuthSupported;
exports.prepareParams = prepareParams;
exports.handleResponse = handleResponse;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _networking = require('../components/networking');
var _networking2 = _interopRequireDefault(_networking);
var _config = require('../components/config');
var _config2 = _interopRequireDefault(_config);
var _index = require('../components/cryptography/index');
var _index2 = _interopRequireDefault(_index);
var _base = require('./base.js');
var _base2 = _interopRequireDefault(_base);
var _flow_interfaces = require('../flow_interfaces');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function __processMessage(modules, message) {
var config = modules.config;
var crypto = modules.crypto;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
if (!config.cipherKey) return message;
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _class = function (_BaseEndpoint) {
_inherits(_class, _BaseEndpoint);
function _class(_ref) {
var networking = _ref.networking;
var crypto = _ref.crypto;
var config = _ref.config;
_classCallCheck(this, _class);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class).call(this, { config: config }));
_this.networking = networking;
_this.crypto = crypto;
_this.config = config;
return _this;
try {
return crypto.decrypt(message);
} catch (e) {
return message;
}
}
_createClass(_class, [{
key: 'fetch',
value: function fetch(args, callback) {
var _this2 = this;
function getOperation() {
return 'PNHistoryOperation';
}
var channel = args.channel;
var start = args.start;
var end = args.end;
var includeTimetoken = args.includeTimetoken;
var reverse = args.reverse;
var _args$count = args.count;
var count = _args$count === undefined ? 100 : _args$count;
function validateParams(modules, incomingParams) {
var channel = incomingParams.channel;
var config = modules.config;
var endpointConfig = {
params: {
authKey: { required: false },
uuid: { required: false },
subscribeKey: { required: true }
},
url: '/v2/history/sub-key/' + this.config.subscribeKey + '/channel/' + encodeURIComponent(channel)
};
if (!channel) return 'Missing channel';
if (!config.subscribeKey) return 'Missing Subscribe Key';
}
if (!channel) return callback(this.createValidationError('Missing channel'));
if (!callback) return this.log('Missing Callback');
function getURL(modules, incomingParams) {
var channel = incomingParams.channel;
var config = modules.config;
if (!this.validateEndpointConfig(endpointConfig)) {
return;
}
return '/v2/history/sub-key/' + config.subscribeKey + '/channel/' + encodeURIComponent(channel);
}
var params = this.createBaseParams(endpointConfig);
params.count = count;
function getRequestTimeout(_ref) {
var config = _ref.config;
if (start) params.start = start;
if (end) params.end = end;
if (includeTimetoken != null) params.include_token = includeTimetoken.toString();
if (reverse != null) params.reverse = reverse.toString();
return config.getTransactionTimeout();
}
this.networking.GET(params, endpointConfig, function (status, payload) {
if (status.error) return callback(status);
function isAuthSupported() {
return true;
}
callback(status, _this2._parseResponse(payload, includeTimetoken));
});
}
}, {
key: '_parseResponse',
value: function _parseResponse(payload, includeTimetoken) {
var _this3 = this;
function prepareParams(modules, incomingParams) {
var start = incomingParams.start;
var end = incomingParams.end;
var includeTimetoken = incomingParams.includeTimetoken;
var reverse = incomingParams.reverse;
var _incomingParams$count = incomingParams.count;
var count = _incomingParams$count === undefined ? 100 : _incomingParams$count;
var response = {
messages: [],
startTimeToken: parseInt(payload[1], 10),
endTimeToken: parseInt(payload[2], 10)
};
var outgoingParams = {};
payload[0].forEach(function (serverHistoryItem) {
var item = {
timetoken: null,
entry: null
};
outgoingParams.count = count;
if (start) outgoingParams.start = start;
if (end) outgoingParams.end = end;
if (includeTimetoken != null) outgoingParams.include_token = includeTimetoken.toString();
if (reverse != null) outgoingParams.reverse = reverse.toString();
if (includeTimetoken) {
item.timetoken = serverHistoryItem.timetoken;
item.entry = _this3.__processMessage(serverHistoryItem.message);
} else {
item.entry = _this3.__processMessage(serverHistoryItem);
}
return outgoingParams;
}
response.messages.push(item);
});
function handleResponse(modules, serverResponse) {
var response = {
messages: [],
startTimeToken: parseInt(serverResponse[1], 10),
endTimeToken: parseInt(serverResponse[2], 10)
};
return response;
}
}, {
key: '__processMessage',
value: function __processMessage(message) {
if (!this.config.cipherKey) return message;
serverResponse[0].forEach(function (serverHistoryItem) {
var item = {
timetoken: null,
entry: null
};
try {
return this.crypto.decrypt(message);
} catch (e) {
return message;
}
if (serverHistoryItem.timetoken) {
item.timetoken = serverHistoryItem.timetoken;
item.entry = __processMessage(modules, serverHistoryItem.message);
} else {
item.entry = __processMessage(modules, serverHistoryItem);
}
}]);
return _class;
}(_base2.default);
response.messages.push(item);
});
exports.default = _class;
module.exports = exports['default'];
return response;
}
//# sourceMappingURL=history.js.map

@@ -9,133 +9,113 @@ 'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.getOperation = getOperation;
exports.validateParams = validateParams;
exports.usePost = usePost;
exports.getURL = getURL;
exports.postURL = postURL;
exports.getRequestTimeout = getRequestTimeout;
exports.isAuthSupported = isAuthSupported;
exports.postPayload = postPayload;
exports.prepareParams = prepareParams;
exports.handleResponse = handleResponse;
var _networking = require('../components/networking');
var _flow_interfaces = require('../flow_interfaces');
var _networking2 = _interopRequireDefault(_networking);
function prepareMessagePayload(modules, messagePayload) {
var crypto = modules.crypto;
var config = modules.config;
var _config = require('../components/config');
var stringifiedPayload = JSON.stringify(messagePayload);
var _config2 = _interopRequireDefault(_config);
if (config.cipherKey) {
stringifiedPayload = crypto.encrypt(stringifiedPayload);
stringifiedPayload = JSON.stringify(stringifiedPayload);
}
var _index = require('../components/cryptography/index');
return stringifiedPayload;
}
var _index2 = _interopRequireDefault(_index);
function getOperation() {
return 'PNPublishOperation';
}
var _base = require('./base.js');
function validateParams(_ref, incomingParams) {
var config = _ref.config;
var message = incomingParams.message;
var channel = incomingParams.channel;
var _base2 = _interopRequireDefault(_base);
var _flow_interfaces = require('../flow_interfaces');
if (!channel) return 'Missing Channel';
if (!message) return 'Missing Message';
if (!config.subscribeKey) return 'Missing Subscribe Key';
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function usePost(modules, incomingParams) {
var _incomingParams$sendB = incomingParams.sendByPost;
var sendByPost = _incomingParams$sendB === undefined ? false : _incomingParams$sendB;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
return sendByPost;
}
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function getURL(modules, incomingParams) {
var config = modules.config;
var channel = incomingParams.channel;
var message = incomingParams.message;
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var stringifiedPayload = prepareMessagePayload(modules, message);
return '/publish/' + config.publishKey + '/' + config.subscribeKey + '/0/' + encodeURIComponent(channel) + '/0/' + encodeURIComponent(stringifiedPayload);
}
var _class = function (_BaseEndpoint) {
_inherits(_class, _BaseEndpoint);
function postURL(modules, incomingParams) {
var config = modules.config;
var channel = incomingParams.channel;
function _class(_ref) {
var networking = _ref.networking;
var config = _ref.config;
var crypto = _ref.crypto;
return '/publish/' + config.publishKey + '/' + config.subscribeKey + '/0/' + encodeURIComponent(channel) + '/0';
}
_classCallCheck(this, _class);
function getRequestTimeout(_ref2) {
var config = _ref2.config;
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class).call(this, { config: config }));
return config.getTransactionTimeout();
}
_this.networking = networking;
_this.config = config;
_this.crypto = crypto;
return _this;
}
function isAuthSupported() {
return true;
}
_createClass(_class, [{
key: 'fire',
value: function fire(args, callback) {
args.replicate = false;
args.storeInHistory = false;
this.publish(args, callback);
}
}, {
key: 'publish',
value: function publish(args, callback) {
var message = args.message;
var channel = args.channel;
var meta = args.meta;
var _args$sendByPost = args.sendByPost;
var sendByPost = _args$sendByPost === undefined ? false : _args$sendByPost;
var _args$replicate = args.replicate;
var replicate = _args$replicate === undefined ? true : _args$replicate;
var storeInHistory = args.storeInHistory;
function postPayload(modules, incomingParams) {
var message = incomingParams.message;
var endpointConfig = {
params: {
authKey: { required: false },
subscribeKey: { required: true },
publishKey: { required: true },
uuid: { required: false }
},
url: '/publish/' + this.config.publishKey + '/' + this.config.subscribeKey + '/0/' + encodeURIComponent(channel) + '/0'
};
return prepareMessagePayload(modules, message);
}
if (!message) return callback(this.createValidationError('Missing Message'));
if (!channel) return callback(this.createValidationError('Missing Channel'));
function prepareParams(modules, incomingParams) {
var meta = incomingParams.meta;
var _incomingParams$repli = incomingParams.replicate;
var replicate = _incomingParams$repli === undefined ? true : _incomingParams$repli;
var storeInHistory = incomingParams.storeInHistory;
if (!this.validateEndpointConfig(endpointConfig)) {
return;
}
var params = {};
var params = this.createBaseParams(endpointConfig);
if (storeInHistory != null) {
if (storeInHistory) {
params.store = '1';
} else {
params.store = '0';
}
}
if (storeInHistory != null) {
if (storeInHistory) {
params.store = '1';
} else {
params.store = '0';
}
}
if (replicate === false) {
params.norep = 'true';
}
if (replicate === false) {
params.norep = 'true';
}
if (meta && (typeof meta === 'undefined' ? 'undefined' : _typeof(meta)) === 'object') {
params.meta = JSON.stringify(meta);
}
if (meta && (typeof meta === 'undefined' ? 'undefined' : _typeof(meta)) === 'object') {
params.meta = JSON.stringify(meta);
}
return params;
}
var onCallback = function onCallback(status, payload) {
if (status.error) return callback(status);
var response = {
timetoken: payload[2]
};
callback(status, response);
};
var stringifiedPayload = JSON.stringify(message);
if (this.config.cipherKey) {
stringifiedPayload = this.crypto.encrypt(stringifiedPayload);
stringifiedPayload = JSON.stringify(stringifiedPayload);
}
if (sendByPost) {
this.networking.POST(params, stringifiedPayload, endpointConfig, onCallback);
} else {
endpointConfig.url += '/' + encodeURIComponent(stringifiedPayload);
this.networking.GET(params, endpointConfig, onCallback);
}
}
}]);
return _class;
}(_base2.default);
exports.default = _class;
module.exports = exports['default'];
function handleResponse(modules, serverResponse) {
return { timetoken: serverResponse[2] };
}
//# sourceMappingURL=publish.js.map

@@ -6,127 +6,102 @@ 'use strict';

});
exports.getOperation = getOperation;
exports.validateParams = validateParams;
exports.getURL = getURL;
exports.getRequestTimeout = getRequestTimeout;
exports.isAuthSupported = isAuthSupported;
exports.prepareParams = prepareParams;
exports.handleResponse = handleResponse;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _flow_interfaces = require('../flow_interfaces');
var _networking = require('../components/networking');
function getOperation() {
return 'PNSubscribeOperation';
}
var _networking2 = _interopRequireDefault(_networking);
function validateParams(modules) {
var config = modules.config;
var _config = require('../components/config');
var _config2 = _interopRequireDefault(_config);
if (!config.subscribeKey) return 'Missing Subscribe Key';
}
var _base = require('./base.js');
function getURL(modules, incomingParams) {
var config = modules.config;
var _incomingParams$chann = incomingParams.channels;
var channels = _incomingParams$chann === undefined ? [] : _incomingParams$chann;
var _base2 = _interopRequireDefault(_base);
var stringifiedChannels = channels.length > 0 ? channels.join(',') : ',';
return '/v2/subscribe/' + config.subscribeKey + '/' + encodeURIComponent(stringifiedChannels) + '/0';
}
var _flow_interfaces = require('../flow_interfaces');
function getRequestTimeout(_ref) {
var config = _ref.config;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
return config.getSubscribeTimeout();
}
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function isAuthSupported() {
return true;
}
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function prepareParams(_ref2, incomingParams) {
var config = _ref2.config;
var _incomingParams$chann2 = incomingParams.channelGroups;
var channelGroups = _incomingParams$chann2 === undefined ? [] : _incomingParams$chann2;
var timetoken = incomingParams.timetoken;
var filterExpression = incomingParams.filterExpression;
var region = incomingParams.region;
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var params = {
heartbeat: config.getPresenceTimeout()
};
var _class = function (_BaseEndpoint) {
_inherits(_class, _BaseEndpoint);
if (channelGroups.length > 0) {
params['channel-group'] = encodeURIComponent(channelGroups.join(','));
}
function _class(_ref) {
var networking = _ref.networking;
var config = _ref.config;
if (filterExpression && filterExpression.length > 0) {
params['filter-expr'] = encodeURIComponent(filterExpression);
}
_classCallCheck(this, _class);
if (timetoken) {
params.tt = timetoken;
}
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class).call(this, { config: config }));
_this._networking = networking;
_this._config = config;
return _this;
if (region) {
params.tr = region;
}
_createClass(_class, [{
key: 'subscribe',
value: function subscribe(args, callback) {
var _args$channels = args.channels;
var channels = _args$channels === undefined ? [] : _args$channels;
var _args$channelGroups = args.channelGroups;
var channelGroups = _args$channelGroups === undefined ? [] : _args$channelGroups;
var timetoken = args.timetoken;
var filterExpression = args.filterExpression;
var region = args.region;
return params;
}
var stringifiedChannels = channels.length > 0 ? channels.join(',') : ',';
var endpointConfig = {
params: {
authKey: { required: false },
uuid: {},
subscribeKey: { required: true }
},
timeout: this._config.getSubscribeTimeout(),
url: '/v2/subscribe/' + this._config.subscribeKey + '/' + encodeURIComponent(stringifiedChannels) + '/0'
};
function handleResponse(modules, serverResponse) {
var messages = [];
if (!this.validateEndpointConfig(endpointConfig)) {
return;
}
serverResponse.m.forEach(function (rawMessage) {
var publishMetaData = {
publishTimetoken: rawMessage.p.t,
region: rawMessage.p.r
};
var parsedMessage = {
shard: parseInt(rawMessage.a, 10),
subscriptionMatch: rawMessage.b,
channel: rawMessage.c,
payload: rawMessage.d,
flags: rawMessage.f,
issuingClientId: rawMessage.i,
subscribeKey: rawMessage.k,
originationTimetoken: rawMessage.o,
publishMetaData: publishMetaData
};
messages.push(parsedMessage);
});
var params = this.createBaseParams(endpointConfig);
var metadata = {
timetoken: serverResponse.t.t,
region: serverResponse.t.r
};
if (channelGroups.length > 0) {
params['channel-group'] = encodeURIComponent(channelGroups.join(','));
}
if (filterExpression && filterExpression.length > 0) {
params['filter-expr'] = encodeURIComponent(filterExpression);
}
if (timetoken) {
params.tt = timetoken;
}
if (region) {
params.tr = region;
}
return this._networking.GET(params, endpointConfig, function (status, payload) {
if (status.error) return callback(status);
var messages = [];
payload.m.forEach(function (rawMessage) {
var publishMetaData = {
publishTimetoken: rawMessage.p.t,
region: rawMessage.p.r
};
var parsedMessage = {
shard: parseInt(rawMessage.a, 10),
subscriptionMatch: rawMessage.b,
channel: rawMessage.c,
payload: rawMessage.d,
flags: rawMessage.f,
issuingClientId: rawMessage.i,
subscribeKey: rawMessage.k,
originationTimetoken: rawMessage.o,
publishMetaData: publishMetaData
};
messages.push(parsedMessage);
});
var metadata = {
timetoken: payload.t.t,
region: payload.t.r
};
var response = { messages: messages, metadata: metadata };
callback(status, response);
});
}
}]);
return _class;
}(_base2.default);
exports.default = _class;
module.exports = exports['default'];
return { messages: messages, metadata: metadata };
}
//# sourceMappingURL=subscribe.js.map

@@ -6,75 +6,41 @@ 'use strict';

});
exports.getOperation = getOperation;
exports.getURL = getURL;
exports.getRequestTimeout = getRequestTimeout;
exports.prepareParams = prepareParams;
exports.isAuthSupported = isAuthSupported;
exports.handleResponse = handleResponse;
exports.validateParams = validateParams;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _networking = require('../components/networking');
var _networking2 = _interopRequireDefault(_networking);
var _config = require('../components/config');
var _config2 = _interopRequireDefault(_config);
var _base = require('./base.js');
var _base2 = _interopRequireDefault(_base);
var _flow_interfaces = require('../flow_interfaces');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getOperation() {
return 'PNTimeOperation';
}
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function getURL() {
return '/time/0';
}
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function getRequestTimeout(_ref) {
var config = _ref.config;
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
return config.getTransactionTimeout();
}
var _class = function (_BaseEndpoint) {
_inherits(_class, _BaseEndpoint);
function prepareParams() {
return {};
}
function _class(_ref) {
var networking = _ref.networking;
var config = _ref.config;
function isAuthSupported() {
return false;
}
_classCallCheck(this, _class);
function handleResponse(modules, serverResponse) {
return {
timetoken: serverResponse[0]
};
}
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class).call(this, { config: config }));
_this._networking = networking;
return _this;
}
_createClass(_class, [{
key: 'fetch',
value: function fetch(callback) {
var endpointConfig = {
params: {
uuid: { required: false }
},
url: '/time/0'
};
if (!this.validateEndpointConfig(endpointConfig)) {
return;
}
var params = this.createBaseParams(endpointConfig);
this._networking.GET(params, endpointConfig, function (status, payload) {
if (status.error) return callback(status);
var response = {
timetoken: payload[0]
};
callback(status, response);
});
}
}]);
return _class;
}(_base2.default);
exports.default = _class;
module.exports = exports['default'];
function validateParams() {}
//# sourceMappingURL=time.js.map

@@ -29,40 +29,98 @@ 'use strict';

var _package = require('../../package.json');
var _endpoint = require('./components/endpoint');
var _package2 = _interopRequireDefault(_package);
var _endpoint2 = _interopRequireDefault(_endpoint);
var _time = require('./endpoints/time');
var _add_channels = require('./endpoints/channel_groups/add_channels');
var _time2 = _interopRequireDefault(_time);
var addChannelsChannelGroupConfig = _interopRequireWildcard(_add_channels);
var _presence = require('./endpoints/presence');
var _remove_channels = require('./endpoints/channel_groups/remove_channels');
var _presence2 = _interopRequireDefault(_presence);
var removeChannelsChannelGroupConfig = _interopRequireWildcard(_remove_channels);
var _history = require('./endpoints/history');
var _delete_group = require('./endpoints/channel_groups/delete_group');
var _history2 = _interopRequireDefault(_history);
var deleteChannelGroupConfig = _interopRequireWildcard(_delete_group);
var _push = require('./endpoints/push');
var _list_groups = require('./endpoints/channel_groups/list_groups');
var _push2 = _interopRequireDefault(_push);
var listChannelGroupsConfig = _interopRequireWildcard(_list_groups);
var _access = require('./endpoints/access');
var _list_channels = require('./endpoints/channel_groups/list_channels');
var _access2 = _interopRequireDefault(_access);
var listChannelsInChannelGroupConfig = _interopRequireWildcard(_list_channels);
var _channel_groups = require('./endpoints/channel_groups');
var _add_push_channels = require('./endpoints/push/add_push_channels');
var _channel_groups2 = _interopRequireDefault(_channel_groups);
var addPushChannelsConfig = _interopRequireWildcard(_add_push_channels);
var _subscribe = require('./endpoints/subscribe');
var _remove_push_channels = require('./endpoints/push/remove_push_channels');
var _subscribe2 = _interopRequireDefault(_subscribe);
var removePushChannelsConfig = _interopRequireWildcard(_remove_push_channels);
var _list_push_channels = require('./endpoints/push/list_push_channels');
var listPushChannelsConfig = _interopRequireWildcard(_list_push_channels);
var _remove_device = require('./endpoints/push/remove_device');
var removeDevicePushConfig = _interopRequireWildcard(_remove_device);
var _leave = require('./endpoints/presence/leave');
var presenceLeaveEndpointConfig = _interopRequireWildcard(_leave);
var _where_now = require('./endpoints/presence/where_now');
var presenceWhereNowEndpointConfig = _interopRequireWildcard(_where_now);
var _heartbeat = require('./endpoints/presence/heartbeat');
var presenceHeartbeatEndpointConfig = _interopRequireWildcard(_heartbeat);
var _get_state = require('./endpoints/presence/get_state');
var presenceGetStateConfig = _interopRequireWildcard(_get_state);
var _set_state = require('./endpoints/presence/set_state');
var presenceSetStateConfig = _interopRequireWildcard(_set_state);
var _here_now = require('./endpoints/presence/here_now');
var presenceHereNowConfig = _interopRequireWildcard(_here_now);
var _audit = require('./endpoints/access_manager/audit');
var auditEndpointConfig = _interopRequireWildcard(_audit);
var _grant = require('./endpoints/access_manager/grant');
var grantEndpointConfig = _interopRequireWildcard(_grant);
var _publish = require('./endpoints/publish');
var _publish2 = _interopRequireDefault(_publish);
var publishEndpointConfig = _interopRequireWildcard(_publish);
var _history = require('./endpoints/history');
var historyEndpointConfig = _interopRequireWildcard(_history);
var _time = require('./endpoints/time');
var timeEndpointConfig = _interopRequireWildcard(_time);
var _subscribe = require('./endpoints/subscribe');
var subscribeEndpointConfig = _interopRequireWildcard(_subscribe);
var _package = require('../../package.json');
var _package2 = _interopRequireDefault(_package);
var _flow_interfaces = require('./flow_interfaces');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -74,2 +132,4 @@

function _class(setup) {
var _this = this;
_classCallCheck(this, _class);

@@ -81,18 +141,24 @@

this._config = new _config2.default({ setup: setup, db: db });
this._crypto = new _index2.default({ config: this._config });
this._networking = new _networking2.default({ config: this._config, crypto: this._crypto, sendBeacon: sendBeacon });
var config = this._config = new _config2.default({ setup: setup, db: db });
var crypto = new _index2.default({ config: config });
var networking = new _networking2.default({ config: config, crypto: crypto, sendBeacon: sendBeacon });
var subscribeEndpoints = new _subscribe2.default({ networking: this._networking, config: this._config });
var presenceEndpoints = new _presence2.default({ networking: this._networking, config: this._config });
var timeEndpoints = new _time2.default({ networking: this._networking, config: this._config });
var pushEndpoints = new _push2.default({ networking: this._networking, config: this._config });
var channelGroupEndpoints = new _channel_groups2.default({ networking: this._networking, config: this._config });
var publishEndpoints = new _publish2.default({ networking: this._networking, config: this._config, crypto: this._crypto });
var historyEndpoint = new _history2.default({ networking: this._networking, config: this._config, crypto: this._crypto });
var accessEndpoints = new _access2.default({ config: this._config, networking: this._networking, crypto: this._crypto });
var modules = { config: config, networking: networking, crypto: crypto };
var listenerManager = new _listener_manager2.default();
var subscriptionManager = new _subscription_manager2.default({ config: this._config, listenerManager: listenerManager, subscribeEndpoints: subscribeEndpoints, presenceEndpoints: presenceEndpoints, timeEndpoints: timeEndpoints });
var timeEndpoint = _endpoint2.default.bind(this, modules, timeEndpointConfig);
var leaveEndpoint = _endpoint2.default.bind(this, modules, presenceLeaveEndpointConfig);
var heartbeatEndpoint = _endpoint2.default.bind(this, modules, presenceHeartbeatEndpointConfig);
var setStateEndpoint = _endpoint2.default.bind(this, modules, presenceSetStateConfig);
var subscribeEndpoint = _endpoint2.default.bind(this, modules, subscribeEndpointConfig);
var subscriptionManager = new _subscription_manager2.default({
timeEndpoint: timeEndpoint,
leaveEndpoint: leaveEndpoint, heartbeatEndpoint: heartbeatEndpoint, setStateEndpoint: setStateEndpoint,
subscribeEndpoint: subscribeEndpoint,
config: modules.config,
listenerManager: listenerManager
});
this.addListener = listenerManager.addListener.bind(listenerManager);

@@ -102,29 +168,36 @@ this.removeListener = listenerManager.removeListener.bind(listenerManager);

this.channelGroups = {
listGroups: channelGroupEndpoints.listGroups.bind(channelGroupEndpoints),
listChannels: channelGroupEndpoints.listChannels.bind(channelGroupEndpoints),
addChannels: channelGroupEndpoints.addChannels.bind(channelGroupEndpoints),
removeChannels: channelGroupEndpoints.removeChannels.bind(channelGroupEndpoints),
deleteGroup: channelGroupEndpoints.deleteGroup.bind(channelGroupEndpoints)
listGroups: _endpoint2.default.bind(this, modules, listChannelGroupsConfig),
listChannels: _endpoint2.default.bind(this, modules, listChannelsInChannelGroupConfig),
addChannels: _endpoint2.default.bind(this, modules, addChannelsChannelGroupConfig),
removeChannels: _endpoint2.default.bind(this, modules, removeChannelsChannelGroupConfig),
deleteGroup: _endpoint2.default.bind(this, modules, deleteChannelGroupConfig)
};
this.push = {
addChannels: pushEndpoints.addDeviceToPushChannels.bind(pushEndpoints),
removeChannels: pushEndpoints.removeDeviceFromPushChannels.bind(pushEndpoints),
deleteDevice: pushEndpoints.removeDevice.bind(pushEndpoints),
listChannels: pushEndpoints.listChannelsForDevice.bind(pushEndpoints)
addChannels: _endpoint2.default.bind(this, modules, addPushChannelsConfig),
removeChannels: _endpoint2.default.bind(this, modules, removePushChannelsConfig),
deleteDevice: _endpoint2.default.bind(this, modules, removeDevicePushConfig),
listChannels: _endpoint2.default.bind(this, modules, listPushChannelsConfig)
};
this.hereNow = presenceEndpoints.hereNow.bind(presenceEndpoints);
this.whereNow = presenceEndpoints.whereNow.bind(presenceEndpoints);
this.getState = presenceEndpoints.getState.bind(presenceEndpoints);
this.hereNow = _endpoint2.default.bind(this, modules, presenceHereNowConfig);
this.whereNow = _endpoint2.default.bind(this, modules, presenceWhereNowEndpointConfig);
this.getState = _endpoint2.default.bind(this, modules, presenceGetStateConfig);
this.setState = subscriptionManager.adaptStateChange.bind(subscriptionManager);
this.grant = accessEndpoints.grant.bind(accessEndpoints);
this.audit = accessEndpoints.audit.bind(accessEndpoints);
this.grant = _endpoint2.default.bind(this, modules, grantEndpointConfig);
this.audit = _endpoint2.default.bind(this, modules, auditEndpointConfig);
this.publish = publishEndpoints.publish.bind(publishEndpoints);
this.fire = publishEndpoints.fire.bind(publishEndpoints);
this.history = historyEndpoint.fetch.bind(historyEndpoint);
this.time = timeEndpoints.fetch.bind(timeEndpoints);
this.publish = _endpoint2.default.bind(this, modules, publishEndpointConfig);
this.fire = function (args, callback) {
args.replicate = false;
args.storeInHistory = false;
_this.publish(args, callback);
};
this.history = _endpoint2.default.bind(this, modules, historyEndpointConfig);
this.time = timeEndpoint;
this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager);

@@ -134,9 +207,10 @@ this.unsubscribe = subscriptionManager.adaptUnsubscribeChange.bind(subscriptionManager);

this.stop = subscriptionManager.disconnect.bind(subscriptionManager);
this.reconnect = subscriptionManager.reconnect.bind(_subscription_manager2.default);
this.getAuthKey = this._config.getAuthKey.bind(this._config);
this.setAuthKey = this._config.setAuthKey.bind(this._config);
this.setCipherKey = this._config.setCipherKey.bind(this._config);
this.getUUID = this._config.getUUID.bind(this._config);
this.setUUID = this._config.setUUID.bind(this._config);
this.getAuthKey = modules.config.getAuthKey.bind(modules.config);
this.setAuthKey = modules.config.setAuthKey.bind(modules.config);
this.setCipherKey = modules.config.setCipherKey.bind(modules.config);
this.getUUID = modules.config.getUUID.bind(modules.config);
this.setUUID = modules.config.setUUID.bind(modules.config);
this.getFilterExpression = modules.config.getFilterExpression.bind(modules.config);
this.setFilterExpression = modules.config.setFilterExpression.bind(modules.config);
}

@@ -143,0 +217,0 @@

@@ -34,10 +34,2 @@ 'use strict';

function navigatorOnlineCheck() {
if (!('onLine' in navigator)) {
return null;
}
return navigator.onLine;
}
function sendBeacon(url) {

@@ -58,3 +50,2 @@ if (navigator && navigator.sendBeacon) {

setup.db = db;
setup.navigatorOnlineCheck = navigatorOnlineCheck;
setup.sendBeacon = sendBeacon;

@@ -65,3 +56,7 @@ setup.params = {

return _possibleConstructorReturn(this, Object.getPrototypeOf(_class).call(this, setup));
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class).call(this, setup));
window.addEventListener('offline', _this.stop.bind(_this));
window.addEventListener('online', _this.reconnect.bind(_this));
return _this;
}

@@ -68,0 +63,0 @@

{
"name": "pubnub",
"preferGlobal": false,
"version": "4.0.0-beta1",
"version": "4.0.0",
"author": "PubNub <support@pubnub.com>",
"description": "Publish & Subscribe Real-time Messaging with PubNub",
"contributors": [
{
"name": "Stephen Blum",
"email": "stephen@pubnub.com"
}
],
"bin": {},

@@ -17,4 +11,4 @@ "scripts": {

},
"main": "./node.js/pubnub.js",
"browser": "./modern/dist/pubnub.js",
"main": "./lib/node/index.js",
"browser": "./dist/web/pubnub.min.js",
"repository": {

@@ -50,7 +44,7 @@ "type": "git",

"eslint-config-airbnb": "9.0.1",
"eslint-plugin-flowtype": "2.3.0",
"eslint-plugin-flowtype": "2.3.1",
"eslint-plugin-import": "^1.9.2",
"eslint-plugin-mocha": "3.0.0",
"eslint-plugin-react": "5.2.2",
"flow-bin": "^0.27.0",
"flow-bin": "^0.29.0",
"gulp": "^3.9.1",

@@ -62,2 +56,3 @@ "gulp-babel": "^6.1.2",

"gulp-flowtype": "^0.4.9",
"gulp-gzip": "^1.4.0",
"gulp-istanbul": "^1.0.0",

@@ -68,7 +63,6 @@ "gulp-mocha": "^2.2.0",

"gulp-uglify": "^1.5.4",
"gulp-webpack": "^1.5.0",
"imports-loader": "0.6.5",
"isparta": "^4.0.0",
"json-loader": "0.5.4",
"karma": "1.1.0",
"karma": "1.1.1",
"karma-babel-preprocessor": "^6.0.1",

@@ -86,6 +80,7 @@ "karma-chai": "0.1.0",

"sinon": "^1.17.4",
"stats-webpack-plugin": "^0.3.1",
"stats-webpack-plugin": "^0.4.0",
"uglify-js": "^2.6.4",
"webpack": "^1.13.1",
"webpack-dev-server": "1.14.1"
"webpack-dev-server": "1.14.1",
"webpack-stream": "^3.2.0"
},

@@ -92,0 +87,0 @@ "bundleDependencies": [],

# PubNub JavaScript SDK
[![Build Status](https://travis-ci.org/pubnub/javascript.svg?branch=master)](https://travis-ci.org/pubnub/javascript)
[![Codecov](https://img.shields.io/codecov/c/github/pubnub/javascript.svg?maxAge=2592000)](https://codecov.io/github/pubnub/javascript)
[![npm](https://img.shields.io/npm/v/pubnub.svg)]()
[![Bower](https://img.shields.io/bower/v/pubnub.svg)]()
---
### Looking for Javascript V3 SDK?
please use the [master_3x ](https://github.com/pubnub/javascript/tree/master_3x) branch
## Documentation Preview
https://hackmd.io/IYJgxgZgbAJhCMBaMAOARgTkQFnCRKw2wOAzAKbnDlQbwrZhA===
### PubNub for JavaScript Docs have been moved to:
* [web](https://www.pubnub.com/docs/javascript/pubnub-javascript-sdk-v4)
* [node](https://www.pubnub.com/docs/nodejs/pubnub-javascript-sdk-v4)
----
PubNub for JavaScript Docs have been moved to: http://www.pubnub.com/docs/javascript/javascript-sdk.html
## Communication

@@ -23,7 +22,7 @@

#### HTTP
* http://cdn.pubnub.com/pubnub-4.0.0-beta1.min.js
* http://cdn.pubnub.com/pubnub-4.0.0-beta1.js
* http://cdn.pubnub.com/sdk/javascript/pubnub-4.0.0.min.js
* http://cdn.pubnub.com/sdk/javascript/pubnub-4.0.0.js
#### HTTPS
* https://cdn.pubnub.com/pubnub-4.0.0-beta1.min.js
* https://cdn.pubnub.com/pubnub-4.0.0-beta1.js
* https://cdn.pubnub.com/sdk/javascript/pubnub-4.0.0.min.js
* https://cdn.pubnub.com/sdk/javascript/pubnub-4.0.0.js

@@ -97,2 +97,4 @@ /* @flow */

this.setFilterExpression(setup.filterExpression);
this.origin = setup.origin || 'pubsub.pubnub.com';

@@ -142,2 +144,5 @@ this.secure = setup.ssl || false;

getFilterExpression(): string { return this.filterExpression; }
setFilterExpression(val: string): this { this.filterExpression = val; return this; }
getPresenceTimeout(): number { return this._presenceTimeout; }

@@ -144,0 +149,0 @@ setPresenceTimeout(val: number): this {

@@ -16,5 +16,10 @@ /* @flow */

removeListener(deprecatedListeners: CallbackStruct) {
const listenerPosition = this._listeners.indexOf(deprecatedListeners);
if (listenerPosition > -1) this._listeners = this._listeners.splice(listenerPosition, 1);
removeListener(deprecatedListener: CallbackStruct) {
let newListeners = [];
this._listeners.forEach((listener) => {
if (listener !== deprecatedListener) newListeners.push(listener);
});
this._listeners = newListeners;
}

@@ -21,0 +26,0 @@

@@ -84,3 +84,3 @@ /* @flow */

.send(body);
return this._abstractedXDR(superagentConstruct, endpoint.timeout, callback);
return this._abstractedXDR(superagentConstruct, endpoint, callback);
}

@@ -92,17 +92,17 @@

.query(params);
return this._abstractedXDR(superagentConstruct, endpoint.timeout, callback);
return this._abstractedXDR(superagentConstruct, endpoint, callback);
}
_abstractedXDR(superagentConstruct: superagent, timeout: number | null | void, callback: Function): Object {
_abstractedXDR(superagentConstruct: superagent, endpoint: EndpointDefinition, callback: Function): Object {
// attach a logger
if (this._config.logVerbosity) {
superagentConstruct = superagentConstruct.use(this._logger());
superagentConstruct = superagentConstruct.use(this._attachSuperagentLogger);
}
return superagentConstruct
.type('json')
.timeout(timeout || this._config.getTransactionTimeout())
.timeout(endpoint.timeout)
.end((err, resp) => {
let status: StatusAnnouncement = {};
status.error = err !== null;
status.operation = endpoint.operation;

@@ -116,4 +116,2 @@ if (resp && resp.status) {

status.category = this._detectErrorCategory(err);
// console.log('status', status);
// console.log('err', err);
return callback(status, null);

@@ -139,13 +137,15 @@ }

_logger(options: ?Object): Function {
if (!options) options = {};
return this._attachSuperagentLogger.bind(null, options);
}
_attachSuperagentLogger(req: Object) {
let _pickLogger = function () {
if (console && console.log) return console; // eslint-disable-line no-console
if (window && window.console && window.console.log) return window.console;
return console;
};
_attachSuperagentLogger(options: Object, req: Object) {
let start = new Date().getTime();
let timestamp = new Date().toISOString();
console.log('<<<<<'); // eslint-disable-line no-console
console.log('[' + timestamp + ']', '\n', req.url, '\n', req.qs); // eslint-disable-line no-console
console.log('-----'); // eslint-disable-line no-console
let logger = _pickLogger();
logger.log('<<<<<'); // eslint-disable-line no-console
logger.log('[' + timestamp + ']', '\n', req.url, '\n', req.qs); // eslint-disable-line no-console
logger.log('-----'); // eslint-disable-line no-console

@@ -157,7 +157,7 @@ req.on('response', (res) => {

console.log('>>>>>>'); // eslint-disable-line no-console
console.log('[' + timestampDone + ' / ' + elapsed + ']', '\n', req.url, '\n', req.qs, '\n', res.text); // eslint-disable-line no-console
console.log('-----'); // eslint-disable-line no-console
logger.log('>>>>>>'); // eslint-disable-line no-console
logger.log('[' + timestampDone + ' / ' + elapsed + ']', '\n', req.url, '\n', req.qs, '\n', res.text); // eslint-disable-line no-console
logger.log('-----'); // eslint-disable-line no-console
});
}
}

@@ -1,6 +0,6 @@

import TimeEndpoints from '../endpoints/time';
import TimeEndpoint from '../endpoints/time';
import { StatusAnnouncement } from '../flow_interfaces';
type ReconnectionManagerArgs = {
timeEndpoints: TimeEndpoints
timeEndpoint: TimeEndpoint
}

@@ -11,7 +11,7 @@

_reconnectionCallback: Function;
_timeEndpoints: TimeEndpoints;
_timeEndpoint: TimeEndpoint;
_timeTimer: number;
constructor({ timeEndpoints }: ReconnectionManagerArgs) {
this._timeEndpoints = timeEndpoints;
constructor({ timeEndpoint }: ReconnectionManagerArgs) {
this._timeEndpoint = timeEndpoint;
}

@@ -28,3 +28,3 @@

_performTimeLoop() {
this._timeEndpoints.fetch((status: StatusAnnouncement) => {
this._timeEndpoint.fetch((status: StatusAnnouncement) => {
if (!status.error) {

@@ -31,0 +31,0 @@ clearInterval(this._timeTimer);

import SubscribeEndpoints from '../endpoints/subscribe';
import PresenceEndpoints from '../endpoints/presence';
import TimeEndpoints from '../endpoints/time';

@@ -32,3 +31,2 @@ import Crypto from '../components/cryptography';

subscribeEndpoints: SubscribeEndpoints,
presenceEndpoints: PresenceEndpoints,
timeEndpoints: TimeEndpoints,

@@ -47,4 +45,8 @@ config: Config,

_subscribeEndpoints: SubscribeEndpoints;
_presenceEndpoints: PresenceEndpoints;
_leaveEndpoint: Function;
_heartbeatEndpoint: Function;
_setStateEndpoint: Function;
_subscribeEndpoint: Function;
_channels: Object;

@@ -62,9 +64,13 @@ _presenceChannels: Object;

_heartbeatTimer: number;
_subscriptionStatusAnnounced: boolean;
constructor({ subscribeEndpoints, presenceEndpoints, timeEndpoints, config, crypto, listenerManager }: SubscriptionManagerConsturct) {
constructor({ subscribeEndpoint, leaveEndpoint, heartbeatEndpoint, setStateEndpoint, timeEndpoint, config, crypto, listenerManager }: SubscriptionManagerConsturct) {
this._listenerManager = listenerManager;
this._config = config;
this._subscribeEndpoints = subscribeEndpoints;
this._presenceEndpoints = presenceEndpoints;
this._timeEndpoints = timeEndpoints;
this._leaveEndpoint = leaveEndpoint;
this._heartbeatEndpoint = heartbeatEndpoint;
this._setStateEndpoint = setStateEndpoint;
this._subscribeEndpoint = subscribeEndpoint;
this._crypto = crypto;

@@ -79,6 +85,11 @@

this._timetoken = 0;
this._subscriptionStatusAnnounced = false;
this._reconnectionManager = new ReconnectionManager({ timeEndpoints });
this._reconnectionManager = new ReconnectionManager({ timeEndpoint });
this._reconnectionManager.onReconnection(() => {
this.reconnect();
let reconnectedStatus: StatusAnnouncement = {};
reconnectedStatus.category = 'PNReconnectedCategory';
this._subscriptionStatusAnnounced = true;
this._listenerManager.announceStatus(status);
});

@@ -98,3 +109,3 @@ }

this._presenceEndpoints.setState({ state, channels, channelGroups }, callback);
this._setStateEndpoint({ state, channels, channelGroups }, callback);
}

@@ -117,2 +128,3 @@

this._subscriptionStatusAnnounced = false;
this.reconnect();

@@ -135,3 +147,3 @@ }

if (this._config.suppressLeaveEvents === false) {
this._presenceEndpoints.leave({ channels, channelGroups }, (status) => {
this._leaveEndpoint({ channels, channelGroups }, (status) => {
this._listenerManager.announceStatus(status);

@@ -156,2 +168,3 @@ });

this._stopHeartbeatTimer();
this._performHeartbeatLoop();
this._heartbeatTimer = setInterval(this._performHeartbeatLoop.bind(this), this._config.getHeartbeatInterval() * 1000);

@@ -178,8 +191,8 @@ }

let channelState = this._channels[channel].state;
if (channelState) presenceState[channel] = channelState;
if (Object.keys(channelState).length) presenceState[channel] = channelState;
});
presenceChannelGroups.forEach((channelGroup) => {
let channelGroupState = this.channelGroup[channelGroup].state;
if (channelGroupState) presenceState[channelGroup] = channelGroupState;
let channelGroupState = this._channelGroups[channelGroup].state;
if (Object.keys(channelGroupState).length) presenceState[channelGroup] = channelGroupState;
});

@@ -197,3 +210,3 @@

this._presenceEndpoints.heartbeat({
this._heartbeatEndpoint({
channels: presenceChannels,

@@ -227,3 +240,3 @@ channelGroups: presenceChannelGroups,

this._subscribeCall = this._subscribeEndpoints.subscribe(subscribeArgs, this._processSubscribeResponse.bind(this));
this._subscribeCall = this._subscribeEndpoint(subscribeArgs, this._processSubscribeResponse.bind(this));
}

@@ -247,2 +260,10 @@

if (!this._subscriptionStatusAnnounced) {
let connectedAnnounce: StatusAnnouncement = {};
connectedAnnounce.category = 'PNConnectedCategory';
connectedAnnounce.operation = status.operation;
this._subscriptionStatusAnnounced = true;
this._listenerManager.announceStatus(connectedAnnounce);
}
payload.messages.forEach((message) => {

@@ -249,0 +270,0 @@ let channel = message.channel;

/* @flow */
import Networking from '../components/networking';
import Config from '../components/config';
import Crypto from '../components/cryptography/index';
import BaseEndpoint from './base.js';
import { EndpointDefinition, StatusAnnouncement } from '../flow_interfaces';
import { FetchHistoryArguments, HistoryResponse, HistoryItem, ModulesInject } from '../flow_interfaces';
type HistoryConstruct = {
networking: Networking,
crypto: Crypto,
config: Config
};
function __processMessage(modules, message: Object): Object | null {
let { config, crypto } = modules;
if (!config.cipherKey) return message;
type FetchHistoryArguments = {
channel: string, // fetch history from a channel
channelGroup: string, // fetch history from channel groups
start: number, // start timetoken for history fetching
end: number, // end timetoken for history feting
includeTimetoken: boolean, // include time token for each history call
reverse: boolean,
count: number
try {
return crypto.decrypt(message);
} catch (e) {
return message;
}
}
type HistoryItem = {
timetoken: number | null,
entry: any,
export function getOperation(): string {
return 'PNHistoryOperation';
}
type HistoryResponse = {
messages: Array<HistoryItem>,
startTimeToken: number,
endTimeToken: number,
export function validateParams(modules: ModulesInject, incomingParams: FetchHistoryArguments) {
let { channel } = incomingParams;
let { config } = modules;
if (!channel) return 'Missing channel';
if (!config.subscribeKey) return 'Missing Subscribe Key';
}
export default class extends BaseEndpoint {
networking: Networking;
crypto: Crypto;
config: Config;
export function getURL(modules: ModulesInject, incomingParams: FetchHistoryArguments): string {
let { channel } = incomingParams;
let { config } = modules;
return '/v2/history/sub-key/' + config.subscribeKey + '/channel/' + encodeURIComponent(channel);
}
constructor({ networking, crypto, config }: HistoryConstruct) {
super({ config });
this.networking = networking;
this.crypto = crypto;
this.config = config;
}
export function getRequestTimeout({ config }: ModulesInject) {
return config.getTransactionTimeout();
}
fetch(args: FetchHistoryArguments, callback: Function) {
const { channel, start, end, includeTimetoken, reverse, count = 100 } = args;
export function isAuthSupported() {
return true;
}
const endpointConfig: EndpointDefinition = {
params: {
authKey: { required: false },
uuid: { required: false },
subscribeKey: { required: true }
},
url: '/v2/history/sub-key/' + this.config.subscribeKey + '/channel/' + encodeURIComponent(channel)
};
export function prepareParams(modules: ModulesInject, incomingParams: FetchHistoryArguments): Object {
const { start, end, includeTimetoken, reverse, count = 100 } = incomingParams;
let outgoingParams = {};
if (!channel) return callback(this.createValidationError('Missing channel'));
if (!callback) return this.log('Missing Callback');
outgoingParams.count = count;
if (start) outgoingParams.start = start;
if (end) outgoingParams.end = end;
if (includeTimetoken != null) outgoingParams.include_token = includeTimetoken.toString();
if (reverse != null) outgoingParams.reverse = reverse.toString();
// validate this request and return false if stuff is missing
if (!this.validateEndpointConfig(endpointConfig)) { return; }
// create base params
const params = this.createBaseParams(endpointConfig);
params.count = count;
return outgoingParams;
}
if (start) params.start = start;
if (end) params.end = end;
if (includeTimetoken != null) params.include_token = includeTimetoken.toString();
if (reverse != null) params.reverse = reverse.toString();
export function handleResponse(modules: ModulesInject, serverResponse: FetchHistoryArguments): HistoryResponse {
const response: HistoryResponse = {
messages: [],
startTimeToken: parseInt(serverResponse[1], 10),
endTimeToken: parseInt(serverResponse[2], 10),
};
// Send Message
this.networking.GET(params, endpointConfig, (status: StatusAnnouncement, payload: Object) => {
if (status.error) return callback(status);
callback(status, this._parseResponse(payload, includeTimetoken));
});
}
_parseResponse(payload: Object, includeTimetoken: boolean): HistoryResponse {
const response: HistoryResponse = {
messages: [],
startTimeToken: parseInt(payload[1], 10),
endTimeToken: parseInt(payload[2], 10),
serverResponse[0].forEach((serverHistoryItem) => {
const item: HistoryItem = {
timetoken: null,
entry: null
};
payload[0].forEach((serverHistoryItem) => {
const item: HistoryItem = {
timetoken: null,
entry: null
};
if (serverHistoryItem.timetoken) {
item.timetoken = serverHistoryItem.timetoken;
item.entry = __processMessage(modules, serverHistoryItem.message);
} else {
item.entry = __processMessage(modules, serverHistoryItem);
}
if (includeTimetoken) {
item.timetoken = serverHistoryItem.timetoken;
item.entry = this.__processMessage(serverHistoryItem.message);
} else {
item.entry = this.__processMessage(serverHistoryItem);
}
response.messages.push(item);
});
response.messages.push(item);
});
return response;
}
__processMessage(message: Object): Object | null {
if (!this.config.cipherKey) return message;
try {
return this.crypto.decrypt(message);
} catch (e) {
return message;
}
}
return response;
}
/* @flow */
import Networking from '../components/networking';
import Config from '../components/config';
import Crypto from '../components/cryptography/index';
import BaseEndpoint from './base.js';
import { PublishResponse, PublishArguments, ModulesInject } from '../flow_interfaces';
import { EndpointDefinition, StatusAnnouncement } from '../flow_interfaces';
function prepareMessagePayload(modules, messagePayload) {
const { crypto, config } = modules;
let stringifiedPayload = JSON.stringify(messagePayload);
type PublishConstruct = {
networking: Networking,
config: Config,
crypto: Crypto
};
if (config.cipherKey) {
stringifiedPayload = crypto.encrypt(stringifiedPayload);
stringifiedPayload = JSON.stringify(stringifiedPayload);
}
type PublishResponse = {
timetoken: number
};
return stringifiedPayload;
}
type PublishArguments = {
message: Object | string | number | boolean, // the contents of the dispatch
channel: string, // the destination of our dispatch
sendByPost: boolean | null, // use POST when dispatching the message
storeInHistory: boolean | null, // store the published message in remote history
meta: Object, // psv2 supports filtering by metadata
replicate: boolean | null // indicates to server on replication status to other data centers.
export function getOperation(): string {
return 'PNPublishOperation';
}
export default class extends BaseEndpoint {
networking: Networking;
config: Config;
crypto: Crypto;
export function validateParams({ config}: ModulesInject, incomingParams: PublishArguments) {
let { message, channel } = incomingParams;
constructor({ networking, config, crypto }: PublishConstruct) {
super({ config });
this.networking = networking;
this.config = config;
this.crypto = crypto;
}
if (!channel) return 'Missing Channel';
if (!message) return 'Missing Message';
if (!config.subscribeKey) return 'Missing Subscribe Key';
}
fire(args: PublishArguments, callback: Function) {
args.replicate = false;
args.storeInHistory = false;
this.publish(args, callback);
}
export function usePost(modules: ModulesInject, incomingParams: PublishArguments) {
let { sendByPost = false } = incomingParams;
return sendByPost;
}
publish(args: PublishArguments, callback: Function) {
const { message, channel, meta, sendByPost = false, replicate = true, storeInHistory } = args;
const endpointConfig: EndpointDefinition = {
params: {
authKey: { required: false },
subscribeKey: { required: true },
publishKey: { required: true },
uuid: { required: false }
},
url: '/publish/' + this.config.publishKey + '/' + this.config.subscribeKey + '/0/' + encodeURIComponent(channel) + '/0'
};
export function getURL(modules: ModulesInject, incomingParams: PublishArguments): string {
const { config } = modules;
const { channel, message } = incomingParams;
let stringifiedPayload = prepareMessagePayload(modules, message);
return '/publish/' + config.publishKey + '/' + config.subscribeKey + '/0/' + encodeURIComponent(channel) + '/0/' + encodeURIComponent(stringifiedPayload);
}
if (!message) return callback(this.createValidationError('Missing Message'));
if (!channel) return callback(this.createValidationError('Missing Channel'));
export function postURL(modules: ModulesInject, incomingParams: PublishArguments): string {
const { config } = modules;
const { channel } = incomingParams;
return '/publish/' + config.publishKey + '/' + config.subscribeKey + '/0/' + encodeURIComponent(channel) + '/0';
}
// validate this request and return false if stuff is missing
if (!this.validateEndpointConfig(endpointConfig)) { return; }
// create base params
const params = this.createBaseParams(endpointConfig);
export function getRequestTimeout({ config }: ModulesInject) {
return config.getTransactionTimeout();
}
if (storeInHistory != null) {
if (storeInHistory) {
params.store = '1';
} else {
params.store = '0';
}
}
export function isAuthSupported() {
return true;
}
if (replicate === false) {
params.norep = 'true';
}
export function postPayload(modules: ModulesInject, incomingParams: PublishArguments): string {
const { message } = incomingParams;
return prepareMessagePayload(modules, message);
}
if (meta && typeof meta === 'object') {
params.meta = JSON.stringify(meta);
export function prepareParams(modules: ModulesInject, incomingParams: PublishArguments): Object {
const { meta, replicate = true, storeInHistory } = incomingParams;
const params = {};
if (storeInHistory != null) {
if (storeInHistory) {
params.store = '1';
} else {
params.store = '0';
}
}
let onCallback = (status: StatusAnnouncement, payload: Object) => {
if (status.error) return callback(status);
if (replicate === false) {
params.norep = 'true';
}
let response: PublishResponse = {
timetoken: payload[2]
};
if (meta && typeof meta === 'object') {
params.meta = JSON.stringify(meta);
}
callback(status, response);
};
return params;
}
let stringifiedPayload = JSON.stringify(message);
if (this.config.cipherKey) {
stringifiedPayload = this.crypto.encrypt(stringifiedPayload);
stringifiedPayload = JSON.stringify(stringifiedPayload);
}
if (sendByPost) {
this.networking.POST(params, stringifiedPayload, endpointConfig, onCallback);
} else {
endpointConfig.url += '/' + encodeURIComponent(stringifiedPayload);
this.networking.GET(params, endpointConfig, onCallback);
}
}
export function handleResponse(modules: ModulesInject, serverResponse: Object): PublishResponse {
return { timetoken: serverResponse[2] };
}
/* @flow */
import Networking from '../components/networking';
import Config from '../components/config';
import { SubscribeArguments, PublishMetaData, SubscribeMetadata, SubscribeMessage, SubscribeEnvelope, ModulesInject } from '../flow_interfaces';
import BaseEndpoint from './base.js';
export function getOperation(): string {
return 'PNSubscribeOperation';
}
import { EndpointDefinition, StatusAnnouncement, PublishMetaData,
SubscribeMetadata, SubscribeMessage, SubscribeEnvelope } from '../flow_interfaces';
export function validateParams(modules: ModulesInject) {
let { config } = modules;
type PubSubConstruct = {
networking: Networking,
config: Config,
};
if (!config.subscribeKey) return 'Missing Subscribe Key';
}
type SubscribeArguments = {
channels: Array<string>,
channelGroups: Array<string>,
timetoken: number,
filterExpression: ?string,
region: ?string,
export function getURL(modules: ModulesInject, incomingParams: SubscribeArguments): string {
let { config } = modules;
let { channels = [] } = incomingParams;
let stringifiedChannels = channels.length > 0 ? channels.join(',') : ',';
return '/v2/subscribe/' + config.subscribeKey + '/' + encodeURIComponent(stringifiedChannels) + '/0';
}
export function getRequestTimeout({ config }: ModulesInject) {
return config.getSubscribeTimeout();
}
export default class extends BaseEndpoint {
_networking: Networking;
_config: Config;
export function isAuthSupported() {
return true;
}
constructor({ networking, config }: PubSubConstruct) {
super({ config });
this._networking = networking;
this._config = config;
export function prepareParams({ config }: ModulesInject, incomingParams: SubscribeArguments): Object {
let { channelGroups = [], timetoken, filterExpression, region } = incomingParams;
const params: Object = {
heartbeat: config.getPresenceTimeout()
};
if (channelGroups.length > 0) {
params['channel-group'] = encodeURIComponent(channelGroups.join(','));
}
subscribe(args: SubscribeArguments, callback: Function) {
let { channels = [], channelGroups = [], timetoken, filterExpression, region } = args;
let stringifiedChannels = channels.length > 0 ? channels.join(',') : ',';
const endpointConfig: EndpointDefinition = {
params: {
authKey: { required: false },
uuid: {},
subscribeKey: { required: true }
},
timeout: this._config.getSubscribeTimeout(),
url: '/v2/subscribe/' + this._config.subscribeKey + '/' + encodeURIComponent(stringifiedChannels) + '/0'
};
if (filterExpression && filterExpression.length > 0) {
params['filter-expr'] = encodeURIComponent(filterExpression);
}
// validate this request and return false if stuff is missing
if (!this.validateEndpointConfig(endpointConfig)) { return; }
// create base params
const params = this.createBaseParams(endpointConfig);
if (timetoken) {
params.tt = timetoken;
}
if (channelGroups.length > 0) {
params['channel-group'] = encodeURIComponent(channelGroups.join(','));
}
if (region) {
params.tr = region;
}
if (filterExpression && filterExpression.length > 0) {
params['filter-expr'] = encodeURIComponent(filterExpression);
}
return params;
}
if (timetoken) {
params.tt = timetoken;
}
export function handleResponse(modules: ModulesInject, serverResponse: Object): SubscribeEnvelope {
const messages: Array<SubscribeMessage> = [];
if (region) {
params.tr = region;
}
serverResponse.m.forEach((rawMessage) => {
let publishMetaData: PublishMetaData = {
publishTimetoken: rawMessage.p.t,
region: rawMessage.p.r
};
let parsedMessage: SubscribeMessage = {
shard: parseInt(rawMessage.a, 10),
subscriptionMatch: rawMessage.b,
channel: rawMessage.c,
payload: rawMessage.d,
flags: rawMessage.f,
issuingClientId: rawMessage.i,
subscribeKey: rawMessage.k,
originationTimetoken: rawMessage.o,
publishMetaData
};
messages.push(parsedMessage);
});
return this._networking.GET(params, endpointConfig, (status: StatusAnnouncement, payload: Object) => {
if (status.error) return callback(status);
const metadata: SubscribeMetadata = {
timetoken: serverResponse.t.t,
region: serverResponse.t.r
};
const messages: Array<SubscribeMessage> = [];
payload.m.forEach((rawMessage) => {
let publishMetaData: PublishMetaData = {
publishTimetoken: rawMessage.p.t,
region: rawMessage.p.r
};
let parsedMessage: SubscribeMessage = {
shard: parseInt(rawMessage.a, 10),
subscriptionMatch: rawMessage.b,
channel: rawMessage.c,
payload: rawMessage.d,
flags: rawMessage.f,
issuingClientId: rawMessage.i,
subscribeKey: rawMessage.k,
originationTimetoken: rawMessage.o,
publishMetaData
};
messages.push(parsedMessage);
});
const metadata: SubscribeMetadata = {
timetoken: payload.t.t,
region: payload.t.r
};
const response: SubscribeEnvelope = { messages, metadata };
callback(status, response);
});
}
return { messages, metadata };
}
/* @flow */
import Networking from '../components/networking';
import Config from '../components/config';
import BaseEndpoint from './base.js';
import { EndpointDefinition, StatusAnnouncement, TimeResponse } from '../flow_interfaces';
import { TimeResponse, ModulesInject } from '../flow_interfaces';
type TimeConstruct = {
networking: Networking,
config: Config
};
export function getOperation(): string {
return 'PNTimeOperation';
}
export default class extends BaseEndpoint {
export function getURL(): string {
return '/time/0';
}
_networking: Networking;
export function getRequestTimeout({ config }: ModulesInject) {
return config.getTransactionTimeout();
}
constructor({ networking, config }: TimeConstruct) {
super({ config });
this._networking = networking;
}
export function prepareParams(): Object {
return {};
}
fetch(callback: Function) {
const endpointConfig: EndpointDefinition = {
params: {
uuid: { required: false }
},
url: '/time/0'
};
export function isAuthSupported() {
return false;
}
// validate this request and return false if stuff is missing
if (!this.validateEndpointConfig(endpointConfig)) { return; }
export function handleResponse(modules: ModulesInject, serverResponse: Object): TimeResponse {
return {
timetoken: serverResponse[0]
};
}
// create base params
const params = this.createBaseParams(endpointConfig);
this._networking.GET(params, endpointConfig, (status: StatusAnnouncement, payload: Object) => {
if (status.error) return callback(status);
let response: TimeResponse = {
timetoken: payload[0]
};
callback(status, response);
});
}
export function validateParams() {
// pass
}

@@ -152,4 +152,192 @@ /* eslint no-unused-vars: 0 */

// history
type FetchHistoryArguments = {
channel: string, // fetch history from a channel
channelGroup: string, // fetch history from channel groups
start: number, // start timetoken for history fetching
end: number, // end timetoken for history feting
includeTimetoken: boolean, // include time token for each history call
reverse: boolean,
count: number
}
type HistoryItem = {
timetoken: number | null,
entry: any,
}
type HistoryResponse = {
messages: Array<HistoryItem>,
startTimeToken: number,
endTimeToken: number,
}
// CG endpoints
type AddChannelParams = {
channels: Array<string>,
channelGroup: string,
}
type RemoveChannelParams = {
channels: Array<string>,
channelGroup: string,
}
type DeleteGroupParams = {
channelGroup: string,
}
type ListAllGroupsResponse = {
groups: Array<string>
}
type ListChannelsParams = {
channelGroup: string,
}
type ListChannelsResponse = {
channels: Array<string>
}
//
// push
type ProvisionDeviceArgs = {
operation: 'add' | 'remove',
pushGateway: 'gcm' | 'apns' | 'mpns',
device: string,
channels: Array<string>
};
type ModifyDeviceArgs = {
pushGateway: 'gcm' | 'apns' | 'mpns',
device: string,
channels: Array<string>
};
type ListChannelsArgs = {
pushGateway: 'gcm' | 'apns' | 'mpns',
device: string,
};
type RemoveDeviceArgs = {
pushGateway: 'gcm' | 'apns' | 'mpns',
device: string,
};
type ListPushChannelsResponse = {
channels: Array<string>
}
//
// presence
type LeaveArguments = {
channels: Array<string>,
channelGroups: Array<string>,
}
type HereNowArguments = {
channels: Array<string>,
channelGroups: Array<string>,
includeUUIDs: boolean,
includeState: boolean
}
type WhereNowArguments = {
uuid: string,
}
type WhereNowResponse = {
channels: Array<string>,
}
//
type GetStateArguments = {
uuid: string,
channels: Array<string>,
channelGroups: Array<string>
}
type GetStateResponse = {
channels: Object
}
//
type SetStateArguments = {
channels: Array<string>,
channelGroups: Array<string>,
state: Object
}
type SetStateResponse = {
state: Object
}
type HeartbeatArguments = {
channels: Array<string>,
channelGroups: Array<string>,
state: Object
}
//
// subscribe
type SubscribeArguments = {
channels: Array<string>,
channelGroups: Array<string>,
timetoken: number,
filterExpression: ?string,
region: ?string,
}
//
// access manager
type AuditArguments = {
channel: string,
channelGroup: string,
authKeys: Array<string>,
}
type GrantArguments = {
channels: Array<string>,
channelGroups: Array<string>,
ttl: number,
read: boolean,
write: boolean,
manage: boolean,
authKeys: Array<string>
}
// publish
type PublishResponse = {
timetoken: number
};
type PublishArguments = {
message: Object | string | number | boolean, // the contents of the dispatch
channel: string, // the destination of our dispatch
sendByPost: boolean | null, // use POST when dispatching the message
storeInHistory: boolean | null, // store the published message in remote history
meta: Object, // psv2 supports filtering by metadata
replicate: boolean | null // indicates to server on replication status to other data centers.
}
//
type ModulesInject = {
config: Object;
}
module.exports = {};

@@ -9,13 +9,32 @@ /* @flow */

import endpointCreator from './components/endpoint';
import * as addChannelsChannelGroupConfig from './endpoints/channel_groups/add_channels';
import * as removeChannelsChannelGroupConfig from './endpoints/channel_groups/remove_channels';
import * as deleteChannelGroupConfig from './endpoints/channel_groups/delete_group';
import * as listChannelGroupsConfig from './endpoints/channel_groups/list_groups';
import * as listChannelsInChannelGroupConfig from './endpoints/channel_groups/list_channels';
import * as addPushChannelsConfig from './endpoints/push/add_push_channels';
import * as removePushChannelsConfig from './endpoints/push/remove_push_channels';
import * as listPushChannelsConfig from './endpoints/push/list_push_channels';
import * as removeDevicePushConfig from './endpoints/push/remove_device';
import * as presenceLeaveEndpointConfig from './endpoints/presence/leave';
import * as presenceWhereNowEndpointConfig from './endpoints/presence/where_now';
import * as presenceHeartbeatEndpointConfig from './endpoints/presence/heartbeat';
import * as presenceGetStateConfig from './endpoints/presence/get_state';
import * as presenceSetStateConfig from './endpoints/presence/set_state';
import * as presenceHereNowConfig from './endpoints/presence/here_now';
import * as auditEndpointConfig from './endpoints/access_manager/audit';
import * as grantEndpointConfig from './endpoints/access_manager/grant';
import * as publishEndpointConfig from './endpoints/publish';
import * as historyEndpointConfig from './endpoints/history';
import * as timeEndpointConfig from './endpoints/time';
import * as subscribeEndpointConfig from './endpoints/subscribe';
import packageJSON from '../../package.json';
import TimeEndpoint from './endpoints/time';
import PresenceEndpoints from './endpoints/presence';
import HistoryEndpoint from './endpoints/history';
import PushEndpoint from './endpoints/push';
import AccessEndpoints from './endpoints/access';
import ChannelGroupEndpoints from './endpoints/channel_groups';
import SubscribeEndpoints from './endpoints/subscribe';
import PublishEndpoints from './endpoints/publish';
import { InternalSetupStruct } from './flow_interfaces';

@@ -26,4 +45,2 @@

_config: Config;
_crypto: Crypto;
_networking: Networking;

@@ -63,2 +80,5 @@ // tell flow about the mounted endpoint

getFilterExpression: Function;
setFilterExpression: Function;
//

@@ -69,18 +89,25 @@

this._config = new Config({ setup, db });
this._crypto = new Crypto({ config: this._config });
this._networking = new Networking({ config: this._config, crypto: this._crypto, sendBeacon });
const config = this._config = new Config({ setup, db });
const crypto = new Crypto({ config });
const networking = new Networking({ config, crypto, sendBeacon });
const subscribeEndpoints = new SubscribeEndpoints({ networking: this._networking, config: this._config });
const presenceEndpoints = new PresenceEndpoints({ networking: this._networking, config: this._config });
const timeEndpoints = new TimeEndpoint({ networking: this._networking, config: this._config });
const pushEndpoints = new PushEndpoint({ networking: this._networking, config: this._config });
const channelGroupEndpoints = new ChannelGroupEndpoints({ networking: this._networking, config: this._config });
const publishEndpoints = new PublishEndpoints({ networking: this._networking, config: this._config, crypto: this._crypto });
const historyEndpoint = new HistoryEndpoint({ networking: this._networking, config: this._config, crypto: this._crypto });
const accessEndpoints = new AccessEndpoints({ config: this._config, networking: this._networking, crypto: this._crypto });
let modules = { config, networking, crypto };
const listenerManager = new ListenerManager();
const subscriptionManager = new SubscriptionManager({ config: this._config, listenerManager, subscribeEndpoints, presenceEndpoints, timeEndpoints });
// new
const timeEndpoint = endpointCreator.bind(this, modules, timeEndpointConfig);
const leaveEndpoint = endpointCreator.bind(this, modules, presenceLeaveEndpointConfig);
const heartbeatEndpoint = endpointCreator.bind(this, modules, presenceHeartbeatEndpointConfig);
const setStateEndpoint = endpointCreator.bind(this, modules, presenceSetStateConfig);
const subscribeEndpoint = endpointCreator.bind(this, modules, subscribeEndpointConfig);
//
const subscriptionManager = new SubscriptionManager({
timeEndpoint,
leaveEndpoint, heartbeatEndpoint, setStateEndpoint,
subscribeEndpoint,
config: modules.config,
listenerManager,
});
this.addListener = listenerManager.addListener.bind(listenerManager);

@@ -91,28 +118,36 @@ this.removeListener = listenerManager.removeListener.bind(listenerManager);

this.channelGroups = {
listGroups: channelGroupEndpoints.listGroups.bind(channelGroupEndpoints),
listChannels: channelGroupEndpoints.listChannels.bind(channelGroupEndpoints),
addChannels: channelGroupEndpoints.addChannels.bind(channelGroupEndpoints),
removeChannels: channelGroupEndpoints.removeChannels.bind(channelGroupEndpoints),
deleteGroup: channelGroupEndpoints.deleteGroup.bind(channelGroupEndpoints)
listGroups: endpointCreator.bind(this, modules, listChannelGroupsConfig),
listChannels: endpointCreator.bind(this, modules, listChannelsInChannelGroupConfig),
addChannels: endpointCreator.bind(this, modules, addChannelsChannelGroupConfig),
removeChannels: endpointCreator.bind(this, modules, removeChannelsChannelGroupConfig),
deleteGroup: endpointCreator.bind(this, modules, deleteChannelGroupConfig)
};
/** push **/
this.push = {
addChannels: pushEndpoints.addDeviceToPushChannels.bind(pushEndpoints),
removeChannels: pushEndpoints.removeDeviceFromPushChannels.bind(pushEndpoints),
deleteDevice: pushEndpoints.removeDevice.bind(pushEndpoints),
listChannels: pushEndpoints.listChannelsForDevice.bind(pushEndpoints)
addChannels: endpointCreator.bind(this, modules, addPushChannelsConfig),
removeChannels: endpointCreator.bind(this, modules, removePushChannelsConfig),
deleteDevice: endpointCreator.bind(this, modules, removeDevicePushConfig),
listChannels: endpointCreator.bind(this, modules, listPushChannelsConfig)
};
/** presence **/
this.hereNow = presenceEndpoints.hereNow.bind(presenceEndpoints);
this.whereNow = presenceEndpoints.whereNow.bind(presenceEndpoints);
this.getState = presenceEndpoints.getState.bind(presenceEndpoints);
this.hereNow = endpointCreator.bind(this, modules, presenceHereNowConfig);
this.whereNow = endpointCreator.bind(this, modules, presenceWhereNowEndpointConfig);
this.getState = endpointCreator.bind(this, modules, presenceGetStateConfig);
this.setState = subscriptionManager.adaptStateChange.bind(subscriptionManager);
/** PAM **/
this.grant = accessEndpoints.grant.bind(accessEndpoints);
this.audit = accessEndpoints.audit.bind(accessEndpoints);
this.grant = endpointCreator.bind(this, modules, grantEndpointConfig);
this.audit = endpointCreator.bind(this, modules, auditEndpointConfig);
//
this.publish = publishEndpoints.publish.bind(publishEndpoints);
this.fire = publishEndpoints.fire.bind(publishEndpoints);
this.history = historyEndpoint.fetch.bind(historyEndpoint);
this.time = timeEndpoints.fetch.bind(timeEndpoints);
this.publish = endpointCreator.bind(this, modules, publishEndpointConfig);
this.fire = (args, callback) => {
args.replicate = false;
args.storeInHistory = false;
this.publish(args, callback);
};
this.history = endpointCreator.bind(this, modules, historyEndpointConfig);
this.time = timeEndpoint;
// subscription related methods

@@ -123,10 +158,11 @@ this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager);

this.stop = subscriptionManager.disconnect.bind(subscriptionManager);
this.reconnect = subscriptionManager.reconnect.bind(SubscriptionManager);
/** config **/
this.getAuthKey = this._config.getAuthKey.bind(this._config);
this.setAuthKey = this._config.setAuthKey.bind(this._config);
this.setCipherKey = this._config.setCipherKey.bind(this._config);
this.getUUID = this._config.getUUID.bind(this._config);
this.setUUID = this._config.setUUID.bind(this._config);
this.getAuthKey = modules.config.getAuthKey.bind(modules.config);
this.setAuthKey = modules.config.setAuthKey.bind(modules.config);
this.setCipherKey = modules.config.setCipherKey.bind(modules.config);
this.getUUID = modules.config.getUUID.bind(modules.config);
this.setUUID = modules.config.setUUID.bind(modules.config);
this.getFilterExpression = modules.config.getFilterExpression.bind(modules.config);
this.setFilterExpression = modules.config.setFilterExpression.bind(modules.config);
}

@@ -133,0 +169,0 @@

@@ -20,13 +20,2 @@ /* @flow */

// Test Connection State
function navigatorOnlineCheck(): boolean | null {
// if onLine is not supported, return nothing.
if (!('onLine' in navigator)) {
return null;
}
return navigator.onLine;
}
function sendBeacon(url: string) {

@@ -45,3 +34,2 @@ if (navigator && navigator.sendBeacon) {

setup.db = db;
setup.navigatorOnlineCheck = navigatorOnlineCheck;
setup.sendBeacon = sendBeacon;

@@ -53,4 +41,8 @@ setup.params = {

super(setup);
// mount network events.
window.addEventListener('offline', this.stop.bind(this));
window.addEventListener('online', this.reconnect.bind(this));
}
}

@@ -26,12 +26,12 @@ /* global describe, it, __dirname */

it('with npm valid entry point', () => {
assert.equal(packageJSON.main, './node.js/pubnub.js');
assert.equal(packageJSON.main, './lib/node/index.js');
});
it('with updated readme', () => {
assert(readMe.indexOf('http://cdn.pubnub.com/pubnub-' + versionFile + '.js') > 1);
assert(readMe.indexOf('http://cdn.pubnub.com/pubnub-' + versionFile + '.min.js') > 1);
assert(readMe.indexOf('http://cdn.pubnub.com/sdk/javascript/pubnub-' + versionFile + '.js') > 1);
assert(readMe.indexOf('http://cdn.pubnub.com/sdk/javascript/pubnub-' + versionFile + '.min.js') > 1);
assert(readMe.indexOf('https://cdn.pubnub.com/pubnub-' + versionFile + '.js') > 1);
assert(readMe.indexOf('https://cdn.pubnub.com/pubnub-' + versionFile + '.min.js') > 1);
assert(readMe.indexOf('https://cdn.pubnub.com/sdk/javascript/pubnub-' + versionFile + '.js') > 1);
assert(readMe.indexOf('https://cdn.pubnub.com/sdk/javascript/pubnub-' + versionFile + '.min.js') > 1);
});
});

@@ -14,7 +14,8 @@ var webpack = require('webpack');

net: 'empty',
tls: 'empty'
tls: 'empty',
formidable: 'empty'
},
output: {
filename: 'pubnub.js',
library: 'PUBNUB',
library: 'PubNub',
libraryTarget: 'umd',

@@ -21,0 +22,0 @@ },

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc