Socket
Socket
Sign inDemoInstall

@superset-ui/connection

Package Overview
Dependencies
Maintainers
14
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@superset-ui/connection - npm Package Compare versions

Comparing version 0.14.0 to 0.14.9

131

esm/callApi/callApi.js

@@ -16,4 +16,35 @@ "use strict";

// This function fetches an API response and returns the corresponding json
function callApi({
function tryParsePayload(payload) {
try {
return typeof payload === 'string' ? JSON.parse(payload) : payload;
} catch (error) {
throw new Error("Invalid payload:\n\n" + payload);
}
}
/**
* Try appending search params to an URL if needed.
*/
function getFullUrl(partialUrl, params) {
if (params) {
const url = new URL(partialUrl, window.location.href);
const search = params instanceof URLSearchParams ? params : new URLSearchParams(params); // will completely override any existing search params
url.search = search.toString();
return url.href;
}
return partialUrl;
}
/**
* Fetch an API response and returns the corresponding json.
*
* @param {Payload} postPayload payload to send as FormData in a post form
* @param {Payload} jsonPayload json payload to post, will automatically add Content-Type header
* @param {string} stringify whether to stringify field values when post as formData
*/
async function callApi({
body,

@@ -27,8 +58,11 @@ cache = 'default',

postPayload,
jsonPayload,
redirect = 'follow',
signal,
stringify = true,
url
url: url_,
searchParams
}) {
const fetchWithRetry = (0, _fetchRetry.default)(fetch, fetchRetryOptions);
const url = "" + getFullUrl(url_, searchParams);
const request = {

@@ -45,47 +79,66 @@ body,

if (method === 'GET' && _constants.CACHE_AVAILABLE && (self.location && self.location.protocol) === 'https:') {
return caches.open(_constants.CACHE_KEY).then(supersetCache => supersetCache.match(url).then(cachedResponse => {
if (cachedResponse) {
// if we have a cached response, send its ETag in the
// `If-None-Match` header in a conditional request
const etag = cachedResponse.headers.get('Etag');
request.headers = _extends({}, request.headers, {
'If-None-Match': etag
});
}
if (method === 'GET' && cache !== 'no-store' && cache !== 'reload' && _constants.CACHE_AVAILABLE && (self.location && self.location.protocol) === 'https:') {
const supersetCache = await caches.open(_constants.CACHE_KEY);
const cachedResponse = await supersetCache.match(url);
return fetchWithRetry(url, request);
}).then(response => {
if (response.status === _constants.HTTP_STATUS_NOT_MODIFIED) {
return supersetCache.match(url).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse.clone();
}
if (cachedResponse) {
// if we have a cached response, send its ETag in the
// `If-None-Match` header in a conditional request
const etag = cachedResponse.headers.get('Etag');
request.headers = _extends({}, request.headers, {
'If-None-Match': etag
});
}
throw new Error('Received 304 but no content is cached!');
});
}
const response = await fetchWithRetry(url, request);
if (response.status === _constants.HTTP_STATUS_OK && response.headers.get('Etag')) {
supersetCache.delete(url);
supersetCache.put(url, response.clone());
if (response.status === _constants.HTTP_STATUS_NOT_MODIFIED) {
const cachedFullResponse = await supersetCache.match(url);
if (cachedFullResponse) {
return cachedFullResponse.clone();
}
return response;
}));
throw new Error('Received 304 but no content is cached!');
}
if (response.status === _constants.HTTP_STATUS_OK && response.headers.get('Etag')) {
supersetCache.delete(url);
supersetCache.put(url, response.clone());
}
return response;
}
if ((method === 'POST' || method === 'PATCH' || method === 'PUT') && typeof postPayload === 'object') {
// using FormData has the effect that Content-Type header is set to `multipart/form-data`,
// not e.g., 'application/x-www-form-urlencoded'
const formData = new FormData();
Object.keys(postPayload).forEach(key => {
const value = postPayload[key];
if (method === 'POST' || method === 'PATCH' || method === 'PUT') {
if (postPayload && jsonPayload) {
throw new Error('Please provide only one of jsonPayload or postPayload');
}
if (typeof value !== 'undefined') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
formData.append(key, stringify ? JSON.stringify(value) : value);
if (postPayload instanceof FormData) {
request.body = postPayload;
} else if (postPayload) {
const payload = tryParsePayload(postPayload);
if (payload && typeof payload === 'object') {
// using FormData has the effect that Content-Type header is set to `multipart/form-data`,
// not e.g., 'application/x-www-form-urlencoded'
const formData = new FormData();
Object.keys(payload).forEach(key => {
const value = payload[key];
if (typeof value !== 'undefined') {
formData.append(key, stringify ? JSON.stringify(value) : String(value));
}
});
request.body = formData;
}
});
request.body = formData;
}
if (jsonPayload !== undefined) {
request.body = JSON.stringify(jsonPayload);
request.headers = _extends({}, request.headers, {
'Content-Type': 'application/json'
});
}
}

@@ -92,0 +145,0 @@

@@ -16,3 +16,3 @@ "use strict";

function callApiAndParseWithTimeout(_ref) {
async function callApiAndParseWithTimeout(_ref) {
let {

@@ -25,4 +25,4 @@ timeout,

const apiPromise = (0, _callApi.default)(rest);
const racedPromise = typeof timeout === 'number' && timeout > 0 ? Promise.race([(0, _rejectAfterTimeout.default)(timeout), apiPromise]) : apiPromise;
const racedPromise = typeof timeout === 'number' && timeout > 0 ? Promise.race([apiPromise, (0, _rejectAfterTimeout.default)(timeout)]) : apiPromise;
return (0, _parseResponse.default)(racedPromise, parseMethod);
}

@@ -6,29 +6,33 @@ "use strict";

function rejectIfNotOkay(response) {
if (!response.ok) return Promise.reject(response);
return Promise.resolve(response);
}
async function parseResponse(apiPromise, parseMethod) {
const response = await apiPromise; // reject failed HTTP requests with the raw response
function parseResponse(apiPromise, parseMethod = 'json') {
const checkedPromise = apiPromise.then(rejectIfNotOkay);
if (!response.ok) {
return Promise.reject(response);
}
if (parseMethod === null) {
return apiPromise.then(rejectIfNotOkay);
if (parseMethod === null || parseMethod === 'raw') {
return response;
}
if (parseMethod === 'text') {
return checkedPromise.then(response => response.text().then(text => ({
const text = await response.text();
const result = {
response,
text
})));
}
};
return result;
} // by default treat this as json
if (parseMethod === 'json') {
return checkedPromise.then(response => response.json().then(json => ({
if (parseMethod === undefined || parseMethod === 'json') {
const json = await response.json();
const result = {
json,
response
})));
};
return result;
}
throw new Error("Expected parseResponse=null|json|text, got '" + parseMethod + "'.");
throw new Error("Expected parseResponse=json|text|raw|null, got '" + parseMethod + "'.");
}
"use strict";
exports.__esModule = true;
exports.DEFAULT_FETCH_RETRY_OPTIONS = exports.CACHE_KEY = exports.CACHE_AVAILABLE = exports.HTTP_STATUS_NOT_MODIFIED = exports.HTTP_STATUS_OK = void 0;
// HTTP status codes
exports.DEFAULT_FETCH_RETRY_OPTIONS = exports.CACHE_KEY = exports.CACHE_AVAILABLE = exports.HTTP_STATUS_NOT_MODIFIED = exports.HTTP_STATUS_OK = exports.DEFAULT_BASE_URL = void 0;
const DEFAULT_BASE_URL = 'http://localhost'; // HTTP status codes
exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
const HTTP_STATUS_OK = 200;

@@ -7,0 +9,0 @@ exports.HTTP_STATUS_OK = HTTP_STATUS_OK;

@@ -25,5 +25,8 @@ "use strict";

},
reset: () => {
singletonClient = undefined;
},
getInstance,
delete: request => getInstance().delete(request),
get: request => getInstance().get(request),
getInstance,
init: force => getInstance().init(force),

@@ -33,11 +36,6 @@ isAuthenticated: () => getInstance().isAuthenticated(),

put: request => getInstance().put(request),
reAuthenticate: () => getInstance().init(
/* force = */
true),
request: _request => getInstance().request(_request),
reset: () => {
singletonClient = undefined;
}
reAuthenticate: () => getInstance().reAuthenticate(),
request: _request => getInstance().request(_request)
};
var _default = SupersetClient;
exports.default = _default;

@@ -6,3 +6,3 @@ "use strict";

var _callApi = _interopRequireDefault(require("./callApi"));
var _callApiAndParseWithTimeout = _interopRequireDefault(require("./callApi/callApiAndParseWithTimeout"));

@@ -13,2 +13,4 @@ var _constants = require("./constants");

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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); }

@@ -20,4 +22,5 @@

constructor({
protocol = 'http:',
host = 'localhost',
baseUrl = _constants.DEFAULT_BASE_URL,
host,
protocol,
headers = {},

@@ -38,2 +41,4 @@ fetchRetryOptions = {},

_defineProperty(this, "baseUrl", void 0);
_defineProperty(this, "protocol", void 0);

@@ -49,10 +54,14 @@

const url = new URL(host || protocol ? (protocol || 'https:') + "//" + (host || 'localhost') : baseUrl, // baseUrl for API could also be relative, so we provide current location.href
// as the base of baseUrl
window.location.href);
this.baseUrl = url.href.replace(/\/+$/, ''); // always strip trailing slash
this.host = url.host;
this.protocol = url.protocol;
this.headers = _extends({}, headers);
this.host = host;
this.mode = mode;
this.timeout = timeout;
this.protocol = protocol;
this.credentials = credentials;
this.csrfToken = csrfToken;
this.csrfPromise = undefined;
this.fetchRetryOptions = _extends({}, _constants.DEFAULT_FETCH_RETRY_OPTIONS, {}, fetchRetryOptions);

@@ -68,3 +77,3 @@

init(force = false) {
async init(force = false) {
if (this.isAuthenticated() && !force) {

@@ -77,2 +86,6 @@ return this.csrfPromise;

async reAuthenticate() {
return this.init(true);
}
isAuthenticated() {

@@ -107,30 +120,18 @@ // if CSRF protection is disabled in the Superset app, the token may be an empty string

async request({
body,
credentials,
endpoint,
fetchRetryOptions,
headers,
host,
method,
mode,
parseMethod,
postPayload,
signal,
stringify,
timeout,
url
}) {
return this.ensureAuth().then(() => (0, _callApi.default)({
body,
async request(_ref) {
let {
credentials,
mode,
endpoint,
host,
url,
headers,
timeout
} = _ref,
rest = _objectWithoutPropertiesLoose(_ref, ["credentials", "mode", "endpoint", "host", "url", "headers", "timeout"]);
await this.ensureAuth();
return (0, _callApiAndParseWithTimeout.default)(_extends({}, rest, {
credentials: credentials != null ? credentials : this.credentials,
fetchRetryOptions,
headers: _extends({}, this.headers, {}, headers),
method,
mode: mode != null ? mode : this.mode,
parseMethod,
postPayload,
signal,
stringify,
timeout: timeout != null ? timeout : this.timeout,
url: this.getUrl({

@@ -140,11 +141,13 @@ endpoint,

url
})
}),
headers: _extends({}, this.headers, {}, headers),
timeout: timeout != null ? timeout : this.timeout
}));
}
ensureAuth() {
async ensureAuth() {
var _this$csrfPromise;
return (_this$csrfPromise = this.csrfPromise) != null ? _this$csrfPromise : Promise.reject({
error: "SupersetClient has no CSRF token, ensure it is initialized or\n try logging into the Superset instance at " + this.getUrl({
error: "SupersetClient has not been provided a CSRF token, ensure it is\n initialized with `client.getCSRFToken()` or try logging in at\n " + this.getUrl({
endpoint: '/login'

@@ -159,3 +162,3 @@ })

this.csrfPromise = (0, _callApi.default)({
this.csrfPromise = (0, _callApiAndParseWithTimeout.default)({
credentials: this.credentials,

@@ -168,6 +171,9 @@ headers: _extends({}, this.headers),

endpoint: 'superset/csrf_token/'
})
}).then(response => {
if (typeof response.json === 'object') {
this.csrfToken = response.json.csrf_token;
}),
parseMethod: 'json'
}).then(({
json
}) => {
if (typeof json === 'object') {
this.csrfToken = json.csrf_token;

@@ -181,9 +187,9 @@ if (typeof this.csrfToken === 'string') {

if (!this.isAuthenticated()) {
return Promise.reject({
error: 'Failed to fetch CSRF token'
});
if (this.isAuthenticated()) {
return this.csrfToken;
}
return this.csrfToken;
return Promise.reject({
error: 'Failed to fetch CSRF token'
});
});

@@ -190,0 +196,0 @@ return this.csrfPromise;

import 'whatwg-fetch';
import { CallApi } from '../types';
export default function callApi({ body, cache, credentials, fetchRetryOptions, headers, method, mode, postPayload, redirect, signal, stringify, url, }: CallApi): Promise<Response>;
/**
* Fetch an API response and returns the corresponding json.
*
* @param {Payload} postPayload payload to send as FormData in a post form
* @param {Payload} jsonPayload json payload to post, will automatically add Content-Type header
* @param {string} stringify whether to stringify field values when post as formData
*/
export default function callApi({ body, cache, credentials, fetchRetryOptions, headers, method, mode, postPayload, jsonPayload, redirect, signal, stringify, url: url_, searchParams, }: CallApi): Promise<Response>;
//# sourceMappingURL=callApi.d.ts.map

@@ -16,4 +16,35 @@ "use strict";

// This function fetches an API response and returns the corresponding json
function callApi({
function tryParsePayload(payload) {
try {
return typeof payload === 'string' ? JSON.parse(payload) : payload;
} catch (error) {
throw new Error("Invalid payload:\n\n" + payload);
}
}
/**
* Try appending search params to an URL if needed.
*/
function getFullUrl(partialUrl, params) {
if (params) {
const url = new URL(partialUrl, window.location.href);
const search = params instanceof URLSearchParams ? params : new URLSearchParams(params); // will completely override any existing search params
url.search = search.toString();
return url.href;
}
return partialUrl;
}
/**
* Fetch an API response and returns the corresponding json.
*
* @param {Payload} postPayload payload to send as FormData in a post form
* @param {Payload} jsonPayload json payload to post, will automatically add Content-Type header
* @param {string} stringify whether to stringify field values when post as formData
*/
async function callApi({
body,

@@ -27,8 +58,11 @@ cache = 'default',

postPayload,
jsonPayload,
redirect = 'follow',
signal,
stringify = true,
url
url: url_,
searchParams
}) {
const fetchWithRetry = (0, _fetchRetry.default)(fetch, fetchRetryOptions);
const url = "" + getFullUrl(url_, searchParams);
const request = {

@@ -45,47 +79,66 @@ body,

if (method === 'GET' && _constants.CACHE_AVAILABLE && (self.location && self.location.protocol) === 'https:') {
return caches.open(_constants.CACHE_KEY).then(supersetCache => supersetCache.match(url).then(cachedResponse => {
if (cachedResponse) {
// if we have a cached response, send its ETag in the
// `If-None-Match` header in a conditional request
const etag = cachedResponse.headers.get('Etag');
request.headers = _extends({}, request.headers, {
'If-None-Match': etag
});
}
if (method === 'GET' && cache !== 'no-store' && cache !== 'reload' && _constants.CACHE_AVAILABLE && (self.location && self.location.protocol) === 'https:') {
const supersetCache = await caches.open(_constants.CACHE_KEY);
const cachedResponse = await supersetCache.match(url);
return fetchWithRetry(url, request);
}).then(response => {
if (response.status === _constants.HTTP_STATUS_NOT_MODIFIED) {
return supersetCache.match(url).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse.clone();
}
if (cachedResponse) {
// if we have a cached response, send its ETag in the
// `If-None-Match` header in a conditional request
const etag = cachedResponse.headers.get('Etag');
request.headers = _extends({}, request.headers, {
'If-None-Match': etag
});
}
throw new Error('Received 304 but no content is cached!');
});
}
const response = await fetchWithRetry(url, request);
if (response.status === _constants.HTTP_STATUS_OK && response.headers.get('Etag')) {
supersetCache.delete(url);
supersetCache.put(url, response.clone());
if (response.status === _constants.HTTP_STATUS_NOT_MODIFIED) {
const cachedFullResponse = await supersetCache.match(url);
if (cachedFullResponse) {
return cachedFullResponse.clone();
}
return response;
}));
throw new Error('Received 304 but no content is cached!');
}
if (response.status === _constants.HTTP_STATUS_OK && response.headers.get('Etag')) {
supersetCache.delete(url);
supersetCache.put(url, response.clone());
}
return response;
}
if ((method === 'POST' || method === 'PATCH' || method === 'PUT') && typeof postPayload === 'object') {
// using FormData has the effect that Content-Type header is set to `multipart/form-data`,
// not e.g., 'application/x-www-form-urlencoded'
const formData = new FormData();
Object.keys(postPayload).forEach(key => {
const value = postPayload[key];
if (method === 'POST' || method === 'PATCH' || method === 'PUT') {
if (postPayload && jsonPayload) {
throw new Error('Please provide only one of jsonPayload or postPayload');
}
if (typeof value !== 'undefined') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
formData.append(key, stringify ? JSON.stringify(value) : value);
if (postPayload instanceof FormData) {
request.body = postPayload;
} else if (postPayload) {
const payload = tryParsePayload(postPayload);
if (payload && typeof payload === 'object') {
// using FormData has the effect that Content-Type header is set to `multipart/form-data`,
// not e.g., 'application/x-www-form-urlencoded'
const formData = new FormData();
Object.keys(payload).forEach(key => {
const value = payload[key];
if (typeof value !== 'undefined') {
formData.append(key, stringify ? JSON.stringify(value) : String(value));
}
});
request.body = formData;
}
});
request.body = formData;
}
if (jsonPayload !== undefined) {
request.body = JSON.stringify(jsonPayload);
request.headers = _extends({}, request.headers, {
'Content-Type': 'application/json'
});
}
}

@@ -92,0 +145,0 @@

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

import { CallApi, ClientTimeout, SupersetClientResponse, ParseMethod } from '../types';
export default function callApiAndParseWithTimeout({ timeout, parseMethod, ...rest }: {
import { CallApi, ClientTimeout, ParseMethod } from '../types';
export default function callApiAndParseWithTimeout<T extends ParseMethod = 'json'>({ timeout, parseMethod, ...rest }: {
timeout?: ClientTimeout;
parseMethod?: ParseMethod;
} & CallApi): Promise<SupersetClientResponse>;
parseMethod?: T;
} & CallApi): Promise<T extends "raw" | null ? Response : T extends "json" | undefined ? import("../types").JsonResponse : T extends "text" ? import("../types").TextResponse : never>;
//# sourceMappingURL=callApiAndParseWithTimeout.d.ts.map

@@ -16,3 +16,3 @@ "use strict";

function callApiAndParseWithTimeout(_ref) {
async function callApiAndParseWithTimeout(_ref) {
let {

@@ -25,4 +25,4 @@ timeout,

const apiPromise = (0, _callApi.default)(rest);
const racedPromise = typeof timeout === 'number' && timeout > 0 ? Promise.race([(0, _rejectAfterTimeout.default)(timeout), apiPromise]) : apiPromise;
const racedPromise = typeof timeout === 'number' && timeout > 0 ? Promise.race([apiPromise, (0, _rejectAfterTimeout.default)(timeout)]) : apiPromise;
return (0, _parseResponse.default)(racedPromise, parseMethod);
}

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

import { ParseMethod, SupersetClientResponse } from '../types';
export default function parseResponse(apiPromise: Promise<Response>, parseMethod?: ParseMethod): Promise<SupersetClientResponse>;
import { ParseMethod, TextResponse, JsonResponse } from '../types';
export default function parseResponse<T extends ParseMethod = 'json'>(apiPromise: Promise<Response>, parseMethod?: T): Promise<T extends "raw" | null ? Response : T extends "json" | undefined ? JsonResponse : T extends "text" ? TextResponse : never>;
//# sourceMappingURL=parseResponse.d.ts.map

@@ -6,29 +6,33 @@ "use strict";

function rejectIfNotOkay(response) {
if (!response.ok) return Promise.reject(response);
return Promise.resolve(response);
}
async function parseResponse(apiPromise, parseMethod) {
const response = await apiPromise; // reject failed HTTP requests with the raw response
function parseResponse(apiPromise, parseMethod = 'json') {
const checkedPromise = apiPromise.then(rejectIfNotOkay);
if (!response.ok) {
return Promise.reject(response);
}
if (parseMethod === null) {
return apiPromise.then(rejectIfNotOkay);
if (parseMethod === null || parseMethod === 'raw') {
return response;
}
if (parseMethod === 'text') {
return checkedPromise.then(response => response.text().then(text => ({
const text = await response.text();
const result = {
response,
text
})));
}
};
return result;
} // by default treat this as json
if (parseMethod === 'json') {
return checkedPromise.then(response => response.json().then(json => ({
if (parseMethod === undefined || parseMethod === 'json') {
const json = await response.json();
const result = {
json,
response
})));
};
return result;
}
throw new Error("Expected parseResponse=null|json|text, got '" + parseMethod + "'.");
throw new Error("Expected parseResponse=json|text|raw|null, got '" + parseMethod + "'.");
}
import { FetchRetryOptions } from './types';
export declare const DEFAULT_BASE_URL = "http://localhost";
export declare const HTTP_STATUS_OK = 200;

@@ -3,0 +4,0 @@ export declare const HTTP_STATUS_NOT_MODIFIED = 304;

"use strict";
exports.__esModule = true;
exports.DEFAULT_FETCH_RETRY_OPTIONS = exports.CACHE_KEY = exports.CACHE_AVAILABLE = exports.HTTP_STATUS_NOT_MODIFIED = exports.HTTP_STATUS_OK = void 0;
// HTTP status codes
exports.DEFAULT_FETCH_RETRY_OPTIONS = exports.CACHE_KEY = exports.CACHE_AVAILABLE = exports.HTTP_STATUS_NOT_MODIFIED = exports.HTTP_STATUS_OK = exports.DEFAULT_BASE_URL = void 0;
const DEFAULT_BASE_URL = 'http://localhost'; // HTTP status codes
exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
const HTTP_STATUS_OK = 200;

@@ -7,0 +9,0 @@ exports.HTTP_STATUS_OK = HTTP_STATUS_OK;

@@ -25,5 +25,8 @@ "use strict";

},
reset: () => {
singletonClient = undefined;
},
getInstance,
delete: request => getInstance().delete(request),
get: request => getInstance().get(request),
getInstance,
init: force => getInstance().init(force),

@@ -33,11 +36,6 @@ isAuthenticated: () => getInstance().isAuthenticated(),

put: request => getInstance().put(request),
reAuthenticate: () => getInstance().init(
/* force = */
true),
request: _request => getInstance().request(_request),
reset: () => {
singletonClient = undefined;
}
reAuthenticate: () => getInstance().reAuthenticate(),
request: _request => getInstance().request(_request)
};
var _default = SupersetClient;
exports.default = _default;

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

import { ClientConfig, ClientTimeout, Credentials, CsrfPromise, CsrfToken, FetchRetryOptions, Headers, Host, Mode, Protocol, RequestConfig, SupersetClientResponse } from './types';
import { ClientConfig, ClientTimeout, Credentials, CsrfPromise, CsrfToken, FetchRetryOptions, Headers, Host, Mode, Protocol, RequestConfig, ParseMethod } from './types';
export default class SupersetClientClass {

@@ -7,2 +7,3 @@ credentials: Credentials;

fetchRetryOptions?: FetchRetryOptions;
baseUrl: string;
protocol: Protocol;

@@ -13,12 +14,23 @@ host: Host;

timeout: ClientTimeout;
constructor({ protocol, host, headers, fetchRetryOptions, mode, timeout, credentials, csrfToken, }?: ClientConfig);
constructor({ baseUrl, host, protocol, headers, fetchRetryOptions, mode, timeout, credentials, csrfToken, }?: ClientConfig);
init(force?: boolean): CsrfPromise;
reAuthenticate(): Promise<string | undefined>;
isAuthenticated(): boolean;
get(requestConfig: RequestConfig): Promise<SupersetClientResponse>;
delete(requestConfig: RequestConfig): Promise<SupersetClientResponse>;
put(requestConfig: RequestConfig): Promise<SupersetClientResponse>;
post(requestConfig: RequestConfig): Promise<SupersetClientResponse>;
request({ body, credentials, endpoint, fetchRetryOptions, headers, host, method, mode, parseMethod, postPayload, signal, stringify, timeout, url, }: RequestConfig): Promise<SupersetClientResponse>;
get<T extends ParseMethod = 'json'>(requestConfig: RequestConfig & {
parseMethod?: T;
}): Promise<T extends "raw" | null ? Response : T extends "json" | undefined ? import("./types").JsonResponse : T extends "text" ? import("./types").TextResponse : never>;
delete<T extends ParseMethod = 'json'>(requestConfig: RequestConfig & {
parseMethod?: T;
}): Promise<T extends "raw" | null ? Response : T extends "json" | undefined ? import("./types").JsonResponse : T extends "text" ? import("./types").TextResponse : never>;
put<T extends ParseMethod = 'json'>(requestConfig: RequestConfig & {
parseMethod?: T;
}): Promise<T extends "raw" | null ? Response : T extends "json" | undefined ? import("./types").JsonResponse : T extends "text" ? import("./types").TextResponse : never>;
post<T extends ParseMethod = 'json'>(requestConfig: RequestConfig & {
parseMethod?: T;
}): Promise<T extends "raw" | null ? Response : T extends "json" | undefined ? import("./types").JsonResponse : T extends "text" ? import("./types").TextResponse : never>;
request<T extends ParseMethod = 'json'>({ credentials, mode, endpoint, host, url, headers, timeout, ...rest }: RequestConfig & {
parseMethod?: T;
}): Promise<T extends "raw" | null ? Response : T extends "json" | undefined ? import("./types").JsonResponse : T extends "text" ? import("./types").TextResponse : never>;
ensureAuth(): CsrfPromise;
getCSRFToken(): CsrfPromise;
getCSRFToken(): Promise<string | undefined>;
getUrl({ host: inputHost, endpoint, url, }?: {

@@ -25,0 +37,0 @@ endpoint?: string;

@@ -6,3 +6,3 @@ "use strict";

var _callApi = _interopRequireDefault(require("./callApi"));
var _callApiAndParseWithTimeout = _interopRequireDefault(require("./callApi/callApiAndParseWithTimeout"));

@@ -13,2 +13,4 @@ var _constants = require("./constants");

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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); }

@@ -20,4 +22,5 @@

constructor({
protocol = 'http:',
host = 'localhost',
baseUrl = _constants.DEFAULT_BASE_URL,
host,
protocol,
headers = {},

@@ -38,2 +41,4 @@ fetchRetryOptions = {},

_defineProperty(this, "baseUrl", void 0);
_defineProperty(this, "protocol", void 0);

@@ -49,10 +54,14 @@

const url = new URL(host || protocol ? (protocol || 'https:') + "//" + (host || 'localhost') : baseUrl, // baseUrl for API could also be relative, so we provide current location.href
// as the base of baseUrl
window.location.href);
this.baseUrl = url.href.replace(/\/+$/, ''); // always strip trailing slash
this.host = url.host;
this.protocol = url.protocol;
this.headers = _extends({}, headers);
this.host = host;
this.mode = mode;
this.timeout = timeout;
this.protocol = protocol;
this.credentials = credentials;
this.csrfToken = csrfToken;
this.csrfPromise = undefined;
this.fetchRetryOptions = _extends({}, _constants.DEFAULT_FETCH_RETRY_OPTIONS, {}, fetchRetryOptions);

@@ -68,3 +77,3 @@

init(force = false) {
async init(force = false) {
if (this.isAuthenticated() && !force) {

@@ -77,2 +86,6 @@ return this.csrfPromise;

async reAuthenticate() {
return this.init(true);
}
isAuthenticated() {

@@ -107,30 +120,18 @@ // if CSRF protection is disabled in the Superset app, the token may be an empty string

async request({
body,
credentials,
endpoint,
fetchRetryOptions,
headers,
host,
method,
mode,
parseMethod,
postPayload,
signal,
stringify,
timeout,
url
}) {
return this.ensureAuth().then(() => (0, _callApi.default)({
body,
async request(_ref) {
let {
credentials,
mode,
endpoint,
host,
url,
headers,
timeout
} = _ref,
rest = _objectWithoutPropertiesLoose(_ref, ["credentials", "mode", "endpoint", "host", "url", "headers", "timeout"]);
await this.ensureAuth();
return (0, _callApiAndParseWithTimeout.default)(_extends({}, rest, {
credentials: credentials != null ? credentials : this.credentials,
fetchRetryOptions,
headers: _extends({}, this.headers, {}, headers),
method,
mode: mode != null ? mode : this.mode,
parseMethod,
postPayload,
signal,
stringify,
timeout: timeout != null ? timeout : this.timeout,
url: this.getUrl({

@@ -140,11 +141,13 @@ endpoint,

url
})
}),
headers: _extends({}, this.headers, {}, headers),
timeout: timeout != null ? timeout : this.timeout
}));
}
ensureAuth() {
async ensureAuth() {
var _this$csrfPromise;
return (_this$csrfPromise = this.csrfPromise) != null ? _this$csrfPromise : Promise.reject({
error: "SupersetClient has no CSRF token, ensure it is initialized or\n try logging into the Superset instance at " + this.getUrl({
error: "SupersetClient has not been provided a CSRF token, ensure it is\n initialized with `client.getCSRFToken()` or try logging in at\n " + this.getUrl({
endpoint: '/login'

@@ -159,3 +162,3 @@ })

this.csrfPromise = (0, _callApi.default)({
this.csrfPromise = (0, _callApiAndParseWithTimeout.default)({
credentials: this.credentials,

@@ -168,6 +171,9 @@ headers: _extends({}, this.headers),

endpoint: 'superset/csrf_token/'
})
}).then(response => {
if (typeof response.json === 'object') {
this.csrfToken = response.json.csrf_token;
}),
parseMethod: 'json'
}).then(({
json
}) => {
if (typeof json === 'object') {
this.csrfToken = json.csrf_token;

@@ -181,9 +187,9 @@ if (typeof this.csrfToken === 'string') {

if (!this.isAuthenticated()) {
return Promise.reject({
error: 'Failed to fetch CSRF token'
});
if (this.isAuthenticated()) {
return this.csrfToken;
}
return this.csrfToken;
return Promise.reject({
error: 'Failed to fetch CSRF token'
});
});

@@ -190,0 +196,0 @@ return this.csrfPromise;

@@ -0,1 +1,19 @@

/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import SupersetClientClass from './SupersetClientClass';

@@ -15,30 +33,39 @@ export declare type Body = RequestInit['body'];

export declare type Host = string;
export declare type Json = {
[k: string]: any;
export declare type JsonPrimitive = string | number | boolean | null;
/**
* More strict JSON value types. If this fails to satisfy TypeScript when using
* as function arguments, use `JsonObject` instead. `StrictJsonObject` helps make
* sure all values are plain objects, but it does not accept specific types when
* used as function arguments.
* (Ref: https://github.com/microsoft/TypeScript/issues/15300).
*/
export declare type StrictJsonValue = JsonPrimitive | StrictJsonObject | StrictJsonArray;
export declare type StrictJsonArray = StrictJsonValue[];
/**
* More strict JSON objects that makes sure all values are plain objects.
* If this fails to satisfy TypeScript when using as function arguments,
* use `JsonObject` instead.
* (Ref: https://github.com/microsoft/TypeScript/issues/15300).
*/
export declare type StrictJsonObject = {
[member: string]: StrictJsonValue;
};
export declare type JsonValue = JsonPrimitive | JsonObject | JsonArray;
export declare type JsonArray = JsonValue[];
export declare type JsonObject = {
[member: string]: any;
};
/**
* Request payload, can be use in GET query string, Post form or POST JSON.
* If string, will parse with JSON.parse.
*/
export declare type Payload = JsonObject | string | null;
export declare type Method = RequestInit['method'];
export declare type PostPayload = {
[key: string]: any;
};
export declare type Mode = RequestInit['mode'];
export declare type Redirect = RequestInit['redirect'];
export declare type ClientTimeout = number | undefined;
export declare type ParseMethod = 'json' | 'text' | null;
export declare type ParseMethod = 'json' | 'text' | 'raw' | null | undefined;
export declare type Signal = RequestInit['signal'];
export declare type Stringify = boolean;
export declare type Url = string;
export interface CallApi {
body?: Body;
cache?: Cache;
credentials?: Credentials;
fetchRetryOptions?: FetchRetryOptions;
headers?: Headers;
method?: Method;
mode?: Mode;
postPayload?: PostPayload;
redirect?: Redirect;
signal?: Signal;
stringify?: Stringify;
url: Url;
}
export interface RequestBase {

@@ -52,4 +79,5 @@ body?: Body;

method?: Method;
parseMethod?: ParseMethod;
postPayload?: PostPayload;
jsonPayload?: Payload;
postPayload?: Payload | FormData;
searchParams?: Payload | URLSearchParams;
signal?: Signal;

@@ -59,16 +87,24 @@ stringify?: Stringify;

}
export interface CallApi extends RequestBase {
url: Url;
cache?: Cache;
redirect?: Redirect;
}
export interface RequestWithEndpoint extends RequestBase {
endpoint: Endpoint;
url?: undefined;
url?: Url;
}
export interface RequestWithUrl extends RequestBase {
url: Url;
endpoint?: undefined;
endpoint?: Endpoint;
}
export declare type RequestConfig = RequestWithEndpoint | RequestWithUrl;
export interface JsonTextResponse {
json?: Json;
export interface JsonResponse {
response: Response;
text?: string;
json: JsonObject;
}
export interface TextResponse {
response: Response;
text: string;
}
export declare type CsrfToken = string;

@@ -78,2 +114,5 @@ export declare type CsrfPromise = Promise<string | undefined>;

export interface ClientConfig {
baseUrl?: string;
host?: Host;
protocol?: Protocol;
credentials?: Credentials;

@@ -83,21 +122,11 @@ csrfToken?: CsrfToken;

headers?: Headers;
host?: Host;
protocol?: Protocol;
mode?: Mode;
timeout?: ClientTimeout;
}
export interface SupersetClientInterface {
export interface SupersetClientInterface extends Pick<SupersetClientClass, 'delete' | 'get' | 'post' | 'put' | 'request' | 'init' | 'isAuthenticated' | 'reAuthenticate'> {
configure: (config?: ClientConfig) => SupersetClientClass;
delete: (request: RequestConfig) => Promise<SupersetClientResponse>;
get: (request: RequestConfig) => Promise<SupersetClientResponse>;
getInstance: (maybeClient?: SupersetClientClass) => SupersetClientClass;
init: (force?: boolean) => Promise<string | undefined>;
isAuthenticated: () => boolean;
post: (request: RequestConfig) => Promise<SupersetClientResponse>;
put: (request: RequestConfig) => Promise<SupersetClientResponse>;
reAuthenticate: () => Promise<string | undefined>;
request: (request: RequestConfig) => Promise<SupersetClientResponse>;
reset: () => void;
}
export declare type SupersetClientResponse = Response | JsonTextResponse;
export declare type SupersetClientResponse = Response | JsonResponse | TextResponse;
//# sourceMappingURL=types.d.ts.map
{
"name": "@superset-ui/connection",
"version": "0.14.0",
"version": "0.14.9",
"description": "Superset UI connection",

@@ -41,3 +41,3 @@ "sideEffects": false,

},
"gitHead": "bccbf2ab4f6618c92cb4f633869ffdf846031430"
"gitHead": "92e0ccbec0e753335a03fb411b59242f4b624391"
}

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