• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

thoughtspot / visual-embed-sdk / #3059

16 Dec 2025 01:41PM UTC coverage: 93.663% (-0.7%) from 94.364%
#3059

Pull #388

ruchI9897
poc
Pull Request #388: poc

1366 of 1551 branches covered (88.07%)

Branch coverage included in aggregate %.

5 of 17 new or added lines in 3 files covered. (29.41%)

33 existing lines in 6 files now uncovered.

3216 of 3341 relevant lines covered (96.26%)

107.9 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.33
/src/embed/base.ts
1
/* eslint-disable camelcase */
2
/* eslint-disable import/no-mutable-exports */
3
/**
4
 * Copyright (c) 2022
5
 *
6
 * Base classes
7
 * @summary Base classes
8
 * @author Ayon Ghosh <ayon.ghosh@thoughtspot.com>
9
 */
10
import EventEmitter from 'eventemitter3';
16✔
11
import { registerReportingObserver } from '../utils/reporting';
16✔
12
import { logger, setGlobalLogLevelOverride } from '../utils/logger';
16✔
13
import { tokenizedFetch } from '../tokenizedFetch';
16✔
14
import { EndPoints } from '../utils/authService/authService';
16✔
15
import { getThoughtSpotHost } from '../config';
16✔
16
import {
16✔
17
    AuthType, EmbedConfig, LogLevel, Param, PrefetchFeatures,
18
} from '../types';
19
import {
16✔
20
    authenticate,
21
    logout as _logout,
22
    AuthFailureType,
23
    AuthStatus,
24
    AuthEvent,
25
    notifyAuthFailure,
26
    notifyAuthSDKSuccess,
27
    notifyAuthSuccess,
28
    notifyLogout,
29
    setAuthEE,
30
    AuthEventEmitter,
31
    postLoginService,
32
} from '../auth';
33
import '../utils/with-resolvers-polyfill';
16✔
34
import { uploadMixpanelEvent, MIXPANEL_EVENT } from '../mixpanel-service';
16✔
35
import { getEmbedConfig, setEmbedConfig } from './embedConfig';
16✔
36
import { getQueryParamString, getValueFromWindow, storeValueInWindow } from '../utils';
16✔
37
import { resetAllCachedServices } from '../utils/resetServices';
16✔
38
import { reload } from '../utils/processTrigger';
16✔
39

40
const CONFIG_DEFAULTS: Partial<EmbedConfig> = {
16✔
41
    loginFailedMessage: 'Not logged in',
42
    authTriggerText: 'Authorize',
43
    authType: AuthType.None,
44
    logLevel: LogLevel.ERROR,
45
    waitForCleanupOnDestroy: false,
46
    cleanupTimeout: 5000,
47
};
48

49
export interface executeTMLInput {
50
    metadata_tmls: string[];
51
    import_policy?: 'PARTIAL' | 'ALL_OR_NONE' | 'VALIDATE_ONLY';
52
    create_new?: boolean;
53
}
54

55
export interface exportTMLInput {
56
    metadata: {
57
        identifier: string;
58
        type?: 'LIVEBOARD' | 'ANSWER' | 'LOGICAL_TABLE' | 'CONNECTION';
59
    }[];
60
    export_associated?: boolean;
61
    export_fqn?: boolean;
62
    edoc_format?: 'YAML' | 'JSON';
63
}
64

65
export let authPromise: Promise<boolean>;
66

67
export const getAuthPromise = (): Promise<boolean> => authPromise;
420✔
68

69
export {
70
    notifyAuthFailure, notifyAuthSDKSuccess, notifyAuthSuccess, notifyLogout,
24✔
71
};
72

73
/**
74
 * Perform authentication on the ThoughtSpot app as applicable.
75
 */
76
export const handleAuth = (): Promise<boolean> => {
16✔
77
    authPromise = authenticate(getEmbedConfig());
75✔
78
    authPromise.then(
75✔
79
        (isLoggedIn) => {
80
            if (!isLoggedIn) {
74✔
81
                notifyAuthFailure(AuthFailureType.SDK);
7✔
82
            } else {
83
                // Post login service is called after successful login.
84
                postLoginService();
67✔
85
                notifyAuthSDKSuccess();
67✔
86
            }
87
        },
88
        () => {
89
            notifyAuthFailure(AuthFailureType.SDK);
1✔
90
        },
91
    );
92
    return authPromise;
75✔
93
};
94

