Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@uppy/companion-client

Package Overview
Dependencies
Maintainers
5
Versions
89
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@uppy/companion-client - npm Package Compare versions

Comparing version 1.10.2 to 2.0.0-alpha.0

32

lib/AuthError.js
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var AuthError = /*#__PURE__*/function (_Error) {
_inheritsLoose(AuthError, _Error);
function AuthError() {
var _this;
_this = _Error.call(this, 'Authorization required') || this;
_this.name = 'AuthError';
_this.isAuthError = true;
return _this;
class AuthError extends Error {
constructor() {
super('Authorization required');
this.name = 'AuthError';
this.isAuthError = true;
}
return AuthError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
}
module.exports = AuthError;

16

lib/index.js

@@ -6,15 +6,15 @@ 'use strict';

var RequestClient = require('./RequestClient');
const RequestClient = require('./RequestClient');
var Provider = require('./Provider');
const Provider = require('./Provider');
var SearchProvider = require('./SearchProvider');
const SearchProvider = require('./SearchProvider');
var Socket = require('./Socket');
const Socket = require('./Socket');
module.exports = {
RequestClient: RequestClient,
Provider: Provider,
SearchProvider: SearchProvider,
Socket: Socket
RequestClient,
Provider,
SearchProvider,
Socket
};
'use strict';
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
const qsStringify = require('qs-stringify');
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
const RequestClient = require('./RequestClient');
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
const tokenStorage = require('./tokenStorage');
var qsStringify = require('qs-stringify');
var URL = require('url-parse');
var RequestClient = require('./RequestClient');
var tokenStorage = require('./tokenStorage');
var _getName = function _getName(id) {
return id.split('-').map(function (s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}).join(' ');
const _getName = id => {
return id.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
};
module.exports = /*#__PURE__*/function (_RequestClient) {
_inheritsLoose(Provider, _RequestClient);
function Provider(uppy, opts) {
var _this;
_this = _RequestClient.call(this, uppy, opts) || this;
_this.provider = opts.provider;
_this.id = _this.provider;
_this.name = _this.opts.name || _getName(_this.id);
_this.pluginId = _this.opts.pluginId;
_this.tokenKey = "companion-" + _this.pluginId + "-auth-token";
_this.companionKeysParams = _this.opts.companionKeysParams;
_this.preAuthToken = null;
return _this;
module.exports = class Provider extends RequestClient {
constructor(uppy, opts) {
super(uppy, opts);
this.provider = opts.provider;
this.id = this.provider;
this.name = this.opts.name || _getName(this.id);
this.pluginId = this.opts.pluginId;
this.tokenKey = `companion-${this.pluginId}-auth-token`;
this.companionKeysParams = this.opts.companionKeysParams;
this.preAuthToken = null;
}
var _proto = Provider.prototype;
headers() {
return Promise.all([super.headers(), this.getAuthToken()]).then(([headers, token]) => {
const authHeaders = {};
_proto.headers = function headers() {
var _this2 = this;
return Promise.all([_RequestClient.prototype.headers.call(this), this.getAuthToken()]).then(function (_ref) {
var headers = _ref[0],
token = _ref[1];
var authHeaders = {};
if (token) {

@@ -54,37 +33,34 @@ authHeaders['uppy-auth-token'] = token;

if (_this2.companionKeysParams) {
if (this.companionKeysParams) {
authHeaders['uppy-credentials-params'] = btoa(JSON.stringify({
params: _this2.companionKeysParams
params: this.companionKeysParams
}));
}
return _extends({}, headers, authHeaders);
return { ...headers,
...authHeaders
};
});
};
}
_proto.onReceiveResponse = function onReceiveResponse(response) {
response = _RequestClient.prototype.onReceiveResponse.call(this, response);
var plugin = this.uppy.getPlugin(this.pluginId);
var oldAuthenticated = plugin.getPluginState().authenticated;
var authenticated = oldAuthenticated ? response.status !== 401 : response.status < 400;
onReceiveResponse(response) {
response = super.onReceiveResponse(response);
const plugin = this.uppy.getPlugin(this.pluginId);
const oldAuthenticated = plugin.getPluginState().authenticated;
const authenticated = oldAuthenticated ? response.status !== 401 : response.status < 400;
plugin.setPluginState({
authenticated: authenticated
authenticated
});
return response;
} // @todo(i.olarewaju) consider whether or not this method should be exposed
;
}
_proto.setAuthToken = function setAuthToken(token) {
setAuthToken(token) {
return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token);
};
}
_proto.getAuthToken = function getAuthToken() {
getAuthToken() {
return this.uppy.getPlugin(this.pluginId).storage.getItem(this.tokenKey);
};
}
_proto.authUrl = function authUrl(queries) {
if (queries === void 0) {
queries = {};
}
authUrl(queries = {}) {
if (this.preAuthToken) {

@@ -94,14 +70,12 @@ queries.uppyPreAuthToken = this.preAuthToken;

var strigifiedQueries = qsStringify(queries);
strigifiedQueries = strigifiedQueries ? "?" + strigifiedQueries : strigifiedQueries;
return this.hostname + "/" + this.id + "/connect" + strigifiedQueries;
};
let strigifiedQueries = qsStringify(queries);
strigifiedQueries = strigifiedQueries ? `?${strigifiedQueries}` : strigifiedQueries;
return `${this.hostname}/${this.id}/connect${strigifiedQueries}`;
}
_proto.fileUrl = function fileUrl(id) {
return this.hostname + "/" + this.id + "/get/" + id;
};
fileUrl(id) {
return `${this.hostname}/${this.id}/get/${id}`;
}
_proto.fetchPreAuthToken = function fetchPreAuthToken() {
var _this3 = this;
fetchPreAuthToken() {
if (!this.companionKeysParams) {

@@ -111,27 +85,20 @@ return Promise.resolve();

return this.post(this.id + "/preauth/", {
return this.post(`${this.id}/preauth/`, {
params: this.companionKeysParams
}).then(function (res) {
_this3.preAuthToken = res.token;
}).catch(function (err) {
_this3.uppy.log("[CompanionClient] unable to fetch preAuthToken " + err, 'warning');
}).then(res => {
this.preAuthToken = res.token;
}).catch(err => {
this.uppy.log(`[CompanionClient] unable to fetch preAuthToken ${err}`, 'warning');
});
};
}
_proto.list = function list(directory) {
return this.get(this.id + "/list/" + (directory || ''));
};
list(directory) {
return this.get(`${this.id}/list/${directory || ''}`);
}
_proto.logout = function logout() {
var _this4 = this;
logout() {
return this.get(`${this.id}/logout`).then(response => Promise.all([response, this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey)])).then(([response]) => response);
}
return this.get(this.id + "/logout").then(function (response) {
return Promise.all([response, _this4.uppy.getPlugin(_this4.pluginId).storage.removeItem(_this4.tokenKey)]);
}).then(function (_ref2) {
var response = _ref2[0];
return response;
});
};
Provider.initPlugin = function initPlugin(plugin, opts, defaultOpts) {
static initPlugin(plugin, opts, defaultOpts) {
plugin.type = 'acquirer';

@@ -141,3 +108,5 @@ plugin.files = [];

if (defaultOpts) {
plugin.opts = _extends({}, defaultOpts, opts);
plugin.opts = { ...defaultOpts,
...opts
};
}

@@ -150,6 +119,6 @@

if (opts.companionAllowedHosts) {
var pattern = opts.companionAllowedHosts; // validate companionAllowedHosts param
const pattern = opts.companionAllowedHosts; // validate companionAllowedHosts param
if (typeof pattern !== 'string' && !Array.isArray(pattern) && !(pattern instanceof RegExp)) {
throw new TypeError(plugin.id + ": the option \"companionAllowedHosts\" must be one of string, Array, RegExp");
throw new TypeError(`${plugin.id}: the option "companionAllowedHosts" must be one of string, Array, RegExp`);
}

@@ -161,3 +130,3 @@

if (/^(?!https?:\/\/).*$/i.test(opts.companionUrl)) {
plugin.opts.companionAllowedHosts = "https://" + opts.companionUrl.replace(/^\/\//, '');
plugin.opts.companionAllowedHosts = `https://${opts.companionUrl.replace(/^\/\//, '')}`;
} else {

@@ -169,5 +138,4 @@ plugin.opts.companionAllowedHosts = new URL(opts.companionUrl).origin;

plugin.storage = plugin.opts.storage || tokenStorage;
};
}
return Provider;
}(RequestClient);
};
'use strict';
var _class, _temp;
var _class, _getPostResponseFunc, _getUrl, _errorHandler, _temp;
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }
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); } }
var id = 0;
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; }
var AuthError = require('./AuthError');
const fetchWithNetworkError = require('@uppy/utils/lib/fetchWithNetworkError');
var fetchWithNetworkError = require('@uppy/utils/lib/fetchWithNetworkError'); // Remove the trailing slash so we can always safely append /xyz.
const AuthError = require('./AuthError'); // Remove the trailing slash so we can always safely append /xyz.

@@ -20,4 +20,38 @@

module.exports = (_temp = _class = /*#__PURE__*/function () {
function RequestClient(uppy, opts) {
async function handleJSONResponse(res) {
if (res.status === 401) {
throw new AuthError();
}
const jsonPromise = res.json();
if (res.status < 200 || res.status > 300) {
let errMsg = `Failed request with status: ${res.status}. ${res.statusText}`;
try {
const errData = await jsonPromise;
errMsg = errData.message ? `${errMsg} message: ${errData.message}` : errMsg;
errMsg = errData.requestId ? `${errMsg} request-Id: ${errData.requestId}` : errMsg;
} finally {
// eslint-disable-next-line no-unsafe-finally
throw new Error(errMsg);
}
}
return jsonPromise;
}
module.exports = (_temp = (_getPostResponseFunc = /*#__PURE__*/_classPrivateFieldLooseKey("getPostResponseFunc"), _getUrl = /*#__PURE__*/_classPrivateFieldLooseKey("getUrl"), _errorHandler = /*#__PURE__*/_classPrivateFieldLooseKey("errorHandler"), _class = class RequestClient {
// eslint-disable-next-line global-require
constructor(uppy, opts) {
Object.defineProperty(this, _errorHandler, {
value: _errorHandler2
});
Object.defineProperty(this, _getUrl, {
value: _getUrl2
});
Object.defineProperty(this, _getPostResponseFunc, {
writable: true,
value: skip => response => skip ? response : this.onReceiveResponse(response)
});
this.uppy = uppy;

@@ -30,32 +64,30 @@ this.opts = opts;

var _proto = RequestClient.prototype;
get hostname() {
const {
companion
} = this.uppy.getState();
const host = this.opts.companionUrl;
return stripSlash(companion && companion[host] ? companion[host] : host);
}
_proto.headers = function headers() {
var userHeaders = this.opts.companionHeaders || this.opts.serverHeaders || {};
return Promise.resolve(_extends({}, this.defaultHeaders, userHeaders));
};
headers() {
const userHeaders = this.opts.companionHeaders || {};
return Promise.resolve({ ...RequestClient.defaultHeaders,
...userHeaders
});
}
_proto._getPostResponseFunc = function _getPostResponseFunc(skip) {
var _this = this;
onReceiveResponse(response) {
const state = this.uppy.getState();
const companion = state.companion || {};
const host = this.opts.companionUrl;
const {
headers
} = response; // Store the self-identified domain name for the Companion instance we just hit.
return function (response) {
if (!skip) {
return _this.onReceiveResponse(response);
}
return response;
};
};
_proto.onReceiveResponse = function onReceiveResponse(response) {
var state = this.uppy.getState();
var companion = state.companion || {};
var host = this.opts.companionUrl;
var headers = response.headers; // Store the self-identified domain name for the Companion instance we just hit.
if (headers.has('i-am') && headers.get('i-am') !== companion[host]) {
var _extends2;
this.uppy.setState({
companion: _extends({}, companion, (_extends2 = {}, _extends2[host] = headers.get('i-am'), _extends2))
companion: { ...companion,
[host]: headers.get('i-am')
}
});

@@ -65,34 +97,5 @@ }

return response;
};
}
_proto._getUrl = function _getUrl(url) {
if (/^(https?:|)\/\//.test(url)) {
return url;
}
return this.hostname + "/" + url;
};
_proto._json = function _json(res) {
if (res.status === 401) {
throw new AuthError();
}
if (res.status < 200 || res.status > 300) {
var errMsg = "Failed request with status: " + res.status + ". " + res.statusText;
return res.json().then(function (errData) {
errMsg = errData.message ? errMsg + " message: " + errData.message : errMsg;
errMsg = errData.requestId ? errMsg + " request-Id: " + errData.requestId : errMsg;
throw new Error(errMsg);
}).catch(function () {
throw new Error(errMsg);
});
}
return res.json();
};
_proto.preflight = function preflight(path) {
var _this2 = this;
preflight(path) {
if (this.preflightDone) {

@@ -102,33 +105,25 @@ return Promise.resolve(this.allowedHeaders.slice());

return fetch(this._getUrl(path), {
return fetch(_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path), {
method: 'OPTIONS'
}).then(function (response) {
}).then(response => {
if (response.headers.has('access-control-allow-headers')) {
_this2.allowedHeaders = response.headers.get('access-control-allow-headers').split(',').map(function (headerName) {
return headerName.trim().toLowerCase();
});
this.allowedHeaders = response.headers.get('access-control-allow-headers').split(',').map(headerName => headerName.trim().toLowerCase());
}
_this2.preflightDone = true;
return _this2.allowedHeaders.slice();
}).catch(function (err) {
_this2.uppy.log("[CompanionClient] unable to make preflight request " + err, 'warning');
_this2.preflightDone = true;
return _this2.allowedHeaders.slice();
this.preflightDone = true;
return this.allowedHeaders.slice();
}).catch(err => {
this.uppy.log(`[CompanionClient] unable to make preflight request ${err}`, 'warning');
this.preflightDone = true;
return this.allowedHeaders.slice();
});
};
}
_proto.preflightAndHeaders = function preflightAndHeaders(path) {
var _this3 = this;
return Promise.all([this.preflight(path), this.headers()]).then(function (_ref) {
var allowedHeaders = _ref[0],
headers = _ref[1];
preflightAndHeaders(path) {
return Promise.all([this.preflight(path), this.headers()]).then(([allowedHeaders, headers]) => {
// filter to keep only allowed Headers
Object.keys(headers).forEach(function (header) {
if (allowedHeaders.indexOf(header.toLowerCase()) === -1) {
_this3.uppy.log("[CompanionClient] excluding unallowed header " + header);
delete headers[header];
Object.keys(headers).forEach(header => {
if (!allowedHeaders.includes(header.toLowerCase())) {
this.uppy.log(`[CompanionClient] excluding disallowed header ${header}`);
delete headers[header]; // eslint-disable-line no-param-reassign
}

@@ -138,87 +133,59 @@ });

});
};
}
_proto.get = function get(path, skipPostResponse) {
var _this4 = this;
get(path, skipPostResponse) {
const method = 'get';
return this.preflightAndHeaders(path).then(headers => fetchWithNetworkError(_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path), {
method,
headers,
credentials: this.opts.companionCookiesRule || 'same-origin'
})).then(_classPrivateFieldLooseBase(this, _getPostResponseFunc)[_getPostResponseFunc](skipPostResponse)).then(handleJSONResponse).catch(_classPrivateFieldLooseBase(this, _errorHandler)[_errorHandler](method, path));
}
return this.preflightAndHeaders(path).then(function (headers) {
return fetchWithNetworkError(_this4._getUrl(path), {
method: 'get',
headers: headers,
credentials: _this4.opts.companionCookiesRule || 'same-origin'
});
}).then(this._getPostResponseFunc(skipPostResponse)).then(function (res) {
return _this4._json(res);
}).catch(function (err) {
if (!err.isAuthError) {
err.message = "Could not get " + _this4._getUrl(path) + ". " + err.message;
}
post(path, data, skipPostResponse) {
const method = 'post';
return this.preflightAndHeaders(path).then(headers => fetchWithNetworkError(_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path), {
method,
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
body: JSON.stringify(data)
})).then(_classPrivateFieldLooseBase(this, _getPostResponseFunc)[_getPostResponseFunc](skipPostResponse)).then(handleJSONResponse).catch(_classPrivateFieldLooseBase(this, _errorHandler)[_errorHandler](method, path));
}
return Promise.reject(err);
});
};
delete(path, data, skipPostResponse) {
const method = 'delete';
return this.preflightAndHeaders(path).then(headers => fetchWithNetworkError(`${this.hostname}/${path}`, {
method,
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
body: data ? JSON.stringify(data) : null
})).then(_classPrivateFieldLooseBase(this, _getPostResponseFunc)[_getPostResponseFunc](skipPostResponse)).then(handleJSONResponse).catch(_classPrivateFieldLooseBase(this, _errorHandler)[_errorHandler](method, path));
}
_proto.post = function post(path, data, skipPostResponse) {
var _this5 = this;
}), _class.VERSION = "2.0.0-alpha.0", _class.defaultHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
'Uppy-Versions': `@uppy/companion-client=${_class.VERSION}`
}, _temp);
return this.preflightAndHeaders(path).then(function (headers) {
return fetchWithNetworkError(_this5._getUrl(path), {
method: 'post',
headers: headers,
credentials: _this5.opts.companionCookiesRule || 'same-origin',
body: JSON.stringify(data)
});
}).then(this._getPostResponseFunc(skipPostResponse)).then(function (res) {
return _this5._json(res);
}).catch(function (err) {
if (!err.isAuthError) {
err.message = "Could not post " + _this5._getUrl(path) + ". " + err.message;
}
function _getUrl2(url) {
if (/^(https?:|)\/\//.test(url)) {
return url;
}
return Promise.reject(err);
});
};
return `${this.hostname}/${url}`;
}
_proto.delete = function _delete(path, data, skipPostResponse) {
var _this6 = this;
function _errorHandler2(method, path) {
return err => {
var _err;
return this.preflightAndHeaders(path).then(function (headers) {
return fetchWithNetworkError(_this6.hostname + "/" + path, {
method: 'delete',
headers: headers,
credentials: _this6.opts.companionCookiesRule || 'same-origin',
body: data ? JSON.stringify(data) : null
});
}).then(this._getPostResponseFunc(skipPostResponse)).then(function (res) {
return _this6._json(res);
}).catch(function (err) {
if (!err.isAuthError) {
err.message = "Could not delete " + _this6._getUrl(path) + ". " + err.message;
}
if (!((_err = err) != null && _err.isAuthError)) {
const error = new Error(`Could not ${method} ${_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path)}`);
error.cause = err;
err = error; // eslint-disable-line no-param-reassign
}
return Promise.reject(err);
});
return Promise.reject(err);
};
_createClass(RequestClient, [{
key: "hostname",
get: function get() {
var _this$uppy$getState = this.uppy.getState(),
companion = _this$uppy$getState.companion;
var host = this.opts.companionUrl;
return stripSlash(companion && companion[host] ? companion[host] : host);
}
}, {
key: "defaultHeaders",
get: function get() {
return {
Accept: 'application/json',
'Content-Type': 'application/json',
'Uppy-Versions': "@uppy/companion-client=" + RequestClient.VERSION
};
}
}]);
return RequestClient;
}(), _class.VERSION = "1.10.2", _temp);
}
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
const RequestClient = require('./RequestClient');
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var RequestClient = require('./RequestClient');
var _getName = function _getName(id) {
return id.split('-').map(function (s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}).join(' ');
const _getName = id => {
return id.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
};
module.exports = /*#__PURE__*/function (_RequestClient) {
_inheritsLoose(SearchProvider, _RequestClient);
module.exports = class SearchProvider extends RequestClient {
constructor(uppy, opts) {
super(uppy, opts);
this.provider = opts.provider;
this.id = this.provider;
this.name = this.opts.name || _getName(this.id);
this.pluginId = this.opts.pluginId;
}
function SearchProvider(uppy, opts) {
var _this;
fileUrl(id) {
return `${this.hostname}/search/${this.id}/get/${id}`;
}
_this = _RequestClient.call(this, uppy, opts) || this;
_this.provider = opts.provider;
_this.id = _this.provider;
_this.name = _this.opts.name || _getName(_this.id);
_this.pluginId = _this.opts.pluginId;
return _this;
search(text, queries) {
queries = queries ? `&${queries}` : '';
return this.get(`search/${this.id}/list?q=${encodeURIComponent(text)}${queries}`);
}
var _proto = SearchProvider.prototype;
_proto.fileUrl = function fileUrl(id) {
return this.hostname + "/search/" + this.id + "/get/" + id;
};
_proto.search = function search(text, queries) {
queries = queries ? "&" + queries : '';
return this.get("search/" + this.id + "/list?q=" + encodeURIComponent(text) + queries);
};
return SearchProvider;
}(RequestClient);
};

@@ -1,15 +0,46 @@

var ee = require('namespace-emitter');
"use strict";
module.exports = /*#__PURE__*/function () {
function UppySocket(opts) {
var _queued, _emitter, _isOpen, _socket, _handleMessage;
let _Symbol$for, _Symbol$for2;
function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }
var id = 0;
function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; }
const ee = require('namespace-emitter');
module.exports = (_queued = /*#__PURE__*/_classPrivateFieldLooseKey("queued"), _emitter = /*#__PURE__*/_classPrivateFieldLooseKey("emitter"), _isOpen = /*#__PURE__*/_classPrivateFieldLooseKey("isOpen"), _socket = /*#__PURE__*/_classPrivateFieldLooseKey("socket"), _handleMessage = /*#__PURE__*/_classPrivateFieldLooseKey("handleMessage"), _Symbol$for = Symbol.for('uppy test: getSocket'), _Symbol$for2 = Symbol.for('uppy test: getQueued'), class UppySocket {
constructor(opts) {
Object.defineProperty(this, _queued, {
writable: true,
value: []
});
Object.defineProperty(this, _emitter, {
writable: true,
value: ee()
});
Object.defineProperty(this, _isOpen, {
writable: true,
value: false
});
Object.defineProperty(this, _socket, {
writable: true,
value: void 0
});
Object.defineProperty(this, _handleMessage, {
writable: true,
value: e => {
try {
const message = JSON.parse(e.data);
this.emit(message.action, message.payload);
} catch (err) {
// TODO: use a more robust error handler.
console.log(err); // eslint-disable-line no-console
}
}
});
this.opts = opts;
this._queued = [];
this.isOpen = false;
this.emitter = ee();
this._handleMessage = this._handleMessage.bind(this);
this.close = this.close.bind(this);
this.emit = this.emit.bind(this);
this.on = this.on.bind(this);
this.once = this.once.bind(this);
this.send = this.send.bind(this);

@@ -21,40 +52,46 @@ if (!opts || opts.autoOpen !== false) {

var _proto = UppySocket.prototype;
get isOpen() {
return _classPrivateFieldLooseBase(this, _isOpen)[_isOpen];
}
_proto.open = function open() {
var _this = this;
[_Symbol$for]() {
return _classPrivateFieldLooseBase(this, _socket)[_socket];
}
this.socket = new WebSocket(this.opts.target);
[_Symbol$for2]() {
return _classPrivateFieldLooseBase(this, _queued)[_queued];
}
this.socket.onopen = function (e) {
_this.isOpen = true;
open() {
_classPrivateFieldLooseBase(this, _socket)[_socket] = new WebSocket(this.opts.target);
while (_this._queued.length > 0 && _this.isOpen) {
var first = _this._queued[0];
_classPrivateFieldLooseBase(this, _socket)[_socket].onopen = () => {
_classPrivateFieldLooseBase(this, _isOpen)[_isOpen] = true;
_this.send(first.action, first.payload);
while (_classPrivateFieldLooseBase(this, _queued)[_queued].length > 0 && _classPrivateFieldLooseBase(this, _isOpen)[_isOpen]) {
const first = _classPrivateFieldLooseBase(this, _queued)[_queued].shift();
_this._queued = _this._queued.slice(1);
this.send(first.action, first.payload);
}
};
this.socket.onclose = function (e) {
_this.isOpen = false;
_classPrivateFieldLooseBase(this, _socket)[_socket].onclose = () => {
_classPrivateFieldLooseBase(this, _isOpen)[_isOpen] = false;
};
this.socket.onmessage = this._handleMessage;
};
_classPrivateFieldLooseBase(this, _socket)[_socket].onmessage = _classPrivateFieldLooseBase(this, _handleMessage)[_handleMessage];
}
_proto.close = function close() {
if (this.socket) {
this.socket.close();
}
};
close() {
var _classPrivateFieldLoo;
_proto.send = function send(action, payload) {
(_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _socket)[_socket]) == null ? void 0 : _classPrivateFieldLoo.close();
}
send(action, payload) {
// attach uuid
if (!this.isOpen) {
this._queued.push({
action: action,
payload: payload
if (!_classPrivateFieldLooseBase(this, _isOpen)[_isOpen]) {
_classPrivateFieldLooseBase(this, _queued)[_queued].push({
action,
payload
});

@@ -65,30 +102,20 @@

this.socket.send(JSON.stringify({
action: action,
payload: payload
_classPrivateFieldLooseBase(this, _socket)[_socket].send(JSON.stringify({
action,
payload
}));
};
}
_proto.on = function on(action, handler) {
this.emitter.on(action, handler);
};
on(action, handler) {
_classPrivateFieldLooseBase(this, _emitter)[_emitter].on(action, handler);
}
_proto.emit = function emit(action, payload) {
this.emitter.emit(action, payload);
};
emit(action, payload) {
_classPrivateFieldLooseBase(this, _emitter)[_emitter].emit(action, payload);
}
_proto.once = function once(action, handler) {
this.emitter.once(action, handler);
};
once(action, handler) {
_classPrivateFieldLooseBase(this, _emitter)[_emitter].once(action, handler);
}
_proto._handleMessage = function _handleMessage(e) {
try {
var message = JSON.parse(e.data);
this.emit(message.action, message.payload);
} catch (err) {
console.log(err);
}
};
return UppySocket;
}();
});

@@ -6,4 +6,4 @@ 'use strict';

module.exports.setItem = function (key, value) {
return new Promise(function (resolve) {
module.exports.setItem = (key, value) => {
return new Promise(resolve => {
localStorage.setItem(key, value);

@@ -14,8 +14,8 @@ resolve();

module.exports.getItem = function (key) {
module.exports.getItem = key => {
return Promise.resolve(localStorage.getItem(key));
};
module.exports.removeItem = function (key) {
return new Promise(function (resolve) {
module.exports.removeItem = key => {
return new Promise(resolve => {
localStorage.removeItem(key);

@@ -22,0 +22,0 @@ resolve();

{
"name": "@uppy/companion-client",
"description": "Client library for communication with Companion. Intended for use in Uppy plugins.",
"version": "1.10.2",
"version": "2.0.0-alpha.0",
"license": "MIT",

@@ -24,8 +24,7 @@ "main": "lib/index.js",

"dependencies": {
"@uppy/utils": "^3.6.2",
"@uppy/utils": "^4.0.0-alpha.0",
"namespace-emitter": "^2.0.1",
"qs-stringify": "^1.1.0",
"url-parse": "^1.4.7"
"qs-stringify": "^1.1.0"
},
"gitHead": "4b782ffbbb443672843d7b4096956bed3b11d612"
"gitHead": "113b627dd0ef5aa5d198dc309dda05da2117dfe5"
}

@@ -15,4 +15,4 @@ # @uppy/companion-client

```js
const Uppy = require('@uppy/core')
const { Provider, RequestClient, Socket } = require('@uppy/companion-client')
import Uppy from '@uppy/core'
import { Provider, RequestClient, Socket } from '@uppy/companion-client'

@@ -26,3 +26,3 @@ const uppy = new Uppy()

companionUrl: 'https://uppy.mywebsite.com/',
provider: providerPluginInstance
provider: providerPluginInstance,
})

@@ -29,0 +29,0 @@ provider.checkAuth().then(() => {})

'use strict'
const qsStringify = require('qs-stringify')
const URL = require('url-parse')
const RequestClient = require('./RequestClient')

@@ -50,3 +49,2 @@ const tokenStorage = require('./tokenStorage')

// @todo(i.olarewaju) consider whether or not this method should be exposed
setAuthToken (token) {

@@ -53,0 +51,0 @@ return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token)

'use strict'
const fetchWithNetworkError = require('@uppy/utils/lib/fetchWithNetworkError')
const AuthError = require('./AuthError')
const fetchWithNetworkError = require('@uppy/utils/lib/fetchWithNetworkError')

@@ -11,5 +11,29 @@ // Remove the trailing slash so we can always safely append /xyz.

async function handleJSONResponse (res) {
if (res.status === 401) {
throw new AuthError()
}
const jsonPromise = res.json()
if (res.status < 200 || res.status > 300) {
let errMsg = `Failed request with status: ${res.status}. ${res.statusText}`
try {
const errData = await jsonPromise
errMsg = errData.message ? `${errMsg} message: ${errData.message}` : errMsg
errMsg = errData.requestId ? `${errMsg} request-Id: ${errData.requestId}` : errMsg
} finally {
// eslint-disable-next-line no-unsafe-finally
throw new Error(errMsg)
}
}
return jsonPromise
}
module.exports = class RequestClient {
// eslint-disable-next-line global-require
static VERSION = require('../package.json').version
#getPostResponseFunc = skip => response => (skip ? response : this.onReceiveResponse(response))
constructor (uppy, opts) {

@@ -29,14 +53,12 @@ this.uppy = uppy

get defaultHeaders () {
return {
Accept: 'application/json',
'Content-Type': 'application/json',
'Uppy-Versions': `@uppy/companion-client=${RequestClient.VERSION}`,
}
static defaultHeaders ={
Accept: 'application/json',
'Content-Type': 'application/json',
'Uppy-Versions': `@uppy/companion-client=${RequestClient.VERSION}`,
}
headers () {
const userHeaders = this.opts.companionHeaders || this.opts.serverHeaders || {}
const userHeaders = this.opts.companionHeaders || {}
return Promise.resolve({
...this.defaultHeaders,
...RequestClient.defaultHeaders,
...userHeaders,

@@ -46,12 +68,2 @@ })

_getPostResponseFunc (skip) {
return (response) => {
if (!skip) {
return this.onReceiveResponse(response)
}
return response
}
}
onReceiveResponse (response) {

@@ -61,3 +73,3 @@ const state = this.uppy.getState()

const host = this.opts.companionUrl
const headers = response.headers
const { headers } = response
// Store the self-identified domain name for the Companion instance we just hit.

@@ -72,3 +84,3 @@ if (headers.has('i-am') && headers.get('i-am') !== companion[host]) {

_getUrl (url) {
#getUrl (url) {
if (/^(https?:|)\/\//.test(url)) {

@@ -80,17 +92,11 @@ return url

_json (res) {
if (res.status === 401) {
throw new AuthError()
#errorHandler (method, path) {
return (err) => {
if (!err?.isAuthError) {
const error = new Error(`Could not ${method} ${this.#getUrl(path)}`)
error.cause = err
err = error // eslint-disable-line no-param-reassign
}
return Promise.reject(err)
}
if (res.status < 200 || res.status > 300) {
let errMsg = `Failed request with status: ${res.status}. ${res.statusText}`
return res.json()
.then((errData) => {
errMsg = errData.message ? `${errMsg} message: ${errData.message}` : errMsg
errMsg = errData.requestId ? `${errMsg} request-Id: ${errData.requestId}` : errMsg
throw new Error(errMsg)
}).catch(() => { throw new Error(errMsg) })
}
return res.json()
}

@@ -103,3 +109,3 @@

return fetch(this._getUrl(path), {
return fetch(this.#getUrl(path), {
method: 'OPTIONS',

@@ -127,5 +133,5 @@ })

Object.keys(headers).forEach((header) => {
if (allowedHeaders.indexOf(header.toLowerCase()) === -1) {
this.uppy.log(`[CompanionClient] excluding unallowed header ${header}`)
delete headers[header]
if (!allowedHeaders.includes(header.toLowerCase())) {
this.uppy.log(`[CompanionClient] excluding disallowed header ${header}`)
delete headers[header] // eslint-disable-line no-param-reassign
}

@@ -139,56 +145,41 @@ })

get (path, skipPostResponse) {
const method = 'get'
return this.preflightAndHeaders(path)
.then((headers) =>
fetchWithNetworkError(this._getUrl(path), {
method: 'get',
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
}))
.then(this._getPostResponseFunc(skipPostResponse))
.then((res) => this._json(res))
.catch((err) => {
if (!err.isAuthError) {
err.message = `Could not get ${this._getUrl(path)}. ${err.message}`
}
return Promise.reject(err)
})
.then((headers) => fetchWithNetworkError(this.#getUrl(path), {
method,
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
}))
.then(this.#getPostResponseFunc(skipPostResponse))
.then(handleJSONResponse)
.catch(this.#errorHandler(method, path))
}
post (path, data, skipPostResponse) {
const method = 'post'
return this.preflightAndHeaders(path)
.then((headers) =>
fetchWithNetworkError(this._getUrl(path), {
method: 'post',
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
body: JSON.stringify(data),
}))
.then(this._getPostResponseFunc(skipPostResponse))
.then((res) => this._json(res))
.catch((err) => {
if (!err.isAuthError) {
err.message = `Could not post ${this._getUrl(path)}. ${err.message}`
}
return Promise.reject(err)
})
.then((headers) => fetchWithNetworkError(this.#getUrl(path), {
method,
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
body: JSON.stringify(data),
}))
.then(this.#getPostResponseFunc(skipPostResponse))
.then(handleJSONResponse)
.catch(this.#errorHandler(method, path))
}
delete (path, data, skipPostResponse) {
const method = 'delete'
return this.preflightAndHeaders(path)
.then((headers) =>
fetchWithNetworkError(`${this.hostname}/${path}`, {
method: 'delete',
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
body: data ? JSON.stringify(data) : null,
}))
.then(this._getPostResponseFunc(skipPostResponse))
.then((res) => this._json(res))
.catch((err) => {
if (!err.isAuthError) {
err.message = `Could not delete ${this._getUrl(path)}. ${err.message}`
}
return Promise.reject(err)
})
.then((headers) => fetchWithNetworkError(`${this.hostname}/${path}`, {
method,
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
body: data ? JSON.stringify(data) : null,
}))
.then(this.#getPostResponseFunc(skipPostResponse))
.then(handleJSONResponse)
.catch(this.#errorHandler(method, path))
}
}
const ee = require('namespace-emitter')
module.exports = class UppySocket {
#queued = []
#emitter = ee()
#isOpen = false
#socket
constructor (opts) {
this.opts = opts
this._queued = []
this.isOpen = false
this.emitter = ee()
this._handleMessage = this._handleMessage.bind(this)
this.close = this.close.bind(this)
this.emit = this.emit.bind(this)
this.on = this.on.bind(this)
this.once = this.once.bind(this)
this.send = this.send.bind(this)
if (!opts || opts.autoOpen !== false) {

@@ -23,26 +20,29 @@ this.open()

get isOpen () { return this.#isOpen }
[Symbol.for('uppy test: getSocket')] () { return this.#socket }
[Symbol.for('uppy test: getQueued')] () { return this.#queued }
open () {
this.socket = new WebSocket(this.opts.target)
this.#socket = new WebSocket(this.opts.target)
this.socket.onopen = (e) => {
this.isOpen = true
this.#socket.onopen = () => {
this.#isOpen = true
while (this._queued.length > 0 && this.isOpen) {
const first = this._queued[0]
while (this.#queued.length > 0 && this.#isOpen) {
const first = this.#queued.shift()
this.send(first.action, first.payload)
this._queued = this._queued.slice(1)
}
}
this.socket.onclose = (e) => {
this.isOpen = false
this.#socket.onclose = () => {
this.#isOpen = false
}
this.socket.onmessage = this._handleMessage
this.#socket.onmessage = this.#handleMessage
}
close () {
if (this.socket) {
this.socket.close()
}
this.#socket?.close()
}

@@ -53,8 +53,8 @@

if (!this.isOpen) {
this._queued.push({ action, payload })
if (!this.#isOpen) {
this.#queued.push({ action, payload })
return
}
this.socket.send(JSON.stringify({
this.#socket.send(JSON.stringify({
action,

@@ -66,14 +66,14 @@ payload,

on (action, handler) {
this.emitter.on(action, handler)
this.#emitter.on(action, handler)
}
emit (action, payload) {
this.emitter.emit(action, payload)
this.#emitter.emit(action, payload)
}
once (action, handler) {
this.emitter.once(action, handler)
this.#emitter.once(action, handler)
}
_handleMessage (e) {
#handleMessage= (e) => {
try {

@@ -83,5 +83,6 @@ const message = JSON.parse(e.data)

} catch (err) {
console.log(err)
// TODO: use a more robust error handler.
console.log(err) // eslint-disable-line no-console
}
}
}

@@ -18,2 +18,3 @@ const UppySocket = require('./Socket')

// eslint-disable-next-line class-methods-use-this
close (args) {

@@ -23,2 +24,3 @@ webSocketCloseSpy(args)

// eslint-disable-next-line class-methods-use-this
send (json) {

@@ -57,3 +59,3 @@ webSocketSendSpy(json)

const uppySocket = new UppySocket({ target: 'foo' })
const webSocketInstance = uppySocket.socket
const webSocketInstance = uppySocket[Symbol.for('uppy test: getSocket')]()
webSocketInstance.triggerOpen()

@@ -72,3 +74,3 @@

uppySocket.send('bar', 'boo')
expect(uppySocket._queued).toEqual([{ action: 'bar', payload: 'boo' }])
expect(uppySocket[Symbol.for('uppy test: getQueued')]()).toEqual([{ action: 'bar', payload: 'boo' }])
expect(webSocketSendSpy.mock.calls.length).toEqual(0)

@@ -79,7 +81,7 @@ })

const uppySocket = new UppySocket({ target: 'foo' })
const webSocketInstance = uppySocket.socket
const webSocketInstance = uppySocket[Symbol.for('uppy test: getSocket')]()
uppySocket.send('bar', 'boo')
uppySocket.send('moo', 'baa')
expect(uppySocket._queued).toEqual([
expect(uppySocket[Symbol.for('uppy test: getQueued')]()).toEqual([
{ action: 'bar', payload: 'boo' },

@@ -92,3 +94,3 @@ { action: 'moo', payload: 'baa' },

expect(uppySocket._queued).toEqual([])
expect(uppySocket[Symbol.for('uppy test: getQueued')]()).toEqual([])
expect(webSocketSendSpy.mock.calls.length).toEqual(2)

@@ -105,10 +107,10 @@ expect(webSocketSendSpy.mock.calls[0]).toEqual([

const uppySocket = new UppySocket({ target: 'foo' })
const webSocketInstance = uppySocket.socket
const webSocketInstance = uppySocket[Symbol.for('uppy test: getSocket')]()
webSocketInstance.triggerOpen()
uppySocket.send('bar', 'boo')
expect(uppySocket._queued).toEqual([])
expect(uppySocket[Symbol.for('uppy test: getQueued')]()).toEqual([])
webSocketInstance.triggerClose()
uppySocket.send('bar', 'boo')
expect(uppySocket._queued).toEqual([{ action: 'bar', payload: 'boo' }])
expect(uppySocket[Symbol.for('uppy test: getQueued')]()).toEqual([{ action: 'bar', payload: 'boo' }])
})

@@ -118,3 +120,3 @@

const uppySocket = new UppySocket({ target: 'foo' })
const webSocketInstance = uppySocket.socket
const webSocketInstance = uppySocket[Symbol.for('uppy test: getSocket')]()
webSocketInstance.triggerOpen()

@@ -128,3 +130,3 @@

const uppySocket = new UppySocket({ target: 'foo' })
const webSocketInstance = uppySocket.socket
const webSocketInstance = uppySocket[Symbol.for('uppy test: getSocket')]()

@@ -131,0 +133,0 @@ const emitterListenerMock = jest.fn()

@@ -0,1 +1,3 @@

import type { Uppy } from '@uppy/core'
/**

@@ -13,15 +15,14 @@ * Async storage interface, similar to `localStorage`. This can be used to

companionUrl: string
companionHeaders?: object
companionHeaders?: Record<string, unknown>
companionCookiesRule?: RequestCredentials
/**
* Deprecated, use `companionHeaders` instead.
*/
serverHeaders?: object
}
export class RequestClient {
constructor (uppy: any, opts: RequestClientOptions)
constructor (uppy: Uppy, opts: RequestClientOptions)
get (path: string): Promise<any>
post (path: string, data: object): Promise<any>
delete (path: string, data: object): Promise<any>
post (path: string, data: Record<string, unknown>): Promise<any>
delete (path: string, data: Record<string, unknown>): Promise<any>
}

@@ -47,9 +48,15 @@

export class Provider extends RequestClient {
constructor (uppy: any, opts: ProviderOptions)
constructor (uppy: Uppy, opts: ProviderOptions)
checkAuth (): Promise<boolean>
authUrl (): string
fileUrl (id: string): string
list (directory: string): Promise<any>
logout (redirect?: string): Promise<any>
static initPlugin (plugin: any, opts: object, defaultOpts?: object): void
static initPlugin (plugin: unknown, opts: Record<string, unknown>, defaultOpts?: Record<string, unknown>): void
}

@@ -63,11 +70,17 @@

export class Socket {
isOpen: boolean
readonly isOpen: boolean
constructor (opts: SocketOptions)
open (): void
close (): void
send (action: string, payload: any): void
send (action: string, payload: unknown): void
on (action: string, handler: (param: any) => void): void
once (action: string, handler: (param: any) => void): void
emit (action: string, payload: (param: any) => void): void
}

@@ -1,2 +0,2 @@

import { RequestClient, Provider, Socket } from '../'
// import { RequestClient, Provider, Socket } from '..'
// TODO tests

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