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

thoughtspot / visual-embed-sdk / #3028

10 Dec 2025 11:28AM UTC coverage: 94.263% (-0.2%) from 94.432%
#3028

push

web-flow
SCAL-286757-4 Update GitHub workflow permissions for OIDC (#379)

1359 of 1530 branches covered (88.82%)

Branch coverage included in aggregate %.

3209 of 3316 relevant lines covered (96.77%)

108.08 hits per line

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

96.0
/src/utils.ts
1
/**
2
 * Copyright (c) 2023
3
 *
4
 * Common utility functions for ThoughtSpot Visual Embed SDK
5
 * @summary Utils
6
 * @author Ayon Ghosh <ayon.ghosh@thoughtspot.com>
7
 */
8

9
import merge from 'ts-deepmerge';
35✔
10
import {
11
    EmbedConfig,
12
    QueryParams,
13
    RuntimeFilter,
14
    CustomisationsInterface,
15
    DOMSelector,
16
    RuntimeParameter,
17
    AllEmbedViewConfig,
18
} from './types';
19
import { logger } from './utils/logger';
35✔
20

21
/**
22
 * Construct a runtime filters query string from the given filters.
23
 * Refer to the following docs for more details on runtime filter syntax:
24
 * https://cloud-docs.thoughtspot.com/admin/ts-cloud/apply-runtime-filter.html
25
 * https://cloud-docs.thoughtspot.com/admin/ts-cloud/runtime-filter-operators.html
26
 * @param runtimeFilters
27
 */
28
export const getFilterQuery = (runtimeFilters: RuntimeFilter[]): string | null => {
35✔
29
    if (runtimeFilters && runtimeFilters.length) {
422✔
30
        const filters = runtimeFilters.map((filter, valueIndex) => {
20✔
31
            const index = valueIndex + 1;
22✔
32
            const filterExpr = [];
22✔
33
            filterExpr.push(`col${index}=${encodeURIComponent(filter.columnName)}`);
22✔
34
            filterExpr.push(`op${index}=${filter.operator}`);
22✔
35
            filterExpr.push(
22✔
36
                filter.values.map((value) => {
37
                    const encodedValue = typeof value === 'bigint' ? value.toString() : value;
23!
38
                    return `val${index}=${encodeURIComponent(String(encodedValue))}`;
23✔
39
                }).join('&'),
40
            );
41

42
            return filterExpr.join('&');
22✔
43
        });
44

45
        return `${filters.join('&')}`;
20✔
46
    }
47

48
    return null;
402✔
49
};
50

51
/**
52
 * Construct a runtime parameter override query string from the given option.
53
 * @param runtimeParameters
54
 */
55
export const getRuntimeParameters = (runtimeParameters: RuntimeParameter[]): string => {
35✔
56
    if (runtimeParameters && runtimeParameters.length) {
421✔
57
        const params = runtimeParameters.map((param, valueIndex) => {
11✔
58
            const index = valueIndex + 1;
14✔
59
            const filterExpr = [];
14✔
60
            filterExpr.push(`param${index}=${encodeURIComponent(param.name)}`);
14✔
61
            filterExpr.push(`paramVal${index}=${encodeURIComponent(param.value)}`);
14✔
62

63
            return filterExpr.join('&');
14✔
64
        });
65

66
        return `${params.join('&')}`;
11✔
67
    }
68

69
    return null;
410✔
70
};
71

72
/**
73
 * Convert a value to a string representation to be sent as a query
74
 * parameter to the ThoughtSpot app.
75
 * @param value Any parameter value
76
 */
77
const serializeParam = (value: any) => {
35✔
78
    // do not serialize primitive types
79
    if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
15,601✔
80
        return value;
15,022✔
81
    }
82

83
    return JSON.stringify(value);
579✔
84
};
85

86
/**
87
 * Convert a value to a string:
88
 * in case of an array, we convert it to CSV.
89
 * in case of any other type, we directly return the value.
90
 * @param value
91
 */
92
const paramToString = (value: any) => (Array.isArray(value) ? value.join(',') : value);
35!
93

94
/**
95
 * Return a query param string composed from the given params object
96
 * @param queryParams
97
 * @param shouldSerializeParamValues
98
 */
