Socket
Socket
Sign inDemoInstall

twilio-sync

Package Overview
Dependencies
Maintainers
1
Versions
608
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

twilio-sync - npm Package Compare versions

Comparing version 3.2.2 to 4.0.0-canary.2

dist/_virtual/_commonjsHelpers.js

48

dist/client.js

@@ -125,2 +125,3 @@ /*

var replayEventEmitter = require('@twilio/replay-event-emitter');
var browser = require('./packages/shared/builds/browser.js');

@@ -166,2 +167,3 @@ const SYNC_PRODUCT_ID = 'data_sync';

super();
this._currentState = 'disconnected';
if (!fpaToken) {

@@ -194,15 +196,22 @@ throw new Error('Sync library needs a valid Twilio token to be passed');

}
let twilsock$1 = options.twilsockClient = (_a = options.twilsockClient) !== null && _a !== void 0 ? _a : new twilsock.Twilsock(fpaToken, productId, options);
let twilsock$1 = options.twilsockClient = (_a = options.twilsockClient) !== null && _a !== void 0 ? _a : new twilsock.TwilsockClient(fpaToken, productId, options);
twilsock$1.on('tokenAboutToExpire', () => this.emit('tokenAboutToExpire'));
twilsock$1.on('tokenExpired', () => this.emit('tokenExpired'));
twilsock$1.on('connectionError', err => this.emit('connectionError', err));
twilsock$1.on('stateChanged', (state) => {
this.emit('connectionStateChanged', state);
/**
* Handle transport establishing event
* If we have any subscriptions - we should check object for modifications
*/
this.services.subscriptions.onConnectionStateChanged(state === 'connected');
// twilsock.on('connectionError', err => this.emit('connectionError', err));
twilsock$1.on('connecting', () => {
this._currentState = 'connecting';
this.emit('connectionStateChanged', 'connecting');
this.services.subscriptions.onConnectionStateChanged(false);
});
twilsock$1.on('message', (messageType, payload) => this._routeMessage(messageType, payload));
twilsock$1.on('connected', () => {
this._currentState = 'connected';
this.emit('connectionStateChanged', 'connected');
this.services.subscriptions.onConnectionStateChanged(true);
});
twilsock$1.on('disconnected', () => {
this._currentState = 'disconnected';
this.emit('connectionStateChanged', 'disconnected');
this.services.subscriptions.onConnectionStateChanged(false);
});
twilsock$1.on('targetedMessageReceived', (messageType, payload) => this._routeMessage(messageType, JSON.parse(payload)));
let config = new configuration.Configuration(options);

@@ -228,4 +237,4 @@ let network$1 = new network.NetworkService(new clientInfo["default"](SDK_VERSION), config, twilsock$1);

static populateInitRegistrations(reg) {
reg.populateInitRegistrations([SYNC_NOTIFICATION_TYPE, SYNC_DOCUMENT_NOTIFICATION_TYPE,
SYNC_LIST_NOTIFICATION_TYPE, SYNC_MAP_NOTIFICATION_TYPE]);
// reg.populateInitRegistrations([SYNC_NOTIFICATION_TYPE, SYNC_DOCUMENT_NOTIFICATION_TYPE,
// SYNC_LIST_NOTIFICATION_TYPE, SYNC_MAP_NOTIFICATION_TYPE]);
}