95
const hostUrlToFeatureUrl = {
16✔
96
    [PrefetchFeatures.SearchEmbed]: (url: string, flags: string) => `${url}v2/?${flags}#/embed/answer`,
2✔
97
    [PrefetchFeatures.LiveboardEmbed]: (url: string, flags: string) => `${url}?${flags}`,
2✔
98
    [PrefetchFeatures.FullApp]: (url: string, flags: string) => `${url}?${flags}`,
2✔
UNCOV
99
    [PrefetchFeatures.VizEmbed]: (url: string, flags: string) => `${url}?${flags}`,
×
100
};
101

102
/**
103
 * Prefetches static resources from the specified URL. Web browsers can then cache the
104
 * prefetched resources and serve them from the user's local disk to provide faster access
105
 * to your app.
106
 * @param url The URL provided for prefetch
107
 * @param prefetchFeatures Specify features which needs to be prefetched.
108
 * @param additionalFlags This can be used to add any URL flag.
109
 * @version SDK: 1.4.0 | ThoughtSpot: ts7.sep.cl, 7.2.1
110
 * @group Global methods
111
 */
112
export const prefetch = (
16✔
113
    url?: string,
114
    prefetchFeatures?: PrefetchFeatures[],
115
    additionalFlags?: { [key: string]: string | number | boolean },
116
): void => {
117
    if (url === '') {
5✔
118
        // eslint-disable-next-line no-console
119
        logger.warn('The prefetch method does not have a valid URL');
1✔
120
    } else {
121
        const features = prefetchFeatures || [PrefetchFeatures.FullApp];
4✔
122
        let hostUrl = url || getEmbedConfig().thoughtSpotHost;
4!
123
        const prefetchFlags = {
4✔
124
            [Param.EmbedApp]: true,
125
            ...getEmbedConfig()?.additionalFlags,
12!
126
            ...additionalFlags,
127
        };
128
        hostUrl = hostUrl[hostUrl.length - 1] === '/' ? hostUrl : `${hostUrl}/`;
4✔
129
        Array.from(
4✔
130
            new Set(features
131
                .map((feature) => hostUrlToFeatureUrl[feature](
6✔
132
                    hostUrl,
133
                    getQueryParamString(prefetchFlags),
134
                ))),
135
        )
136
            .forEach(
137
                (prefetchUrl, index) => {
138
                    const iFrame = document.createElement('iframe');
6✔
139
                    iFrame.src = prefetchUrl;
6✔
140
                    iFrame.style.width = '0';
6✔
141
                    iFrame.style.height = '0';
6✔
142
                    iFrame.style.border = '0';
6✔
143

144
                    // Make it 'fixed' to keep it in a different stacking context.
145
                    //   This should solve the focus behaviours inside the iframe from
146
                    //   interfering with main body.
147
                    iFrame.style.position = 'fixed';
6✔
148
                    // Push it out of viewport.
149
                    iFrame.style.top = '100vh';
6✔
150
                    iFrame.style.left = '100vw';
6✔
151

152
                    iFrame.classList.add('prefetchIframe');
6✔
153
                    iFrame.classList.add(`prefetchIframeNum-${index}`);
6✔
154
                    document.body.appendChild(iFrame);
6✔
155
                },
156
            );
157
    }
158
};
159

160
/**
161
 *
162
 * @param embedConfig
163
 */
164
function sanity(embedConfig: EmbedConfig) {
165
    if (embedConfig.thoughtSpotHost === undefined) {
118✔
166
        throw new Error('ThoughtSpot host not provided');
2✔
167
    }
168
    if (embedConfig.authType === AuthType.TrustedAuthToken) {
116✔
169
        if (!embedConfig.authEndpoint && typeof embedConfig.getAuthToken !== 'function') {
3✔
170
            throw new Error('Trusted auth should provide either authEndpoint or getAuthToken');
2✔
171
        }
172
    }
173
}
174

175
/**
176
 *
177
 * @param embedConfig
178
 */