99
export const getQueryParamString = (
35✔
100
    queryParams: QueryParams,
101
    shouldSerializeParamValues = false,
9✔
102
): string => {
103
    const qp: string[] = [];
576✔
104
    const params = Object.keys(queryParams);
576✔
105
    params.forEach((key) => {
576✔
106
        const val = queryParams[key];
16,198✔
107
        if (val !== undefined) {
16,198✔
108
            const serializedValue = shouldSerializeParamValues
15,618✔
109
                ? serializeParam(val)
110
                : paramToString(val);
111
            qp.push(`${key}=${serializedValue}`);
15,618✔
112
        }
113
    });
114

115
    if (qp.length) {
576✔
116
        return qp.join('&');
575✔
117
    }
118

119
    return null;
1✔
120
};
121

122
/**
123
 * Get a string representation of a dimension value in CSS
124
 * If numeric, it is considered in pixels.
125
 * @param value
126
 */
127
export const getCssDimension = (value: number | string): string => {
35✔
128
    if (typeof value === 'number') {
809✔
129
        return `${value}px`;
574✔
130
    }
131

132
    return value;
235✔
133
};
134

135
export const getSSOMarker = (markerId: string) => {
35✔
136
    const encStringToAppend = encodeURIComponent(markerId);
18✔
137
    return `tsSSOMarker=${encStringToAppend}`;
18✔
138
};
139

140
/**
141
 * Append a string to a URL's hash fragment
142
 * @param url A URL
143
 * @param stringToAppend The string to append to the URL hash
144
 */
145
export const appendToUrlHash = (url: string, stringToAppend: string) => {
35✔
146
    let outputUrl = url;
12✔
147
    const encStringToAppend = encodeURIComponent(stringToAppend);
12✔
148

149
    const marker = `tsSSOMarker=${encStringToAppend}`;
12✔
150

151
    let splitAdder = '';
12✔
152

153
    if (url.indexOf('#') >= 0) {
12✔
154
        // If second half of hash contains a '?' already add a '&' instead of
155
        // '?' which appends to query params.
156
        splitAdder = url.split('#')[1].indexOf('?') >= 0 ? '&' : '?';
8✔
157
    } else {
158
        splitAdder = '#?';
4✔
159
    }
160
    outputUrl = `${outputUrl}${splitAdder}${marker}`;
12✔
161

162
    return outputUrl;
12✔
163
};
164

165
/**
166
 *
167
 * @param url
168
 * @param stringToAppend
169
 * @param path
170
 */
171
export function getRedirectUrl(url: string, stringToAppend: string, path = '') {
35✔
172
    const targetUrl = path ? new URL(path, window.location.origin).href : url;
10✔
173
    return appendToUrlHash(targetUrl, stringToAppend);
10✔
174
}
175

176
export const getEncodedQueryParamsString = (queryString: string) => {
35✔
177
    if (!queryString) {
4✔
178
        return queryString;
1✔
179
    }
180
    return btoa(queryString).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
3✔
181
};
182

183
export const getOffsetTop = (element: any) => {
35✔
184
    const rect = element.getBoundingClientRect();
5✔
185
    return rect.top + window.scrollY;
5✔
186
};
187

188
export const embedEventStatus = {
35✔
189
    START: 'start',
190
    END: 'end',
191
};
192

193
export const setAttributes = (
35✔
194
    element: HTMLElement,
195
    attributes: { [key: string]: string | number | boolean },
196
): void => {
197
    Object.keys(attributes).forEach((key) => {
401✔
198
        element.setAttribute(key, attributes[key].toString());
21✔
199
    });
200
};
201

202
const isCloudRelease = (version: string) => version.endsWith('.cl');
35✔
203

204
/* For Search Embed: ReleaseVersionInBeta */
205
export const checkReleaseVersionInBeta = (
35✔
206
    releaseVersion: string,
207
    suppressBetaWarning: boolean,
208
): boolean => {
209
    if (releaseVersion !== '' && !isCloudRelease(releaseVersion)) {
110✔
210
        const splittedReleaseVersion = releaseVersion.split('.');
34✔
211
        const majorVersion = Number(splittedReleaseVersion[0]);
34✔
212
        const isBetaVersion = majorVersion < 8;
34✔
213
        return !suppressBetaWarning && isBetaVersion;
34✔
214
    }
215
    return false;
76✔
216
};
217