@@ -278,3 +287,3 @@ /**

get connectionState() {
return this.services.twilsock.state;
return this._currentState;
}

@@ -291,9 +300,2 @@ /**

}
try {
let storageSettings = await this.services.twilsock.storageId();
this.services.storage.updateStorageId(storageSettings.id);
}
catch (e) {
logger["default"].warn('Failed to initialize storage', e);
}
}

@@ -657,3 +659,3 @@ storeRootInSessionCache(type, id, value) {

await this.services.subscriptions.shutdown();
await this.services.twilsock.disconnect();
await this.services.network.disconnect();
}

@@ -667,5 +669,3 @@ /**

.catch((error) => {
var _a;
const status = (_a = error === null || error === void 0 ? void 0 : error.reply) === null || _a === void 0 ? void 0 : _a.status;
if ((status === null || status === void 0 ? void 0 : status.code) === 401 && (status === null || status === void 0 ? void 0 : status.status) === 'UNAUTHORIZED') {
if (error instanceof browser.TwilioError && error.errorInfo.status === 401) {
throw new syncerror.SyncError('Updated token was rejected by server', 400, 51130);

@@ -672,0 +672,0 @@ }

@@ -105,4 +105,4 @@ /*

var uuid = require('uuid');
var replayEventEmitter = require('@twilio/replay-event-emitter');
var require$$9 = require('nanoid');

@@ -113,3 +113,3 @@ class Closeable extends replayEventEmitter.ReplayEventEmitter {

this.closed = false;
this.uuid = uuid.v4();
this.uuid = require$$9.nanoid();
}

@@ -116,0 +116,0 @@ get listenerUuid() {

@@ -278,10 +278,2 @@ /*

class LiveQuery extends closeable.Closeable {
/**
* @internal
*/
constructor(liveQueryImpl) {
super();
this.liveQueryImpl = liveQueryImpl;
this.liveQueryImpl.attach(this);
}
// private props

