All files / src/v1 api.ts

46.72% Statements 57/122
22.22% Branches 12/54
42.86% Functions 12/28
46.72% Lines 57/122

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331                3x 3x 3x 3x 3x 3x         3x 3x         3x 3x 3x                                                                               6x 6x 18x 18x 18x   6x                                     6x 6x 6x       6x               6x 6x   6x 6x 6x             6x       6x 6x                                                                   6x                                                               6x 6x     6x               6x 6x       6x   6x             6x 6x   6x                                                                   3x   3x                           12x 12x 12x       6x 6x     6x   6x           6x     6x                 3x                                                     3x 3x 3x 3x 3x    
/**
 * Copyright: ThoughtSpot Inc. 2012-2016
 * Author: Shashank Singh (sunny@thoughtspot.com)
 *
 * @fileoverview ThoughtSpot Javascript API for use of ThoughtSpot in external webpages.
 */
 
// eslint-disable-next-line no-shadow
enum Events {
    THOUGHTSPOT_AUTH_EXPIRED = 'ThoughtspotAuthExpired',
    EXPORT_VIZ_DATA_TO_PARENT = 'exportVizDataToParent',
    ALERT = 'alert',
    EXPORT_VIZ_DATA_TO_CHILD = 'exportVizDataToChild',
    GET_DATA = 'getData',
}
 
type Callback = (...args: any[]) => void;
 
const SSO_REDIRECTION_MARKER_GUID = '5e16222e-ef02-43e9-9fbd-24226bf3ce5b';
const EndPoints = {
    AUTH_VERIFICATION: '/callosum/v1/session/info',
    SSO_LOGIN_TEMPLATE: '/callosum/v1/saml/login?targetURLPath={targetUrl}',
};
 
let autoDeterminedThoughtspotHost = '';
const authExpirationHandlers: Callback[] = [];
let initialized = false;
let thoughtspotHost: string;
let dataCallBack: Callback;
 
function parseUrl(url: string) {
    const parser = document.createElement('a');
    parser.href = url;
 
    return {
        protocol: parser.protocol,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        hash: parser.hash,
        host: parser.host,
    };
}
 
function getScriptHost() {
    const scripts = document.getElementsByTagName('script');
    const currentScriptNode = scripts[scripts.length - 1];
 
    const currentScriptSrc = currentScriptNode?.src;
    if (!currentScriptSrc) {
        // eslint-disable-next-line no-console
        console.error(
            "Could not determine Thoughtspot domain from script's url",
        );
        return '';
    }
 
    const currentScriptSrcParts = parseUrl(currentScriptSrc);
    return currentScriptSrcParts.host;
}
 
function formatString(
    template: string,
    keyValueMap: { [key: string]: string },
) {
    let str = '';
    Object.keys(keyValueMap).forEach((key) => {
        const pattern = `\\{${key}\\}`;
        const re = new RegExp(pattern, 'g');
        str = template.replace(re, keyValueMap[key]);
    });
    return template;
}
 
function appendToUrlHash(url: string, stringToAppend: string) {
    let outputUrl = url;
    const encStringToAppend = encodeURIComponent(stringToAppend);
 
    if (url.indexOf('#') >= 0) {
        outputUrl = `${outputUrl}${encStringToAppend}`;
    } else {
        outputUrl = `${outputUrl}#${encStringToAppend}`;
    }
 
    return outputUrl;
}
 
function getAbsoluteTSUrl(tsHost: string, relativeUrl: string) {
    // assume that the protocol for TS is the same as the protocol
    // of the parent page. Mixed content is getting deprecated anyway
    const protocol = document.location.protocol;
    let path = relativeUrl;
    Iif (relativeUrl[0] !== '/') {
        path = `/${relativeUrl}`;
    }
 
    return formatString('{protocol}//{domain}{path}', {
        protocol,
        domain: tsHost,
        path,
    });
}
 
function checkIfLoggedIn(tsHost: string, callback: Callback) {
    const xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
 
    xhr.onreadystatechange = () => {
        Eif (xhr.readyState < 4) {
            return;
        }
 
        const authenticated = xhr.status === 200;
        callback(authenticated);
    };
 
    const authVerificationUrl = getAbsoluteTSUrl(
        tsHost,
        EndPoints.AUTH_VERIFICATION,
    );
    xhr.open('GET', authVerificationUrl, true);
    xhr.send();
}
 
function doSSO(tsHost: string) {
    const ssoRedirectUrl = appendToUrlHash(
        window.location.href,
        SSO_REDIRECTION_MARKER_GUID,
    );
 
    // bring back the page to the same url
    const ssoEndPoint = formatString(EndPoints.SSO_LOGIN_TEMPLATE, {
        targetUrl: encodeURIComponent(ssoRedirectUrl),
    });
 
    const ssoURL = getAbsoluteTSUrl(tsHost, ssoEndPoint);
    window.location.href = ssoURL;
}
 
function isAtSSORedirectUrl() {
    return window.location.href.indexOf(SSO_REDIRECTION_MARKER_GUID) >= 0;
}
 
function removeSSORedirectUrlMarker() {
    // Note (sunny): this will leave a # around even if it was not in the URL to
    // being with, trying to remove the hash by changing window.location will reload
    // the page which we don't want. We'll live with adding an unnecessary hash to the
    // parent page's URL until we find any use case where that creates an issue
    window.location.hash = window.location.hash.replace(
        SSO_REDIRECTION_MARKER_GUID,
        '',
    );
}
 
function setUpAuthExpirationHandling(tsHost: string) {
    window.addEventListener('message', (event) => {
        const messageOrigin = event.origin.replace(/^https?:\/\//, '');
        if (messageOrigin !== tsHost) {
            return;
        }
 
        if (
            !event.data ||
            event.data.type !== Events.THOUGHTSPOT_AUTH_EXPIRED
        ) {
            return;
        }
 
        // a statically embedded TS iframe might fire this
        // on load even before initialization has happened
        // the external page could treat this as a auto log
        // out scenario and try to authenticate again, interfering
        // with any ongoing initialiation.
        // Hence we don't fire `notifyOnAuthExpiration` until the
        // system has initialized.
        if (!initialized) {
            return;
        }
 
        authExpirationHandlers.forEach((authExpirationHandler) => {
            authExpirationHandler();
        });
    });
}
 
function addAuthExpirationHandler(authExpirationHandler: Callback) {
    const handlerAlreadySetUp =
        authExpirationHandlers.indexOf(authExpirationHandler) >= 0;
    Iif (handlerAlreadySetUp) {
        return;
    }
    authExpirationHandlers.push(authExpirationHandler);
}
 
function initialize(
    onInitialized: Callback,
    onAuthExpiration: Callback,
    _thoughtspotHost: string,
): void {
    let tsHost = _thoughtspotHost;
    Iif (_thoughtspotHost === undefined) {
        autoDeterminedThoughtspotHost = getScriptHost();
        tsHost = autoDeterminedThoughtspotHost;
    }
    thoughtspotHost = tsHost;
 
    Iif (!thoughtspotHost) {
        throw new Error(
            'Invalid configuration, parameter `thoughtspotHost` ' +
                'was not provided and could not be automatically deduced',
        );
    }
 
    setUpAuthExpirationHandling(thoughtspotHost);
    addAuthExpirationHandler(onAuthExpiration);
 
    checkIfLoggedIn(thoughtspotHost, (isLoggedIn: boolean) => {
        if (isLoggedIn) {
            if (isAtSSORedirectUrl()) {
                removeSSORedirectUrlMarker();
            }
            initialized = true;
            onInitialized(true);
            return;
        }
 
        // we have already tried authentication and it did not succeed, restore
        // the current url to the original one and call the callback
        if (isAtSSORedirectUrl()) {
            removeSSORedirectUrlMarker();
            initialized = true;
            onInitialized(false);
            return;
        }
 
        // redirect for SSO, when SSO is done this page will be loaded
        // again and the same JS will execute again
        doSSO(thoughtspotHost);
    });
}
 
function notifyOnAuthExpiration(): void {
    window.parent.postMessage(
        {
            type: Events.THOUGHTSPOT_AUTH_EXPIRED,
        },
        '*',
    );
}
 
const messageCallbacks = {};
 
const eventHandler = {
    handleEvent: (event: any) => {
        // eslint-disable-next-line no-underscore-dangle
        if (event.data && event.data.__type) {
            // eslint-disable-next-line no-underscore-dangle
            const callback = messageCallbacks[event.origin][event.data.__type];
            if (typeof callback === 'function') {
                callback(event);
            }
        }
    },
};
 
function addSubscription(tsHost: string, type: string, callback: Callback) {
    messageCallbacks[tsHost] = messageCallbacks[tsHost] || {};
    messageCallbacks[tsHost][type] = callback;
    window.addEventListener('message', eventHandler);
}
 
function subscribeToAlerts(tsHost: string, onAlertCallback: Callback): void {
    let alertCallback = onAlertCallback;
    Iif (typeof tsHost === 'function') {
        alertCallback = tsHost;
    } else {
        thoughtspotHost = tsHost || thoughtspotHost;
    }
    addSubscription(thoughtspotHost, Events.ALERT, (event: any) => {
        alertCallback(event);
    });
}
 
function subscribeToData(responseCallback: Callback): void {
    Iif (!thoughtspotHost) {
        throw new Error('ThoughtSpot App needs to be initialized with a host');
    }
    addSubscription(
        thoughtspotHost,
        Events.EXPORT_VIZ_DATA_TO_PARENT,
        (event: any) => {
            responseCallback(event.data.data);
        },
    );
}
 
window.addEventListener('message', (event) => {
    if (
        // eslint-disable-next-line no-underscore-dangle
        event.data.__type === Events.EXPORT_VIZ_DATA_TO_CHILD &&
        event.data.data !== undefined &&
        dataCallBack !== undefined &&
        typeof dataCallBack === 'function'
    ) {
        dataCallBack(event.data.data);
    }
});
 
function requestTSAppToPushData() {
    window.parent.postMessage(
        {
            __type: Events.GET_DATA,
        },
        '*',
    );
}
 
function getCurrentData(responseCallBack: Callback): void {
    dataCallBack = responseCallBack;
    requestTSAppToPushData();
}
 
export {
    initialize,
    notifyOnAuthExpiration,
    subscribeToAlerts,
    subscribeToData,
    getCurrentData,
};