179
function backwardCompat(embedConfig: EmbedConfig): EmbedConfig {
180
    const newConfig = { ...embedConfig };
109✔
181
    if (embedConfig.noRedirect !== undefined && embedConfig.inPopup === undefined) {
109✔
182
        newConfig.inPopup = embedConfig.noRedirect;
1✔
183
    }
184
    return newConfig;
109✔
185
}
186

187
type InitFlagStore = {
188
  initPromise: Promise<ReturnType<typeof init>>;
189
  isInitCalled: boolean;
190
  initPromiseResolve: (value: ReturnType<typeof init>) => void;
191
}
192
const initFlagKey = 'initFlagKey';
16✔
193

194
export const createAndSetInitPromise = (): void => {
16✔
195
    const {
196
        promise: initPromise,
197
        resolve: initPromiseResolve,
198
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
199
        // @ts-ignore
200
    } = Promise.withResolvers<AuthEventEmitter>();
19✔
201
    const initFlagStore: InitFlagStore = {
19✔
202
        initPromise,
203
        isInitCalled: false,
204
        initPromiseResolve,
205
    };
206
    storeValueInWindow(initFlagKey, initFlagStore, {
19✔
207
        // In case of diff imports the promise might be already set
208
        ignoreIfAlreadyExists: true,
209
    });
210
};
211

212
createAndSetInitPromise();
16✔
213

214
export const getInitPromise = ():
16✔
215
    Promise<
216
      ReturnType<typeof init>
217
    > => getValueFromWindow<InitFlagStore>(initFlagKey)?.initPromise;
465!
218

219
export const getIsInitCalled = (): boolean => !!getValueFromWindow(initFlagKey)?.isInitCalled;
427!
220

221
/**
222
 * Initializes the Visual Embed SDK globally and perform
223
 * authentication if applicable. This function needs to be called before any ThoughtSpot
224
 * component like Liveboard etc can be embedded. But need not wait for AuthEvent.SUCCESS
225
 * to actually embed. That is handled internally.
226
 * @param embedConfig The configuration object containing ThoughtSpot host,
227
 * authentication mechanism and so on.
228
 * @example
229
 * ```js
230
 *   const authStatus = init({
231
 *     thoughtSpotHost: 'https://my.thoughtspot.cloud',
232
 *     authType: AuthType.None,
233
 *   });
234
 *   authStatus.on(AuthStatus.FAILURE, (reason) => { // do something here });
235
 * ```
236
 * @returns {@link AuthEventEmitter} event emitter which emits events on authentication success,
237
 *      failure and logout. See {@link AuthStatus}
238
 * @version SDK: 1.0.0 | ThoughtSpot ts7.april.cl, 7.2.1
239
 * @group Authentication / Init
240
 */
241
export const init = (embedConfig: EmbedConfig): AuthEventEmitter => {
16✔
242
    sanity(embedConfig);
112✔
243
    resetAllCachedServices();
109✔
244
    embedConfig = setEmbedConfig(
109✔
245
        backwardCompat({
246
            ...CONFIG_DEFAULTS,
247
            ...embedConfig,
248
            thoughtSpotHost: getThoughtSpotHost(embedConfig),
249
        }),
250
    );
251

252
    setGlobalLogLevelOverride(embedConfig.logLevel);
109✔
253
    registerReportingObserver();
109✔
254

255
    const authEE = new EventEmitter<AuthStatus | AuthEvent>();
109✔
256
    setAuthEE(authEE);
109✔
257
    handleAuth();
109✔
258

259
    const { password, ...configToTrack } = getEmbedConfig();
109✔
260
    uploadMixpanelEvent(MIXPANEL_EVENT.VISUAL_SDK_CALLED_INIT, {
109✔
261
        ...configToTrack,
262
        usedCustomizationSheet: embedConfig.customizations?.style?.customCSSUrl != null,
654✔
263
        usedCustomizationVariables: embedConfig.customizations?.style?.customCSS?.variables != null,
981✔
264
        usedCustomizationRules:
265
            embedConfig.customizations?.style?.customCSS?.rules_UNSTABLE != null,
981✔
266
        usedCustomizationStrings: !!embedConfig.customizations?.content?.strings,
654✔
267
        usedCustomizationIconSprite: !!embedConfig.customizations?.iconSpriteUrl,
327✔
268
    });
269

270
    if (getEmbedConfig().callPrefetch) {
109✔
271
        prefetch(getEmbedConfig().thoughtSpotHost);
2✔
272
    }
273

274
    // Resolves the promise created in the initPromiseKey
275
    getValueFromWindow<InitFlagStore>(initFlagKey).initPromiseResolve(authEE);
109✔
276
    getValueFromWindow<InitFlagStore>(initFlagKey).isInitCalled = true;
109✔
277

278
    return authEE as AuthEventEmitter;
109✔
279
};
280