218
export const getCustomisations = (
35✔
219
    embedConfig: EmbedConfig,
220
    viewConfig: AllEmbedViewConfig,
221
): CustomisationsInterface => {
222
    const customizationsFromViewConfig = viewConfig.customizations;
20✔
223
    const customizationsFromEmbedConfig = embedConfig.customizations
20✔
224
        || ((embedConfig as any).customisations as CustomisationsInterface);
225

226
    const customizations: CustomisationsInterface = {
20✔
227
        style: {
228
            ...customizationsFromEmbedConfig?.style,
60✔
229
            ...customizationsFromViewConfig?.style,
60✔
230
            customCSS: {
231
                ...customizationsFromEmbedConfig?.style?.customCSS,
120✔
232
                ...customizationsFromViewConfig?.style?.customCSS,
120✔
233
            },
234
            customCSSUrl:
235
                customizationsFromViewConfig?.style?.customCSSUrl
160✔
236
                || customizationsFromEmbedConfig?.style?.customCSSUrl,
120✔
237
        },
238
        content: {
239
            ...customizationsFromEmbedConfig?.content,
60✔
240
            ...customizationsFromViewConfig?.content,
60✔
241
        },
242
    };
243
    return customizations;
20✔
244
};
245

246
export const getRuntimeFilters = (runtimefilters: any) => getFilterQuery(runtimefilters || []);
35!
247

248
/**
249
 * Gets a reference to the DOM node given
250
 * a selector.
251
 * @param domSelector
252
 */
253
export function getDOMNode(domSelector: DOMSelector): HTMLElement {
35✔
254
    return typeof domSelector === 'string' ? document.querySelector(domSelector) : domSelector;
467✔
255
}
256

257
export const deepMerge = (target: any, source: any) => merge(target, source);
35✔
258

259
export const getOperationNameFromQuery = (query: string) => {
35✔
260
    const regex = /(?:query|mutation)\s+(\w+)/;
88✔
261
    const matches = query.match(regex);
88✔
262
    return matches?.[1];
88!
263
};
264

265
/**
266
 *
267
 * @param obj
268
 */
269
export function removeTypename(obj: any) {
35✔
270
    if (!obj || typeof obj !== 'object') return obj;
47✔
271

272

273
    for (const key in obj) {
36✔
274
        if (key === '__typename') {
90✔
275
            delete obj[key];
2✔
276
        } else if (typeof obj[key] === 'object') {
88✔
277
            removeTypename(obj[key]);
18✔
278
        }
279
    }
280
    return obj;
36✔
281
}
282

283
/**
284
 * Sets the specified style properties on an HTML element.
285
 * @param {HTMLElement} element - The HTML element to which the styles should be applied.
286
 * @param {Partial<CSSStyleDeclaration>} styleProperties - An object containing style
287
 * property names and their values.
288
 * @example
289
 * // Apply styles to an element
290
 * const element = document.getElementById('myElement');
291
 * const styles = {
292
 *   backgroundColor: 'red',
293
 *   fontSize: '16px',
294
 * };
295
 * setStyleProperties(element, styles);
296
 */
297
export const setStyleProperties = (
35✔
298
    element: HTMLElement,
299
    styleProperties: Partial<CSSStyleDeclaration>,
300
): void => {
301
    if (!element?.style) return;
37✔
302
    Object.keys(styleProperties).forEach((styleProperty) => {
36✔
303
        const styleKey = styleProperty as keyof CSSStyleDeclaration;
124✔
304
        const value = styleProperties[styleKey];
124✔
305
        if (value !== undefined) {
124✔
306
            (element.style as any)[styleKey] = value.toString();
124✔
307
        }
308
    });
309
};
310
/**
311
 * Removes specified style properties from an HTML element.
312
 * @param {HTMLElement} element - The HTML element from which the styles should be removed.
313
 * @param {string[]} styleProperties - An array of style property names to be removed.
314
 * @example
315
 * // Remove styles from an element
316
 * const element = document.getElementById('myElement');
317
 * element.style.backgroundColor = 'red';
318
 * const propertiesToRemove = ['backgroundColor'];
319
 * removeStyleProperties(element, propertiesToRemove);
320
 */