@@ -304,2 +296,10 @@ static get type() {

/**
* @internal
*/
constructor(liveQueryImpl) {
super();
this.liveQueryImpl = liveQueryImpl;
this.liveQueryImpl.attach(this);
}
/**
* Closes this query instance and unsubscribes from further service events.

@@ -358,2 +358,9 @@ * This will eventually stop the physical inflow of updates over the network, when all other instances of this query are closed as well.

class InstantQuery extends replayEventEmitter.ReplayEventEmitter {
// private props
static get type() {
return 'instant_query';
}
get type() {
return InstantQuery.type;
}
/**

@@ -369,9 +376,2 @@ * @internal

}
// private props
static get type() {
return 'instant_query';
}
get type() {
return InstantQuery.type;
}
/**

@@ -378,0 +378,0 @@ * Spawns a new search request. The result will be provided asynchronously via the {@link InstantQuery.searchResult}

@@ -105,5 +105,5 @@ /*

var version = "3.2.2";
var version = "4.0.0-rc.1";
exports.version = version;
//# sourceMappingURL=package.json.js.map

@@ -105,28 +105,9 @@ /*

var uuid = require('uuid');
var syncerror = require('../utils/syncerror.js');
var logger = require('../utils/logger.js');
var operationRetrier = require('@twilio/operation-retrier');
var require$$9 = require('nanoid');
var browser = require('../packages/shared/builds/browser.js');
var twilsock = require('twilsock');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var uuid__namespace = /*#__PURE__*/_interopNamespace(uuid);
const MINIMUM_RETRY_DELAY = 4000;

@@ -136,9 +117,8 @@ const MAXIMUM_RETRY_DELAY = 60000;

const RETRY_DELAY_RANDOMNESS = 0.2;
function messageFromErrorBody(transportError) {
if (transportError.body) {
if (transportError.body.message) {
return transportError.body.message;
}
const sidGenerator = require$$9.customAlphabet('1234567890abcdef', 32);
function messageFromErrorBody(transportError, payload) {
if (payload === null || payload === void 0 ? void 0 : payload.message) {
return payload.message;
}
switch (transportError.status) {
switch (transportError.statusCode) {
case 429:

@@ -152,20 +132,20 @@ return 'Throttled by server';

}
function codeFromErrorBody(trasportError) {
if (trasportError.body) {
return trasportError.body.code;
}
return 0;
function codeFromErrorBody(payload) {
var _a;
return (_a = payload === null || payload === void 0 ? void 0 : payload.code) !== null && _a !== void 0 ? _a : 0;
}
function mapTransportError(transportError) {
if (transportError.status === 409) {
return new syncerror.SyncNetworkError(messageFromErrorBody(transportError), transportError.status, codeFromErrorBody(transportError), transportError.body);
function mapTransportError(transportError, payload) {
var _a, _b;
if (transportError.statusCode === 409) {
return new syncerror.SyncNetworkError(messageFromErrorBody(transportError, payload), transportError.statusCode, codeFromErrorBody(payload), payload);
}
else if (transportError.status) {
return new syncerror.SyncError(messageFromErrorBody(transportError), transportError.status, codeFromErrorBody(transportError));
else if (transportError.statusCode) {
return new syncerror.SyncError(messageFromErrorBody(transportError, payload), transportError.statusCode, codeFromErrorBody(payload));
// todo: still idk
}
else if (transportError instanceof twilsock.TransportUnavailableError) {
else if (transportError instanceof browser.TwilioError && transportError.errorInfo.reason === 'transportDisconnected') {
return transportError;
}
else {
return new syncerror.SyncError(transportError.message, 0, 0);
return new syncerror.SyncError((_b = (_a = payload === null || payload === void 0 ? void 0 : payload.message) !== null && _a !== void 0 ? _a : transportError.message) !== null && _b !== void 0 ? _b : 'Unexpected error', 0, 0);
}

@@ -178,5 +158,7 @@ }

constructor(clientInfo, config, transport) {
this.isShutdownInitiated = false;
this.clientInfo = clientInfo;
this.config = config;
this.transport = transport;
this.pendingRequests = new Set();
}

@@ -187,3 +169,3 @@ createHeaders() {

'Twilio-Sync-Client-Info': JSON.stringify(this.clientInfo),
'Twilio-Request-Id': 'RQ' + uuid__namespace.v4().replace(/-/g, '')
'Twilio-Request-Id': `RQ${sidGenerator()}`
};

@@ -208,11 +190,20 @@ }

request()
.then(result => retrier.succeeded(result))
.catch(err => {
if (codesToRetryOn.includes(err.status)) {
let delayOverride = parseInt(err.headers ? err.headers['Retry-After'] : null);
retrier.failed(mapTransportError(err), isNaN(delayOverride) ? null : delayOverride * 1000);
.then(result => {
const isError = result.statusCode >= 400;
if (!isError) {
retrier.succeeded(result);
return;
}
else if (err.message === 'Twilsock disconnected') {
let parsedPayload = {};
try {
parsedPayload = JSON.parse(result.payload);
}
catch (_a) { }
if (codesToRetryOn.includes(result.statusCode)) {
let delayOverride = parseInt(result.headers ? result.headers['Retry-After'] : null);
retrier.failed(mapTransportError(result, parsedPayload), isNaN(delayOverride) ? null : delayOverride * 1000);
}
else if (parsedPayload.message === 'Twilsock disconnected') {
// Ugly hack. We must make a proper exceptions for twilsock
retrier.failed(mapTransportError(err));
retrier.failed(mapTransportError(result, parsedPayload));
}

@@ -223,4 +214,10 @@ else {

retrier.cancel();
reject(mapTransportError(err));
reject(mapTransportError(result, parsedPayload));
}
})
.catch(err => {
// Fatal error
retrier.removeAllListeners();
retrier.cancel();
reject(mapTransportError(err, null));
});

@@ -231,7 +228,23 @@ });

});
retrier.on('cancelled', err => reject(mapTransportError(err)));
retrier.on('failed', err => reject(mapTransportError(err)));
retrier.on('cancelled', err => reject(mapTransportError(err, null)));
retrier.on('failed', err => reject(mapTransportError(err, null)));
retrier.start();
});
}
responsePostProcess(response) {
let body = {};
try {
body = JSON.parse(response.payload);
}
catch (_a) {
}
return {
status: {
code: response.statusCode,
status: response.status,
},
headers: response.headers,
body,
};
}
/**

@@ -242,7 +255,18 @@ * Make a GET request by given URI

get(uri) {
if (this.isShutdownInitiated) {
throw new Error('Client has been shut down.');
}
let headers = this.createHeaders();
logger["default"].debug('GET', uri, 'ID:', headers['Twilio-Request-Id']);
return this.executeWithRetry(() => this.transport.get(uri, headers, this.config.productId), true);
const responsePromise = this.executeWithRetry(() => this.transport.sendRequest(new twilsock.HttpRequest({ url: uri, headers, grant: this.config.productId })), true);
this.pendingRequests.add(responsePromise);
return responsePromise.then((response) => {
this.pendingRequests.delete(responsePromise);
return this.responsePostProcess(response);
});
}
post(uri, body, revision, retryWhenThrottled = false) {
if (this.isShutdownInitiated) {
throw new Error('Client has been shut down.');
}
let headers = this.createHeaders();

@@ -253,5 +277,13 @@ if (typeof revision !== 'undefined' && revision !== null) {

logger["default"].debug('POST', uri, 'ID:', headers['Twilio-Request-Id']);
return this.executeWithRetry(() => this.transport.post(uri, headers, body, this.config.productId), retryWhenThrottled);
const responsePromise = this.executeWithRetry(() => this.transport.sendRequest(new twilsock.HttpRequest({ method: 'POST', url: uri, headers, payload: body, grant: this.config.productId })), retryWhenThrottled);
this.pendingRequests.add(responsePromise);
return responsePromise.then((response) => {
this.pendingRequests.delete(responsePromise);
return this.responsePostProcess(response);
});
}
put(uri, body, revision) {
if (this.isShutdownInitiated) {
throw new Error('Client has been shut down.');
}
let headers = this.createHeaders();

@@ -262,9 +294,30 @@ if (typeof revision !== 'undefined' && revision !== null) {

logger["default"].debug('PUT', uri, 'ID:', headers['Twilio-Request-Id']);
return this.executeWithRetry(() => this.transport.put(uri, headers, body, this.config.productId), false);
const responsePromise = this.executeWithRetry(() => this.transport.sendRequest(new twilsock.HttpRequest({ method: 'PUT', url: uri, headers, payload: body, grant: this.config.productId })), false);
this.pendingRequests.add(responsePromise);
return responsePromise.then((response) => {
this.pendingRequests.delete(responsePromise);
return this.responsePostProcess(response);
});
}
delete(uri) {
if (this.isShutdownInitiated) {
throw new Error('Client has been shut down.');
}
let headers = this.createHeaders();
logger["default"].debug('DELETE', uri, 'ID:', headers['Twilio-Request-Id']);
return this.executeWithRetry(() => this.transport.delete(uri, headers, this.config.productId), false);
const responsePromise = this.executeWithRetry(() => this.transport.sendRequest(new twilsock.HttpRequest({ method: 'DELETE', url: uri, headers, grant: this.config.productId })), false);
this.pendingRequests.add(responsePromise);
return responsePromise.then((response) => {
this.pendingRequests.delete(responsePromise);
return this.responsePostProcess(response);
});
}
async disconnect() {
this.isShutdownInitiated = true;
try {
await Promise.all([...this.pendingRequests]);
}
catch (_a) { }
await this.transport.disconnect();
}
}

@@ -271,0 +324,0 @@

@@ -224,10 +224,2 @@ /*

class SyncStream extends closeable.Closeable {
/**
* @internal
*/
constructor(syncStreamImpl) {
super();
this.syncStreamImpl = syncStreamImpl;
this.syncStreamImpl.attach(this);
}
// private props

@@ -265,2 +257,10 @@ get uri() {

/**
* @internal
*/
constructor(syncStreamImpl) {
super();
this.syncStreamImpl = syncStreamImpl;
this.syncStreamImpl.attach(this);
}
/**
* Publish a message to the stream. The system will attempt delivery to all online subscribers.

@@ -267,0 +267,0 @@ * @param data The body of the dispatched message. Maximum size in serialized JSON: 4KB.

@@ -108,4 +108,5 @@ /*

var logger = require('./utils/logger.js');
var twilsock = require('twilsock');
var browser = require('./packages/shared/builds/browser.js');
// import { TransportUnavailableError } from 'twilsock';
/**

@@ -291,3 +292,4 @@ * A data container used by the Subscriptions class to track subscribed entities' local

}
if (e instanceof twilsock.TransportUnavailableError) {
// todo: transport disconnected here? idk really
if (e instanceof browser.TwilioError && e.errorInfo.reason === 'transportDisconnected') {
logger["default"].debug(`Twilsock connection (required for subscription) not ready (c:${correlationId}); waiting…`);

@@ -294,0 +296,0 @@ this.backoff.reset();

@@ -353,10 +353,2 @@ /*

class SyncDocument extends closeable.Closeable {
/**
* @internal
*/
constructor(syncDocumentImpl) {
super();
this.syncDocumentImpl = syncDocumentImpl;
this.syncDocumentImpl.attach(this);
}
// private props

@@ -407,2 +399,10 @@ get uri() {

/**
* @internal
*/
constructor(syncDocumentImpl) {
super();
this.syncDocumentImpl = syncDocumentImpl;
this.syncDocumentImpl.attach(this);
}
/**
* Assign new contents to this document. The current data will be overwritten.

@@ -409,0 +409,0 @@ * @param data The new contents to assign.

@@ -457,10 +457,2 @@ /*

class SyncList extends closeable.Closeable {
/**
* @internal
*/
constructor(syncListImpl) {
super();
this.syncListImpl = syncListImpl;
this.syncListImpl.attach(this);
}
// private props

@@ -507,2 +499,10 @@ get uri() {

/**
* @internal
*/
constructor(syncListImpl) {
super();
this.syncListImpl = syncListImpl;
this.syncListImpl.attach(this);
}
/**
* Add a new item to the list.

@@ -509,0 +509,0 @@ * @param data Data to be added.

@@ -434,10 +434,2 @@ /*

class SyncMap extends closeable.Closeable {
/**
* @internal
*/
constructor(syncMapImpl) {
super();
this.syncMapImpl = syncMapImpl;
this.syncMapImpl.attach(this);
}
// private props

@@ -485,2 +477,10 @@ get uri() {

/**
* @internal
*/
constructor(syncMapImpl) {
super();
this.syncMapImpl = syncMapImpl;
this.syncMapImpl.attach(this);
}
/**
* Add a new item to the map with the given key-value pair. Overwrites any data that might already exist with that key.

@@ -487,0 +487,0 @@ * @param key Unique item identifier.

{
"name": "twilio-sync",
"version": "3.2.2",
"version": "4.0.0-canary.2+d4f97895",
"description": "Twilio Sync client library",

@@ -39,11 +39,11 @@ "main": "./builds/lib.js",

"@babel/runtime": "^7.17.0",
"@twilio/declarative-type-validator": "^0.2.1",
"@twilio/operation-retrier": "^4.0.9",
"@twilio/replay-event-emitter": "^0.3.1",
"@twilio/declarative-type-validator": "~0.2.2-rc.1",
"@twilio/operation-retrier": "~4.0.10-rc.1",
"@twilio/replay-event-emitter": "~0.3.2-rc.1",
"core-js": "^3.17.3",
"iso8601-duration": "=1.2.0",
"loglevel": "^1.8.0",
"nanoid": "^3.3.4",
"platform": "^1.3.6",
"twilsock": "~0.12.2",
"uuid": "^3.4.0"
"twilsock": "~1.0.0-canary.2+d4f97895"
},

@@ -96,3 +96,3 @@ "devDependencies": {

"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-ts": "^2.0.7",
"rollup-plugin-ts": "^3.0.2",
"sinon": "^7.3.2",

@@ -105,3 +105,3 @@ "sinon-chai": "^3.3.0",

"typedoc": "^0.21.4",
"typescript": "^4.3.2",
"typescript": "^4.8.4",
"uglify-es": "^3.3.10",

@@ -126,3 +126,4 @@ "uglify-save-license": "^0.4.1",

"last 2 UCAndroid versions"
]
],
"gitHead": "d4f97895167fc357381daa23dba19a2c5429db87"
}

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 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 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

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