281
/**
282
 *
283
 */
284
export function disableAutoLogin(): void {
16✔
285
    getEmbedConfig().autoLogin = false;
3✔
286
}
287

288
/**
289
 * Logs out from ThoughtSpot. This also sets the autoLogin flag to false, to
290
 * prevent the SDK from automatically logging in again.
291
 *
292
 * You can call the `init` method again to re login, if autoLogin is set to
293
 * true in this second call it will be honored.
294
 * @param doNotDisableAutoLogin This flag when passed will not disable autoLogin
295
 * @returns Promise which resolves when logout completes.
296
 * @version SDK: 1.10.1 | ThoughtSpot: 8.2.0.cl, 8.4.1-sw
297
 * @group Global methods
298
 */
299
export const logout = (doNotDisableAutoLogin = false): Promise<boolean> => {
16✔
300
    if (!doNotDisableAutoLogin) {
2✔
301
        disableAutoLogin();
2✔
302
    }
303
    return _logout(getEmbedConfig()).then((isLoggedIn) => {
2✔
304
        notifyLogout();
2✔
305
        return isLoggedIn;
2✔
306
    });
307
};
308

309
let renderQueue: Promise<any> = Promise.resolve();
16✔
310

311
/**
312
 * Renders functions in a queue, resolves to next function only after the callback next
313
 * is called
314
 * @param fn The function being registered
315
 */
316
export const renderInQueue = (fn: (next?: (val?: any) => void) => Promise<any>): Promise<any> => {
16✔
317
    const { queueMultiRenders = false } = getEmbedConfig();
417✔
318
    if (queueMultiRenders) {
417!
UNCOV
319
        renderQueue = renderQueue.then(() => new Promise((res) => fn(res)));
×
UNCOV
320
        return renderQueue;
×
321
    }
322
    // Sending an empty function to keep it consistent with the above usage.
323
    return fn(() => {}); // eslint-disable-line @typescript-eslint/no-empty-function
417✔
324
};
325

326
/**
327
 * Imports TML representation of the metadata objects into ThoughtSpot.
328
 * @param data
329
 * @returns imports TML data into ThoughtSpot
330
 * @example
331
 * ```js
332
 *  executeTML({
333
 * //Array of metadata Tmls in string format
334
 *      metadata_tmls: [
335
 *          "'\''{\"guid\":\"9bd202f5-d431-44bf-9a07-b4f7be372125\",
336
 *          \"liveboard\":{\"name\":\"Parameters Liveboard\"}}'\''"
337
 *      ],
338
 *      import_policy: 'PARTIAL', // Specifies the import policy for the TML import.
339
 *      create_new: false, // If selected, creates TML objects with new GUIDs.
340
 *  }).then(result => {
341
 *      console.log(result);
342
 *  }).catch(error => {
343
 *      console.error(error);
344
 *  });
345
 *```
346
 * @version SDK: 1.23.0 | ThoughtSpot: 9.4.0.cl
347
 * @group Global methods
348
 */