321
export const removeStyleProperties = (element: HTMLElement, styleProperties: string[]): void => {
35✔
322
    if (!element?.style) return;
9✔
323
    styleProperties.forEach((styleProperty) => {
8✔
324
        element.style.removeProperty(styleProperty);
22✔
325
    });
326
};
327

328
export const isUndefined = (value: any): boolean => value === undefined;
309✔
329

330
// Return if the value is a string, double or boolean.
331
export const getTypeFromValue = (value: any): [string, string] => {
35✔
332
    if (typeof value === 'string') {
9✔
333
        return ['char', 'string'];
1✔
334
    }
335
    if (typeof value === 'number') {
8✔
336
        return ['double', 'double'];
2✔
337
    }
338
    if (typeof value === 'boolean') {
6✔
339
        return ['boolean', 'boolean'];
2✔
340
    }
341
    return ['', ''];
4✔
342
};
343

344
const sdkWindowKey = '_tsEmbedSDK' as any;
35✔
345

346
/**
347
 * Stores a value in the global `window` object under the `_tsEmbedSDK` namespace.
348
 * @param key - The key under which the value will be stored.
349
 * @param value - The value to store.
350
 * @param options - Additional options.
351
 * @param options.ignoreIfAlreadyExists - Does not set if value for key is set.
352
 *
353
 * @returns The stored value.
354
 *
355
 * @version SDK: 1.36.2 | ThoughtSpot: *
356
 */
357
export function storeValueInWindow<T>(
35✔
358
    key: string,
359
    value: T,
360
    options: { ignoreIfAlreadyExists?: boolean } = {},
471✔
361
): T {
362
    if (!window[sdkWindowKey]) {
363
        (window as any)[sdkWindowKey] = {};
497!
364
    }
×
365

366
    if (options.ignoreIfAlreadyExists && key in (window as any)[sdkWindowKey]) {
497✔
367
        return (window as any)[sdkWindowKey][key];
22✔
368
    }
369

370
    (window as any)[sdkWindowKey][key] = value;
497✔
371
    return value;
2✔
372
}
373

374
/**
495✔
375
 * Retrieves a stored value from the global `window` object under the `_tsEmbedSDK` namespace.
495✔
376
 * @param key - The key whose value needs to be retrieved.
377
 * @returns The stored value or `undefined` if the key is not found.
378
 */
379
export const getValueFromWindow = <T = any>
380
    (key: string): T => (window as any)?.[sdkWindowKey]?.[key];
381

382
/**
383
 * Check if an array includes a string value
35✔
384
 * @param arr - The array to check
385
 * @param key - The string to search for
3,284!
386
 * @returns boolean indicating if the string is found in the array
×
387
 */
388
export const arrayIncludesString = (arr: readonly unknown[], key: string): boolean => {
3,284!
389
    return arr.some(item => typeof item === 'string' && item === key);
390
};
391

392
/**
393
 * Resets the key if it exists in the `window` object under the `_tsEmbedSDK` key.
394
 * Returns true if the key was reset, false otherwise.
395
 * @param key - Key to reset
396
 * @returns - boolean indicating if the key was reset
35✔
397
 */
397✔
398
export function resetValueFromWindow(key: string): boolean {
399
    if (key in window[sdkWindowKey]) {
400
        delete (window as any)[sdkWindowKey][key];
401
        return true;
402
    }
403
    return false;
404
}
405

406
/**
35✔
407
 * Check if the document is currently in fullscreen mode
408
 */
6!
409
const isInFullscreen = (): boolean => {
×
410
    return !!(
411
        document.fullscreenElement ||
6✔
412
        (document as any).webkitFullscreenElement ||
5✔
413
        (document as any).mozFullScreenElement ||
5✔
414
        (document as any).msFullscreenElement
415
    );
1✔
416
};
417

418
/**
419
 * Handle Present HostEvent by entering fullscreen mode
420
 * @param iframe The iframe element to make fullscreen
421
 */
35✔
422
export const handlePresentEvent = async (iframe: HTMLIFrameElement): Promise<void> => {
6✔
423
    if (isInFullscreen()) {
15✔
424
        return; // Already in fullscreen
425
    }
426

427
    // Browser-specific methods to enter fullscreen mode
428
    const fullscreenMethods = [
429
        'requestFullscreen',      // Standard API
430
        'webkitRequestFullscreen', // WebKit browsers
431
        'mozRequestFullScreen',   // Firefox
432
        'msRequestFullscreen'     // IE/Edge
433
    ];
434

35✔
435
    for (const method of fullscreenMethods) {
3✔
436
        if (typeof (iframe as any)[method] === 'function') {
1✔
437
            try {
438
                const result = (iframe as any)[method]();
439
                await Promise.resolve(result);
440
                return;
2✔
441
            } catch (error) {
442
                logger.warn(`Failed to enter fullscreen using ${method}:`, error);
443
            }
444
        }
445
    }
446

447
    logger.error('Fullscreen API is not supported by this browser.');
2✔
448
};
5✔
449

1✔
450
/**
1✔
451
 * Handle ExitPresentMode EmbedEvent by exiting fullscreen mode
1✔
452
 */
1✔
453
export const handleExitPresentMode = async (): Promise<void> => {
454
    if (!isInFullscreen()) {
×
455
        return; // Not in fullscreen
456
    }
457

458
    const exitFullscreenMethods = [
459
        'exitFullscreen',        // Standard API
1✔
460
        'webkitExitFullscreen',  // WebKit browsers
461
        'mozCancelFullScreen',   // Firefox
462
        'msExitFullscreen'       // IE/Edge
463
    ];
464

465
    // Try each method until one works
35✔
466
    for (const method of exitFullscreenMethods) {
3✔
467
        if (typeof (document as any)[method] === 'function') {
1✔
468
            try {
469
                const result = (document as any)[method]();
470
                await Promise.resolve(result);
2✔
471
                return;
472
            } catch (error) {
473
                logger.warn(`Failed to exit fullscreen using ${method}:`, error);
474
            }
475
        }
476
    }
477

478
    logger.warn('Exit fullscreen API is not supported by this browser.');
2✔
479
};
5✔
480

1✔
481
export const calculateVisibleElementData = (element: HTMLElement) => {
1✔
482
    const rect = element.getBoundingClientRect();
1✔
483

1✔
484
    const windowHeight = window.innerHeight;
485
    const windowWidth = window.innerWidth;
×
486

487
    const frameRelativeTop = Math.max(rect.top, 0);
488
    const frameRelativeLeft = Math.max(rect.left, 0);
489

490
    const frameRelativeBottom = Math.min(windowHeight, rect.bottom);
1✔
491
    const frameRelativeRight = Math.min(windowWidth, rect.right);
492

493
    const data = {
35✔
494
        top: Math.max(0, rect.top * -1),
19✔
495
        height: Math.max(0, frameRelativeBottom - frameRelativeTop),
496
        left: Math.max(0, rect.left * -1),
19✔
497
        width: Math.max(0, frameRelativeRight - frameRelativeLeft),
19✔
498
    };
499

19✔
500
    return data;
19✔
501
}
502

19✔
503
/**
19✔
504
 * Replaces placeholders in a template string with provided values.
505
 * Placeholders should be in the format {key}.
19✔
506
 * @param template - The template string with placeholders
507
 * @param values - An object containing key-value pairs to replace placeholders
508
 * @returns The template string with placeholders replaced
509
 * @example
510
 * formatTemplate('Hello {name}, you are {age} years old', { name: 'John', age: 30 })
511
 * // Returns: 'Hello John, you are 30 years old'
512
 *
19✔
513
 * formatTemplate('Expected {type}, but received {actual}', { type: 'string', actual: 'number' })
514
 * // Returns: 'Expected string, but received number'
515
 */
516
export const formatTemplate = (template: string, values: Record<string, any>): string => {
517
    // This regex /\{(\w+)\}/g finds all placeholders in the format {word} 
518
    // and captures the word inside the braces for replacement.
519
    return template.replace(/\{(\w+)\}/g, (match, key) => {
520
        return values[key] !== undefined ? String(values[key]) : match;
521
    });
522
};
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