349
export const executeTML = async (data: executeTMLInput): Promise<any> => {
16✔
350
    try {
4✔
351
        sanity(getEmbedConfig());
4✔
352
    } catch (err) {
353
        return Promise.reject(err);
1✔
354
    }
355

356
    const { thoughtSpotHost, authType } = getEmbedConfig();
3✔
357
    const headers: Record<string, string | undefined> = {
3✔
358
        'Content-Type': 'application/json',
359
        'x-requested-by': 'ThoughtSpot',
360
    };
361

362
    const payload = {
3✔
363
        metadata_tmls: data.metadata_tmls,
364
        import_policy: data.import_policy || 'PARTIAL',
3!
365
        create_new: data.create_new || false,
6✔
366
    };
367
    return tokenizedFetch(`${thoughtSpotHost}${EndPoints.EXECUTE_TML}`, {
3✔
368
        method: 'POST',
369
        headers,
370
        body: JSON.stringify(payload),
371
        credentials: 'include',
372
    })
373
        .then((response) => {
374
            if (!response.ok) {
2!
UNCOV
375
                throw new Error(
×
376
                    `Failed to import TML data: ${response.status} - ${response.statusText}`,
377
                );
378
            }
379
            return response.json();
2✔
380
        })
381
        .catch((error) => {
382
            throw error;
1✔
383
        });
384
};
385

386
/**
387
 * Exports TML representation of the metadata objects from ThoughtSpot in JSON or YAML
388
 * format.
389
 * @param data
390
 * @returns exports TML data
391
 * @example
392
 * ```js
393
 * exportTML({
394
 *   metadata: [
395
 *     {
396
 *       type: "LIVEBOARD", //Metadata Type
397
 *       identifier: "9bd202f5-d431-44bf-9a07-b4f7be372125" //Metadata Id
398
 *     }
399
 *   ],
400
 *   export_associated: false,//indicates whether to export associated metadata objects
401
 *   export_fqn: false, //Adds FQNs of the referenced objects.For example, if you are
402
 *                      //exporting a Liveboard and its associated objects, the API
403
 *                      //returns the Liveboard TML data with the FQNs of the referenced
404
 *                      //worksheet. If the exported TML data includes FQNs, you don't need
405
 *                      //to manually add FQNs of the referenced objects during TML import.
406
 *   edoc_format: "JSON" //It takes JSON or YAML value
407
 * }).then(result => {
408
 *   console.log(result);
409
 * }).catch(error => {
410
 *   console.error(error);
411
 * });
412
 * ```
413
 * @version SDK: 1.23.0 | ThoughtSpot: 9.4.0.cl
414
 * @group Global methods
415
 */
416
export const exportTML = async (data: exportTMLInput): Promise<any> => {
16✔
417
    const { thoughtSpotHost, authType } = getEmbedConfig();
2✔
418
    try {
2✔
419
        sanity(getEmbedConfig());
2✔
420
    } catch (err) {
UNCOV
421
        return Promise.reject(err);
×
422
    }
423
    const payload = {
2✔
424
        metadata: data.metadata,
425
        export_associated: data.export_associated || false,
4✔
426
        export_fqn: data.export_fqn || false,
4✔
427
        edoc_format: data.edoc_format || 'YAML',
2!
428
    };
429

430
    const headers: Record<string, string | undefined> = {
2✔
431
        'Content-Type': 'application/json',
432
        'x-requested-by': 'ThoughtSpot',
433
    };
434

435
    return tokenizedFetch(`${thoughtSpotHost}${EndPoints.EXPORT_TML}`, {
2✔
436
        method: 'POST',
437
        headers,
438
        body: JSON.stringify(payload),
439
        credentials: 'include',
440
    })
441
        .then((response) => {
442
            if (!response.ok) {
1!
UNCOV
443
                throw new Error(
×
444
                    `Failed to export TML: ${response.status} - ${response.statusText}`,
445
                );
446
            }
447
            return response.json();
1✔
448
        })
449
        .catch((error) => {
450
            throw error;
1✔
451
        });
452
};
453

454
// For testing purposes only
455
/**
456
 *
457
 */
458
export function reset(): void {
16✔
459
    setEmbedConfig({} as any);
10✔
460
    setAuthEE(null);
10✔
461
    authPromise = null;
10✔
462
}
463

464
/**
465
 * Reloads the ThoughtSpot iframe.
466
 * @param iFrame
467
 * @group Global methods
468
 * @version SDK: 1.43.1
469
 */
470
export const reloadIframe = (iFrame: HTMLIFrameElement) => {
16✔
471
    if (!iFrame) {
2✔
472
        logger.warn('reloadIframe called with no iFrame element.');
1✔
473
        return;
1✔
474
    }
475
    reload(iFrame);
1✔
476
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc