From 4b5aa80326bb36cc6e9bad9226d4897e94a70a1d Mon Sep 17 00:00:00 2001 From: Sai Kumar Battinoju Date: Mon, 18 Nov 2024 17:01:06 +0530 Subject: [PATCH] Revert "Revert "feat: add error handling to all public apis (#1907)"" This reverts commit ef1a977e13acbda5b84f6abbedd8c96be06cbb44. --- .github/workflows/deploy-npm.yml | 12 +- .github/workflows/deploy-sanity-suite.yml | 4 +- .github/workflows/deploy.yml | 4 +- .github/workflows/publish-new-release.yml | 4 +- CODEOWNERS | 18 +- .../__tests__/utilities/errors.test.ts | 18 + .../src/constants/loggerContexts.ts | 4 +- .../src/types/ApiObject.ts | 2 +- .../src/types/IRudderAnalytics.ts | 4 +- .../src/utilities/errors.ts | 11 +- .../src/utilities/eventMethodOverloads.ts | 201 +++-- .../__tests__/app/RudderAnalytics.test.ts | 783 ++++++++++++++---- .../analytics-js/src/app/RudderAnalytics.ts | 351 ++++---- .../analytics-js/src/constants/logMessages.ts | 4 - .../src/services/ErrorHandler/ErrorHandler.ts | 3 + 15 files changed, 993 insertions(+), 430 deletions(-) create mode 100644 packages/analytics-js-common/__tests__/utilities/errors.test.ts diff --git a/.github/workflows/deploy-npm.yml b/.github/workflows/deploy-npm.yml index 63dfa3e0f7..f73132e335 100644 --- a/.github/workflows/deploy-npm.yml +++ b/.github/workflows/deploy-npm.yml @@ -155,7 +155,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_VALUE }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_VALUE }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -171,7 +171,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_VALUE }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_VALUE }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", @@ -205,7 +205,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_SW_VALUE }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_SW_VALUE }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -221,7 +221,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_SW_VALUE }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_SW_VALUE }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", @@ -255,7 +255,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_COOKIE_UTILS_VALUE }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.NPM_PACKAGE_URL }}|${{ env.CURRENT_VERSION_COOKIE_UTILS_VALUE }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -271,7 +271,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_COOKIE_UTILS_VALUE }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.NPM_PACKAGE_URL }}|v${{ env.CURRENT_VERSION_COOKIE_UTILS_VALUE }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", diff --git a/.github/workflows/deploy-sanity-suite.yml b/.github/workflows/deploy-sanity-suite.yml index 1896ba1b5a..0c73ebfab6 100644 --- a/.github/workflows/deploy-sanity-suite.yml +++ b/.github/workflows/deploy-sanity-suite.yml @@ -154,7 +154,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Deployment: ${{ env.PROJECT_NAME }} - <${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Deployment: ${{ env.PROJECT_NAME }} - <${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -170,7 +170,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 8dc1906721..bfdc3b1b4f 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -233,7 +233,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -249,7 +249,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.CDN_URL }}|${{ env.LINK_TEXT }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", diff --git a/.github/workflows/publish-new-release.yml b/.github/workflows/publish-new-release.yml index c03c086fb8..836fe8d05b 100644 --- a/.github/workflows/publish-new-release.yml +++ b/.github/workflows/publish-new-release.yml @@ -117,7 +117,7 @@ jobs: channel-id: ${{ secrets.SLACK_RELEASE_CHANNEL_ID }} payload: | { - "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.TAG_COMPARE_URL }}${{ env.last_monorepo_version }}...v${{ steps.extract-version.outputs.release_version }}|v${{ steps.extract-version.outputs.release_version }}>*\n${{ env.DATE }}\nCC: ", + "text": "*New Release: ${{ env.PROJECT_NAME }} - <${{ env.TAG_COMPARE_URL }}${{ env.last_monorepo_version }}...v${{ steps.extract-version.outputs.release_version }}|v${{ steps.extract-version.outputs.release_version }}>*\n${{ env.DATE }}\nCC: ", "blocks": [ { "type": "header", @@ -133,7 +133,7 @@ jobs: "type": "section", "text": { "type": "mrkdwn", - "text": "*<${{ env.TAG_COMPARE_URL }}${{ env.last_monorepo_version }}...v${{ steps.extract-version.outputs.release_version }}|v${{ steps.extract-version.outputs.release_version }}>*\n${{ env.DATE }}\nCC: " + "text": "*<${{ env.TAG_COMPARE_URL }}${{ env.last_monorepo_version }}...v${{ steps.extract-version.outputs.release_version }}|v${{ steps.extract-version.outputs.release_version }}>*\n${{ env.DATE }}\nCC: " }, "accessory": { "type": "image", diff --git a/CODEOWNERS b/CODEOWNERS index ba26277d24..ec64eff795 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1,12 +1,12 @@ * @rudderlabs/js-sdk -/packages/analytics-js-integrations/src/ @rudderlabs/js-sdk-dm-intg-eng -/packages/analytics-js-integrations/__fixtures__/ @rudderlabs/js-sdk-dm-intg-eng -/packages/analytics-js-integrations/__tests__/ @rudderlabs/js-sdk-dm-intg-eng -/packages/analytics-js-integrations/__mocks__/ @rudderlabs/js-sdk-dm-intg-eng -/packages/analytics-js-integrations/README.md @rudderlabs/js-sdk-dm-intg-eng -/packages/analytics-js-integrations/.size-limit.js @rudderlabs/js-sdk-dm-intg-eng +/packages/analytics-js-integrations/src/ @rudderlabs/integrations +/packages/analytics-js-integrations/__fixtures__/ @rudderlabs/integrations +/packages/analytics-js-integrations/__tests__/ @rudderlabs/integrations +/packages/analytics-js-integrations/__mocks__/ @rudderlabs/integrations +/packages/analytics-js-integrations/README.md @rudderlabs/integrations +/packages/analytics-js-integrations/.size-limit.js @rudderlabs/integrations -/packages/analytics-js-common/src/constants/integrations/ @rudderlabs/js-sdk-dm-intg-eng -/assets/integrations/AdobeAnalytics/ @rudderlabs/js-sdk-dm-intg-eng -/examples/integrations/ @rudderlabs/js-sdk-dm-intg-eng +/packages/analytics-js-common/src/constants/integrations/ @rudderlabs/integrations +/assets/integrations/AdobeAnalytics/ @rudderlabs/integrations +/examples/integrations/ @rudderlabs/integrations diff --git a/packages/analytics-js-common/__tests__/utilities/errors.test.ts b/packages/analytics-js-common/__tests__/utilities/errors.test.ts new file mode 100644 index 0000000000..d1dab56190 --- /dev/null +++ b/packages/analytics-js-common/__tests__/utilities/errors.test.ts @@ -0,0 +1,18 @@ +import { dispatchErrorEvent } from '../../src/utilities/errors'; + +describe('Errors - utilities', () => { + describe('dispatchErrorEvent', () => { + it('should dispatch an error event', () => { + const dispatchEvent = jest.fn(); + const originalDispatchEvent = globalThis.dispatchEvent; + + globalThis.dispatchEvent = dispatchEvent; + const error = new Error('Test error'); + dispatchErrorEvent(error); + expect(dispatchEvent).toHaveBeenCalledWith(new ErrorEvent('error', { error })); + + // Cleanup + globalThis.dispatchEvent = originalDispatchEvent; + }); + }); +}); diff --git a/packages/analytics-js-common/src/constants/loggerContexts.ts b/packages/analytics-js-common/src/constants/loggerContexts.ts index 2aa4f7f858..65583c9774 100644 --- a/packages/analytics-js-common/src/constants/loggerContexts.ts +++ b/packages/analytics-js-common/src/constants/loggerContexts.ts @@ -11,7 +11,7 @@ const LOAD_CONFIGURATION = 'LoadConfiguration'; const EVENT_REPOSITORY = 'EventRepository'; const EXTERNAL_SRC_LOADER = 'ExternalSrcLoader'; const HTTP_CLIENT = 'HttpClient'; -const RS_APP = 'RudderStackApplication'; +const RSA = 'RudderStackAnalytics'; const ANALYTICS_CORE = 'AnalyticsCore'; export { @@ -28,6 +28,6 @@ export { EVENT_REPOSITORY, EXTERNAL_SRC_LOADER, HTTP_CLIENT, - RS_APP, + RSA, ANALYTICS_CORE, }; diff --git a/packages/analytics-js-common/src/types/ApiObject.ts b/packages/analytics-js-common/src/types/ApiObject.ts index 1265ec70d6..a72a68bacf 100644 --- a/packages/analytics-js-common/src/types/ApiObject.ts +++ b/packages/analytics-js-common/src/types/ApiObject.ts @@ -10,6 +10,6 @@ export type ApiObject = { | ApiObject | null | Date - | (string | number | boolean | null | Date | ApiObject)[] + | (string | number | boolean | null | Date | ApiObject | undefined)[] | undefined; }; diff --git a/packages/analytics-js-common/src/types/IRudderAnalytics.ts b/packages/analytics-js-common/src/types/IRudderAnalytics.ts index c9dcdbdfbc..3663b78c54 100644 --- a/packages/analytics-js-common/src/types/IRudderAnalytics.ts +++ b/packages/analytics-js-common/src/types/IRudderAnalytics.ts @@ -85,7 +85,7 @@ export interface IRudderAnalytics { /** * Get the instance of Analytics that is set as default */ - getAnalyticsInstance(writeKey?: string): T; + getAnalyticsInstance(writeKey?: string): T | undefined; /** * Trigger load event in buffer queue if exists @@ -188,7 +188,7 @@ export interface IRudderAnalytics { /** * To fetch the current sessionId */ - getSessionId(): Nullable; + getSessionId(): Nullable | undefined; /** * To provide consent diff --git a/packages/analytics-js-common/src/utilities/errors.ts b/packages/analytics-js-common/src/utilities/errors.ts index 59bf78b1ca..29768eb791 100644 --- a/packages/analytics-js-common/src/utilities/errors.ts +++ b/packages/analytics-js-common/src/utilities/errors.ts @@ -1,6 +1,8 @@ import { isTypeOfError } from './checks'; import { stringifyData } from './json'; +const MANUAL_ERROR_IDENTIFIER = '[MANUAL ERROR]'; + /** * Get mutated error with issue prepended to error message * @param err Original error @@ -17,4 +19,11 @@ const getMutatedError = (err: any, issue: string): Error => { return finalError; }; -export { getMutatedError }; +const dispatchErrorEvent = (error: any) => { + if (isTypeOfError(error)) { + error.stack = `${error.stack ?? ''}\n${MANUAL_ERROR_IDENTIFIER}`; + } + (globalThis as typeof window).dispatchEvent(new ErrorEvent('error', { error })); +}; + +export { getMutatedError, dispatchErrorEvent, MANUAL_ERROR_IDENTIFIER }; diff --git a/packages/analytics-js-common/src/utilities/eventMethodOverloads.ts b/packages/analytics-js-common/src/utilities/eventMethodOverloads.ts index 4a7f063819..f92b823ca9 100644 --- a/packages/analytics-js-common/src/utilities/eventMethodOverloads.ts +++ b/packages/analytics-js-common/src/utilities/eventMethodOverloads.ts @@ -6,6 +6,7 @@ import { isObjectLiteralAndNotNull, mergeDeepRight } from './object'; import { isDefined, isDefinedAndNotNull, isFunction, isNull, isString } from './checks'; import { tryStringify } from './string'; import type { IdentifyTraits } from '../types/traits'; +import { getSanitizedValue } from './json'; export type PageCallOptions = { category?: string; @@ -56,64 +57,70 @@ const pageArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): PageCallOptions => { + const sanitizedCategory = getSanitizedValue(category); + const sanitizedName = getSanitizedValue(name); + const sanitizedProperties = getSanitizedValue(properties); + const sanitizedOptions = getSanitizedValue(options); + const sanitizedCallback = getSanitizedValue(callback); + const payload: PageCallOptions = { - category: category as string, - name: name as string, - properties: properties as Nullable, - options: options as Nullable, + category: sanitizedCategory as string, + name: sanitizedName as string, + properties: sanitizedProperties as Nullable, + options: sanitizedOptions as Nullable, callback: undefined, }; - if (isFunction(callback)) { - payload.callback = callback; + if (isFunction(sanitizedCallback)) { + payload.callback = sanitizedCallback; } - if (isFunction(options)) { - payload.category = category as string; - payload.name = name as string; - payload.properties = properties as Nullable; + if (isFunction(sanitizedOptions)) { + payload.category = sanitizedCategory as string; + payload.name = sanitizedName as string; + payload.properties = sanitizedProperties as Nullable; payload.options = undefined; - payload.callback = options; + payload.callback = sanitizedOptions; } - if (isFunction(properties)) { - payload.category = category as string; - payload.name = name as string; + if (isFunction(sanitizedProperties)) { + payload.category = sanitizedCategory as string; + payload.name = sanitizedName as string; payload.properties = undefined; payload.options = undefined; - payload.callback = properties; + payload.callback = sanitizedProperties; } - if (isFunction(name)) { - payload.category = category as string; + if (isFunction(sanitizedName)) { + payload.category = sanitizedCategory as string; payload.name = undefined; payload.properties = undefined; payload.options = undefined; - payload.callback = name; + payload.callback = sanitizedName; } - if (isFunction(category)) { + if (isFunction(sanitizedCategory)) { payload.category = undefined; payload.name = undefined; payload.properties = undefined; payload.options = undefined; - payload.callback = category; + payload.callback = sanitizedCategory; } - if (isObjectLiteralAndNotNull(category)) { + if (isObjectLiteralAndNotNull(sanitizedCategory)) { payload.name = undefined; payload.category = undefined; - payload.properties = category as Nullable; - if (!isFunction(name)) { - payload.options = name as Nullable; + payload.properties = sanitizedCategory as Nullable; + if (!isFunction(sanitizedName)) { + payload.options = sanitizedName as Nullable; } else { payload.options = undefined; } - } else if (isObjectLiteralAndNotNull(name)) { + } else if (isObjectLiteralAndNotNull(sanitizedName)) { payload.name = undefined; - payload.properties = name as Nullable; - if (!isFunction(properties)) { - payload.options = properties as Nullable; + payload.properties = sanitizedName as Nullable; + if (!isFunction(sanitizedProperties)) { + payload.options = sanitizedProperties as Nullable; } else { payload.options = undefined; } @@ -121,9 +128,9 @@ const pageArgumentsToCallOptions = ( // if the category argument alone is provided b/w category and name, // use it as name and set category to undefined - if (isString(category) && !isString(name)) { + if (isString(sanitizedCategory) && !isString(sanitizedName)) { payload.category = undefined; - payload.name = category; + payload.name = sanitizedCategory; } // Rest of the code is just to clean up undefined values @@ -171,27 +178,32 @@ const trackArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): TrackCallOptions => { + const sanitizedEvent = getSanitizedValue(event); + const sanitizedProperties = getSanitizedValue(properties); + const sanitizedOptions = getSanitizedValue(options); + const sanitizedCallback = getSanitizedValue(callback); + const payload: TrackCallOptions = { - name: event, - properties: properties as Nullable, - options: options as Nullable, + name: sanitizedEvent, + properties: sanitizedProperties as Nullable, + options: sanitizedOptions as Nullable, callback: undefined, }; - if (isFunction(callback)) { - payload.callback = callback; + if (isFunction(sanitizedCallback)) { + payload.callback = sanitizedCallback; } - if (isFunction(options)) { - payload.properties = properties as Nullable; + if (isFunction(sanitizedOptions)) { + payload.properties = sanitizedProperties as Nullable; payload.options = undefined; - payload.callback = options; + payload.callback = sanitizedOptions; } - if (isFunction(properties)) { + if (isFunction(sanitizedProperties)) { payload.properties = undefined; payload.options = undefined; - payload.callback = properties; + payload.callback = sanitizedProperties; } // Rest of the code is just to clean up undefined values @@ -217,38 +229,43 @@ const identifyArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): IdentifyCallOptions => { + const sanitizedUserId = getSanitizedValue(userId); + const sanitizedTraits = getSanitizedValue(traits); + const sanitizedOptions = getSanitizedValue(options); + const sanitizedCallback = getSanitizedValue(callback); + const payload: IdentifyCallOptions = { - userId: userId as string, - traits: traits as Nullable, - options: options as Nullable, + userId: sanitizedUserId as string, + traits: sanitizedTraits as Nullable, + options: sanitizedOptions as Nullable, callback: undefined, }; - if (isFunction(callback)) { - payload.callback = callback; + if (isFunction(sanitizedCallback)) { + payload.callback = sanitizedCallback; } - if (isFunction(options)) { - payload.userId = userId as string; - payload.traits = traits as Nullable; + if (isFunction(sanitizedOptions)) { + payload.userId = sanitizedUserId as string; + payload.traits = sanitizedTraits as Nullable; payload.options = undefined; - payload.callback = options; + payload.callback = sanitizedOptions; } - if (isFunction(traits)) { - payload.userId = userId as string; + if (isFunction(sanitizedTraits)) { + payload.userId = sanitizedUserId as string; payload.traits = undefined; payload.options = undefined; - payload.callback = traits; + payload.callback = sanitizedTraits; } - if (isObjectLiteralAndNotNull(userId) || isNull(userId)) { + if (isObjectLiteralAndNotNull(sanitizedUserId) || isNull(sanitizedUserId)) { // Explicitly set null to prevent resetting the existing value // in the Analytics class payload.userId = null; - payload.traits = userId as Nullable; - if (!isFunction(traits)) { - payload.options = traits as Nullable; + payload.traits = sanitizedUserId as Nullable; + if (!isFunction(sanitizedTraits)) { + payload.options = sanitizedTraits as Nullable; } else { payload.options = undefined; } @@ -283,33 +300,38 @@ const aliasArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): AliasCallOptions => { + const sanitizedTo = getSanitizedValue(to); + const sanitizedFrom = getSanitizedValue(from); + const sanitizedOptions = getSanitizedValue(options); + const sanitizedCallback = getSanitizedValue(callback); + const payload: AliasCallOptions = { - to, - from: from as string, - options: options as Nullable, + to: sanitizedTo, + from: sanitizedFrom as string, + options: sanitizedOptions as Nullable, callback: undefined, }; - if (isFunction(callback)) { - payload.callback = callback; + if (isFunction(sanitizedCallback)) { + payload.callback = sanitizedCallback; } - if (isFunction(options)) { - payload.to = to; - payload.from = from as string; + if (isFunction(sanitizedOptions)) { + payload.to = sanitizedTo; + payload.from = sanitizedFrom as string; payload.options = undefined; - payload.callback = options; + payload.callback = sanitizedOptions; } - if (isFunction(from)) { - payload.to = to; + if (isFunction(sanitizedFrom)) { + payload.to = sanitizedTo; payload.from = undefined; payload.options = undefined; - payload.callback = from; - } else if (isObjectLiteralAndNotNull(from) || isNull(from)) { - payload.to = to; + payload.callback = sanitizedFrom; + } else if (isObjectLiteralAndNotNull(sanitizedFrom) || isNull(sanitizedFrom)) { + payload.to = sanitizedTo; payload.from = undefined; - payload.options = from as Nullable; + payload.options = sanitizedFrom as Nullable; } // Rest of the code is just to clean up undefined values @@ -343,38 +365,43 @@ const groupArgumentsToCallOptions = ( options?: Nullable | ApiCallback, callback?: ApiCallback, ): GroupCallOptions => { + const sanitizedGroupId = getSanitizedValue(groupId); + const sanitizedTraits = getSanitizedValue(traits); + const sanitizedOptions = getSanitizedValue(options); + const sanitizedCallback = getSanitizedValue(callback); + const payload: GroupCallOptions = { - groupId: groupId as string, - traits: traits as Nullable, - options: options as Nullable, + groupId: sanitizedGroupId as string, + traits: sanitizedTraits as Nullable, + options: sanitizedOptions as Nullable, callback: undefined, }; - if (isFunction(callback)) { - payload.callback = callback; + if (isFunction(sanitizedCallback)) { + payload.callback = sanitizedCallback; } - if (isFunction(options)) { - payload.groupId = groupId as string; - payload.traits = traits as Nullable; + if (isFunction(sanitizedOptions)) { + payload.groupId = sanitizedGroupId as string; + payload.traits = sanitizedTraits as Nullable; payload.options = undefined; - payload.callback = options; + payload.callback = sanitizedOptions; } - if (isFunction(traits)) { - payload.groupId = groupId as string; + if (isFunction(sanitizedTraits)) { + payload.groupId = sanitizedGroupId as string; payload.traits = undefined; payload.options = undefined; - payload.callback = traits; + payload.callback = sanitizedTraits; } - if (isObjectLiteralAndNotNull(groupId) || isNull(groupId)) { + if (isObjectLiteralAndNotNull(sanitizedGroupId) || isNull(sanitizedGroupId)) { // Explicitly set null to prevent resetting the existing value // in the Analytics class payload.groupId = null; - payload.traits = groupId as Nullable; - if (!isFunction(traits)) { - payload.options = traits as Nullable; + payload.traits = sanitizedGroupId as Nullable; + if (!isFunction(sanitizedTraits)) { + payload.options = sanitizedTraits as Nullable; } else { payload.options = undefined; } diff --git a/packages/analytics-js/__tests__/app/RudderAnalytics.test.ts b/packages/analytics-js/__tests__/app/RudderAnalytics.test.ts index 85afcbd90b..690c96114b 100644 --- a/packages/analytics-js/__tests__/app/RudderAnalytics.test.ts +++ b/packages/analytics-js/__tests__/app/RudderAnalytics.test.ts @@ -16,7 +16,6 @@ describe('Core - Rudder Analytics Facade', () => { } as LoadOptions; beforeEach(() => { - Analytics.mockClear(); analyticsInstanceMock = new Analytics() as jest.Mocked; (window as any).rudderanalytics = [ ['track'], @@ -31,11 +30,10 @@ describe('Core - Rudder Analytics Facade', () => { }); afterEach(() => { - (rudderAnalytics as any).globalSingleton = null; jest.resetAllMocks(); }); - it('should return the global singleton from "rudderanalytics" global object', done => { + it('should return the global singleton from "rudderanalytics" global object', () => { const expectedPreloadedEvents = [ ['consent', { sendPageEvent: true }], ['consent', { sendPageEvent: false }], @@ -46,7 +44,6 @@ describe('Core - Rudder Analytics Facade', () => { expect(window.RudderStackGlobals?.app?.preloadedEventsBuffer).toEqual(expectedPreloadedEvents); expect(window.rudderanalytics).toEqual(globalSingleton); - done(); }); it('should retrieve all preloaded events and set to global', () => { @@ -58,6 +55,27 @@ describe('Core - Rudder Analytics Facade', () => { ]); }); + it('should return an empty array when globalThis.rudderanalytics is not an array', () => { + const rudderAnalyticsInstance = new RudderAnalytics(); + (globalThis as typeof window).rudderanalytics = undefined; + const result = rudderAnalyticsInstance.getPreloadedEvents(); + expect(result).toEqual([]); + }); + + it('should return buffered events array when globalThis.rudderanalytics is an array', () => { + const bufferedEvents = [ + ['track'], + ['consent', { sendPageEvent: true }], + ['load', 'dummyWriteKey', 'dummyDataPlaneUrl', { option1: true }], + ['consent', { sendPageEvent: false }], + ['track'], + ]; + (window as any).rudderanalytics = bufferedEvents; + const rudderAnalyticsInstance = new RudderAnalytics(); + const result = rudderAnalyticsInstance.getPreloadedEvents(); + expect(result).toEqual(bufferedEvents); + }); + it('should return the global singleton if it exists', () => { const globalSingleton = rudderAnalytics; rudderAnalytics = new RudderAnalytics(); @@ -65,20 +83,54 @@ describe('Core - Rudder Analytics Facade', () => { expect(rudderAnalytics).toEqual(globalSingleton); }); + it('should dispatch an error event if an exception is thrown during the construction', () => { + const originalSingleton = RudderAnalytics.globalSingleton; + + RudderAnalytics.globalSingleton = null; + + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Explicitly throw an error during the construction + const nowSpy = jest.spyOn(Date, 'now').mockImplementation(() => { + throw new Error('Error in now function'); + }); + + // eslint-disable-next-line sonarjs/constructor-for-side-effects, no-new + new RudderAnalytics(); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in now function'), + }), + ); + + RudderAnalytics.globalSingleton = originalSingleton; + nowSpy.mockRestore(); + + dispatchEventSpy.mockRestore(); + }); + it('should auto set the default analytics key if no analytics instances exist', () => { (rudderAnalytics as any).analyticsInstances = {}; (rudderAnalytics as any).defaultAnalyticsKey = ''; + rudderAnalytics.setDefaultInstanceKey('writeKey'); expect(rudderAnalytics.defaultAnalyticsKey).toEqual('writeKey'); }); - it('should auto set the default analytics key if analytics instances exist', () => { + it('should set the default analytics key even if analytics instances exist', () => { rudderAnalytics.setDefaultInstanceKey('writeKey2'); expect(rudderAnalytics.defaultAnalyticsKey).toEqual('writeKey2'); }); + it('should not set default analytics key if the key is not a valid string', () => { + rudderAnalytics.setDefaultInstanceKey(''); + + expect(rudderAnalytics.defaultAnalyticsKey).toEqual('writeKey'); + }); + it('should return an existing analytics instance', () => { expect(rudderAnalytics.getAnalyticsInstance('writeKey')).toStrictEqual(analyticsInstanceMock); }); @@ -106,6 +158,25 @@ describe('Core - Rudder Analytics Facade', () => { expect(rudderAnalytics.getAnalyticsInstance('writeKey')).toStrictEqual(analyticsInstance); }); + it('should return undefined and log error if an exception is thrown while getting the analytics instance', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally set the parameter to undefined to trigger an error + (rudderAnalytics as any).analyticsInstances = undefined; + + const result = rudderAnalytics.getAnalyticsInstance('writeKey2'); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new TypeError("Cannot read properties of undefined (reading 'writeKey2')"), + }), + ); + + expect(result).toBeUndefined(); + + dispatchEventSpy.mockRestore(); + }); + it('should set the default analytics key if none has been set', () => { rudderAnalytics.load('writeKey', 'data-plane-url'); @@ -116,169 +187,390 @@ describe('Core - Rudder Analytics Facade', () => { rudderAnalytics.analyticsInstances = {}; rudderAnalytics.defaultAnalyticsKey = ''; rudderAnalytics.load('writeKey', 'data-plane-url', mockLoadOptions); - const analyticsInstance = rudderAnalytics.getAnalyticsInstance('writeKey'); + const analyticsInstance = rudderAnalytics.getAnalyticsInstance('writeKey') as Analytics; const loadSpy = jest.spyOn(analyticsInstance, 'load'); expect(rudderAnalytics.analyticsInstances).toHaveProperty('writeKey', analyticsInstance); expect(loadSpy).toHaveBeenCalledWith('writeKey', 'data-plane-url', mockLoadOptions); }); + it('should dispatch an error event if an exception is thrown during the load', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally set the parameter to undefined to trigger an error + (rudderAnalytics as any).analyticsInstances = undefined; + + rudderAnalytics.defaultAnalyticsKey = ''; + rudderAnalytics.load('writeKey', 'data-plane-url', mockLoadOptions); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new TypeError("Cannot read properties of undefined (reading 'writeKey')"), + }), + ); + + dispatchEventSpy.mockRestore(); + }); + it('should process ready arguments and forwards to ready call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const readySpy = jest.spyOn(analyticsInstance, 'ready'); + const callback = () => console.log('Ready!'); + + rudderAnalytics.ready(callback); + expect(analyticsInstanceMock.ready).toHaveBeenCalledWith(expect.any(Function)); + }); + + it('should dispatch an error event if an exception is thrown during the ready call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the ready call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); const callback = () => console.log('Ready!'); rudderAnalytics.ready(callback); - expect(readySpy).toHaveBeenCalledWith(expect.any(Function)); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + getAnalyticsInstanceSpy.mockRestore(); }); it('should process page arguments and forwards to page call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const pageSpy = jest.spyOn(analyticsInstance, 'page'); - rudderAnalytics.page('category'); - expect(pageSpy).toHaveBeenCalledWith({ + expect(analyticsInstanceMock.page).toHaveBeenCalledWith({ name: 'category', properties: { name: 'category' }, }); }); + it('should dispatch an error event if an exception is thrown during the page call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the page call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + rudderAnalytics.page('category'); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); + }); + it('should process track arguments and forwards to track call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const trackSpy = jest.spyOn(analyticsInstance, 'track'); + rudderAnalytics.track('event'); + expect(analyticsInstanceMock.track).toHaveBeenCalledWith({ name: 'event', properties: {} }); + }); + + it('should dispatch an error event if an exception is thrown during the track call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the track call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); rudderAnalytics.track('event'); - expect(trackSpy).toHaveBeenCalledWith({ name: 'event', properties: {} }); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); it('should process identify arguments and forwards to identify call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const identifySpy = jest.spyOn(analyticsInstance, 'identify'); + rudderAnalytics.identify('1234'); + expect(analyticsInstanceMock.identify).toHaveBeenCalledWith({ userId: '1234' }); + }); + + it('should dispatch an error event if an exception is thrown during the identify call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the identify call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); - rudderAnalytics.identify(1234); - expect(identifySpy).toHaveBeenCalledWith({ userId: '1234' }); + rudderAnalytics.identify('1234'); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); it('should process alias arguments and forwards to alias call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const aliasSpy = jest.spyOn(analyticsInstance, 'alias'); + rudderAnalytics.alias('abc'); + expect(analyticsInstanceMock.alias).toHaveBeenCalledWith({ to: 'abc' }); + }); + + it('should dispatch an error event if an exception is thrown during the alias call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the alias call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + rudderAnalytics.alias('abc'); - rudderAnalytics.alias('1234'); - expect(aliasSpy).toHaveBeenCalledWith({ to: '1234' }); + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); it('should process group arguments and forwards to group call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const groupSpy = jest.spyOn(analyticsInstance, 'group'); + rudderAnalytics.group('5678'); + expect(analyticsInstanceMock.group).toHaveBeenCalledWith({ groupId: '5678' }); + }); + + it('should dispatch an error event if an exception is thrown during the group call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the group call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + rudderAnalytics.group('5678'); - rudderAnalytics.group(1234); - expect(groupSpy).toHaveBeenCalledWith({ groupId: '1234' }); + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); it('should process reset arguments and forwards to reset call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const resetSpy = jest.spyOn(analyticsInstance, 'reset'); + rudderAnalytics.reset(true); + expect(analyticsInstanceMock.reset).toHaveBeenCalledWith(true); + }); + + it('should dispatch an error event if an exception is thrown during the reset call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the reset call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); rudderAnalytics.reset(true); - expect(resetSpy).toHaveBeenCalledWith(true); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); it('should process getAnonymousId arguments and forwards to getAnonymousId call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const getAnonymousIdSpy = jest.spyOn(analyticsInstance, 'getAnonymousId'); - rudderAnalytics.getAnonymousId({ autoCapture: { enabled: true, }, }); - expect(getAnonymousIdSpy).toHaveBeenCalledWith({ autoCapture: { enabled: true } }); + expect(analyticsInstanceMock.getAnonymousId).toHaveBeenCalledWith({ + autoCapture: { enabled: true }, + }); }); - it('should process setAnonymousId arguments and forwards to setAnonymousId call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const setAnonymousIdSpy = jest.spyOn(analyticsInstance, 'setAnonymousId'); + it('should return undefined and log an error if an exception is thrown during the getAnonymousId call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the getAnonymousId call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + const result = rudderAnalytics.getAnonymousId(); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + expect(result).toBeUndefined(); + + getAnalyticsInstanceSpy.mockRestore(); + }); + + it('should process setAnonymousId arguments and forwards to setAnonymousId call', () => { rudderAnalytics.setAnonymousId('id', 'param'); - expect(setAnonymousIdSpy).toHaveBeenCalledWith('id', 'param'); + expect(analyticsInstanceMock.setAnonymousId).toHaveBeenCalledWith('id', 'param'); }); - it('should process getUserId arguments and forwards to getUserId call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const getUserIdSpy = jest.spyOn(analyticsInstance, 'getUserId'); + it('should dispatch an error event if an exception is thrown during the setAnonymousId call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + // Intentionally cause an error during the setAnonymousId call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + rudderAnalytics.setAnonymousId('id'); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); + }); + + it('should process getUserId arguments and forwards to getUserId call', () => { rudderAnalytics.getUserId(); - expect(getUserIdSpy).toHaveBeenCalledTimes(1); + expect(analyticsInstanceMock.getUserId).toHaveBeenCalledTimes(1); }); it('should process getUserTraits arguments and forwards to getUserTraits call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const getUserTraitsSpy = jest.spyOn(analyticsInstance, 'getUserTraits'); - rudderAnalytics.getUserTraits(); - expect(getUserTraitsSpy).toHaveBeenCalledTimes(1); + expect(analyticsInstanceMock.getUserTraits).toHaveBeenCalledTimes(1); }); it('should process getGroupId arguments and forwards to getGroupId call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const getGroupIdSpy = jest.spyOn(analyticsInstance, 'getGroupId'); - rudderAnalytics.getGroupId(); - expect(getGroupIdSpy).toHaveBeenCalledTimes(1); + expect(analyticsInstanceMock.getGroupId).toHaveBeenCalledTimes(1); }); it('should process getGroupTraits arguments and forwards to getGroupTraits call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const getGroupTraitsSpy = jest.spyOn(analyticsInstance, 'getGroupTraits'); - rudderAnalytics.getGroupTraits(); - expect(getGroupTraitsSpy).toHaveBeenCalledTimes(1); + expect(analyticsInstanceMock.getGroupTraits).toHaveBeenCalledTimes(1); }); it('should process startSession arguments and forwards to startSession call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const startSessionSpy = jest.spyOn(analyticsInstance, 'startSession'); + rudderAnalytics.startSession(1234); + expect(analyticsInstanceMock.startSession).toHaveBeenCalledWith(1234); + }); + + it('should dispatch an error event if an exception is thrown during the startSession call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the startSession call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); rudderAnalytics.startSession(1234); - expect(startSessionSpy).toHaveBeenCalledWith(1234); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); it('should process endSession arguments and forwards to endSession call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const endSessionSpy = jest.spyOn(analyticsInstance, 'endSession'); - rudderAnalytics.endSession(); - expect(endSessionSpy).toHaveBeenCalledTimes(1); + expect(analyticsInstanceMock.endSession).toHaveBeenCalledTimes(1); }); it('should process getSessionId arguments and forwards to getSessionId call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const getSessionIdSpy = jest.spyOn(analyticsInstance, 'getSessionId'); - rudderAnalytics.getSessionId(); - expect(getSessionIdSpy).toHaveBeenCalledTimes(1); + expect(analyticsInstanceMock.getSessionId).toHaveBeenCalledTimes(1); }); it('should process setAuthToken arguments and forwards to setAuthToken call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const setAuthTokenSpy = jest.spyOn(analyticsInstance, 'setAuthToken'); + rudderAnalytics.setAuthToken('token'); + expect(analyticsInstanceMock.setAuthToken).toHaveBeenCalledWith('token'); + }); + + it('should dispatch an error event if an exception is thrown during the setAuthToken call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the setAuthToken call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); rudderAnalytics.setAuthToken('token'); - expect(setAuthTokenSpy).toHaveBeenCalledWith('token'); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); it('should process consent arguments and forwards to consent call', () => { - const analyticsInstance = rudderAnalytics.getAnalyticsInstance(); - const consentSpy = jest.spyOn(analyticsInstance, 'consent'); - rudderAnalytics.consent({ consentManagement: { allowedConsentIds: ['1'], deniedConsentIds: ['2'], }, }); - expect(consentSpy).toHaveBeenCalledWith({ + expect(analyticsInstanceMock.consent).toHaveBeenCalledWith({ consentManagement: { allowedConsentIds: ['1'], deniedConsentIds: ['2'], @@ -286,128 +578,283 @@ describe('Core - Rudder Analytics Facade', () => { }); }); - it('should return an empty array when globalThis.rudderanalytics is not an array', () => { - const rudderAnalyticsInstance = new RudderAnalytics(); - (globalThis as typeof window).rudderanalytics = undefined; - const result = rudderAnalyticsInstance.getPreloadedEvents(); - expect(result).toEqual([]); + it('should dispatch an error event if an exception is thrown during the consent call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the consent call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + rudderAnalytics.consent({ + consentManagement: { + allowedConsentIds: ['1'], + deniedConsentIds: ['2'], + }, + }); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); - it('should return buffered events array when globalThis.rudderanalytics is an array', () => { - const bufferedEvents = [ - ['track'], - ['consent', { sendPageEvent: true }], - ['load', 'dummyWriteKey', 'dummyDataPlaneUrl', { option1: true }], - ['consent', { sendPageEvent: false }], - ['track'], - ]; - (window as any).rudderanalytics = bufferedEvents; - const rudderAnalyticsInstance = new RudderAnalytics(); - const result = rudderAnalyticsInstance.getPreloadedEvents(); - expect(result).toEqual(bufferedEvents); + it('should dispatch an error event if an exception is thrown during the getUserId call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the getUserId call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + const userIdVal = rudderAnalytics.getUserId(); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + expect(userIdVal).toBeUndefined(); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); -}); -describe('trackPageLifecycleEvents', () => { - let rudderAnalyticsInstance: RudderAnalytics; + it('should dispatch an error event if an exception is thrown during the getUserTraits call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - beforeEach(() => { - (window as any).rudderanalytics = []; - rudderAnalyticsInstance = new RudderAnalytics(); - rudderAnalyticsInstance.analyticsInstances = {}; + // Intentionally cause an error during the getUserTraits call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + const traitsVal = rudderAnalytics.getUserTraits(); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + expect(traitsVal).toBeUndefined(); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); - afterEach(() => { - (rudderAnalyticsInstance as any).globalSingleton = null; - jest.resetAllMocks(); + it('should dispatch an error event if an exception is thrown during the getGroupId call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the getGroupId call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + const groupId = rudderAnalytics.getGroupId(); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + expect(groupId).toBeUndefined(); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); - it('should not add pageLifecycleEvents in the buffer when the tracking is not enabled through load options', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, {}); + it('should dispatch an error event if an exception is thrown during the getGroupTraits call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the getGroupTraits call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + const traitsVal = rudderAnalytics.getGroupTraits(); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + expect(traitsVal).toBeUndefined(); - expect(bufferedEvents).toEqual([]); + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); - it('should inherit enabled and options properties from autoTrack load option', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { - autoTrack: { - enabled: true, - options: { key: 'value' }, - }, - }); + it('should dispatch an error event if an exception is thrown during the endSession call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); - expect(bufferedEvents).toEqual([ - ['track', 'Page Loaded', {}, { key: 'value', originalTimestamp: expect.any(String) }], - ]); + // Intentionally cause an error during the endSession call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + rudderAnalytics.endSession(); + + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); - it('should override enabled and options properties of autoTrack if provided in load option', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { - autoTrack: { - enabled: true, - options: { key: 'value' }, - pageLifecycle: { - enabled: false, - }, - }, - }); + it('should dispatch an error event if an exception is thrown during the getSessionId call', () => { + const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); + + // Intentionally cause an error during the getSessionId call + const getAnalyticsInstanceSpy = jest + .spyOn(rudderAnalytics, 'getAnalyticsInstance') + .mockImplementation(() => { + throw new Error('Error in getAnalyticsInstance'); + }); + + const sessionId = rudderAnalytics.getSessionId(); - expect(bufferedEvents).toEqual([]); + expect(dispatchEventSpy).toHaveBeenCalledWith( + new ErrorEvent('error', { + error: new Error('Error in getAnalyticsInstance'), + }), + ); + + expect(sessionId).toBeUndefined(); + + dispatchEventSpy.mockRestore(); + + getAnalyticsInstanceSpy.mockRestore(); }); - it('should track Page Loaded event irrespective of useBeacon load option', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { - useBeacon: false, - autoTrack: { - pageLifecycle: { + describe('trackPageLifecycleEvents', () => { + let rudderAnalyticsInstance: RudderAnalytics; + + beforeEach(() => { + (window as any).rudderanalytics = []; + rudderAnalyticsInstance = new RudderAnalytics(); + rudderAnalyticsInstance.analyticsInstances = {}; + }); + + afterEach(() => { + (rudderAnalyticsInstance as any).globalSingleton = null; + jest.resetAllMocks(); + }); + + it('should not add pageLifecycleEvents in the buffer when the tracking is not enabled through load options', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, {}); + + expect(bufferedEvents).toEqual([]); + }); + + it('should inherit enabled and options properties from autoTrack load option', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { + autoTrack: { enabled: true, + options: { key: 'value' }, }, - }, - }); + }); - expect(bufferedEvents).toEqual([ - ['track', 'Page Loaded', {}, { originalTimestamp: expect.any(String) }], - ]); - }); + expect(bufferedEvents).toEqual([ + ['track', 'Page Loaded', {}, { key: 'value', originalTimestamp: expect.any(String) }], + ]); + }); - it('should track Page Unloaded event if useBeacon is set to true and trackPageLifecycle feature is enabled', () => { - const bufferedEvents: PreloadedEventCall[] = []; - rudderAnalyticsInstance.track = jest.fn(); - rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { - useBeacon: true, - autoTrack: { - pageLifecycle: { + it('should override enabled and options properties of autoTrack if provided in load option', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { + autoTrack: { enabled: true, + options: { key: 'value' }, + pageLifecycle: { + enabled: false, + }, }, - }, + }); + + expect(bufferedEvents).toEqual([]); }); - state.lifecycle.loaded.value = true; - const event = new Event('beforeunload'); - // Simulate the event - window.dispatchEvent(event); - - expect(rudderAnalyticsInstance.track).toHaveBeenCalledWith( - 'Page Unloaded', - { visitDuration: expect.any(Number) }, - { originalTimestamp: expect.any(String) }, - ); - }); - it('should invoke trackPageLifecycleEvents method when load API is called', () => { - rudderAnalyticsInstance.trackPageLifecycleEvents = jest.fn(); - rudderAnalyticsInstance.load('writeKey', 'data-plane-url', { - autoTrack: { - enabled: true, - }, + it('should track Page Loaded event irrespective of useBeacon load option', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { + useBeacon: false, + autoTrack: { + pageLifecycle: { + enabled: true, + }, + }, + }); + + expect(bufferedEvents).toEqual([ + ['track', 'Page Loaded', {}, { originalTimestamp: expect.any(String) }], + ]); }); - expect(rudderAnalyticsInstance.trackPageLifecycleEvents).toHaveBeenCalledWith([], { - autoTrack: { - enabled: true, - }, + + it('should track Page Unloaded event if useBeacon is set to true and trackPageLifecycle feature is enabled', () => { + const bufferedEvents: PreloadedEventCall[] = []; + rudderAnalyticsInstance.track = jest.fn(); + rudderAnalyticsInstance.trackPageLifecycleEvents(bufferedEvents, { + useBeacon: true, + autoTrack: { + pageLifecycle: { + enabled: true, + }, + }, + }); + state.lifecycle.loaded.value = true; + const event = new Event('beforeunload'); + // Simulate the event + window.dispatchEvent(event); + + expect(rudderAnalyticsInstance.track).toHaveBeenCalledWith( + 'Page Unloaded', + { visitDuration: expect.any(Number) }, + { originalTimestamp: expect.any(String) }, + ); + }); + + it('should invoke trackPageLifecycleEvents method when load API is called', () => { + rudderAnalyticsInstance.trackPageLifecycleEvents = jest.fn(); + rudderAnalyticsInstance.load('writeKey', 'data-plane-url', { + autoTrack: { + enabled: true, + }, + }); + expect(rudderAnalyticsInstance.trackPageLifecycleEvents).toHaveBeenCalledWith([], { + autoTrack: { + enabled: true, + }, + }); }); }); }); diff --git a/packages/analytics-js/src/app/RudderAnalytics.ts b/packages/analytics-js/src/app/RudderAnalytics.ts index 7d8de7add9..8ea3ed5085 100644 --- a/packages/analytics-js/src/app/RudderAnalytics.ts +++ b/packages/analytics-js/src/app/RudderAnalytics.ts @@ -17,13 +17,14 @@ import { } from '@rudderstack/analytics-js-common/types/LoadOptions'; import type { ApiCallback, ApiOptions } from '@rudderstack/analytics-js-common/types/EventApi'; import type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject'; -import { RS_APP } from '@rudderstack/analytics-js-common/constants/loggerContexts'; +import { RSA } from '@rudderstack/analytics-js-common/constants/loggerContexts'; import type { IdentifyTraits } from '@rudderstack/analytics-js-common/types/traits'; -import { getSanitizedValue } from '@rudderstack/analytics-js-common/utilities/json'; import { generateUUID } from '@rudderstack/analytics-js-common/utilities/uuId'; import { onPageLeave } from '@rudderstack/analytics-js-common/utilities/page'; import { isString } from '@rudderstack/analytics-js-common/utilities/checks'; import { getFormattedTimestamp } from '@rudderstack/analytics-js-common/utilities/timestamp'; +import { getSanitizedValue } from '@rudderstack/analytics-js-common/utilities/json'; +import { dispatchErrorEvent } from '@rudderstack/analytics-js-common/utilities/errors'; import { GLOBAL_PRELOAD_BUFFER } from '../constants/app'; import { getPreloadedLoadEvent, @@ -34,10 +35,7 @@ import { setExposedGlobal } from '../components/utilities/globals'; import type { IAnalytics } from '../components/core/IAnalytics'; import { Analytics } from '../components/core/Analytics'; import { defaultLogger } from '../services/Logger/Logger'; -import { - EMPTY_GROUP_CALL_ERROR, - PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING, -} from '../constants/logMessages'; +import { PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING } from '../constants/logMessages'; import { defaultErrorHandler } from '../services/ErrorHandler'; import { state } from '../state'; @@ -50,55 +48,62 @@ import { state } from '../state'; * consume SDK preload event buffer */ class RudderAnalytics implements IRudderAnalytics { + // START-NO-SONAR-SCAN + // eslint-disable-next-line sonarjs/public-static-readonly static globalSingleton: Nullable = null; + // END-NO-SONAR-SCAN analyticsInstances: Record = {}; defaultAnalyticsKey = ''; logger = defaultLogger; // Singleton with constructor bind methods constructor() { - if (RudderAnalytics.globalSingleton) { - // START-NO-SONAR-SCAN - // eslint-disable-next-line no-constructor-return - return RudderAnalytics.globalSingleton; - // END-NO-SONAR-SCAN + try { + if (RudderAnalytics.globalSingleton) { + // START-NO-SONAR-SCAN + // eslint-disable-next-line no-constructor-return + return RudderAnalytics.globalSingleton; + // END-NO-SONAR-SCAN + } + defaultErrorHandler.attachErrorListeners(); + + this.setDefaultInstanceKey = this.setDefaultInstanceKey.bind(this); + this.getAnalyticsInstance = this.getAnalyticsInstance.bind(this); + this.load = this.load.bind(this); + this.ready = this.ready.bind(this); + this.triggerBufferedLoadEvent = this.triggerBufferedLoadEvent.bind(this); + this.page = this.page.bind(this); + this.track = this.track.bind(this); + this.identify = this.identify.bind(this); + this.alias = this.alias.bind(this); + this.group = this.group.bind(this); + this.reset = this.reset.bind(this); + this.getAnonymousId = this.getAnonymousId.bind(this); + this.setAnonymousId = this.setAnonymousId.bind(this); + this.getUserId = this.getUserId.bind(this); + this.getUserTraits = this.getUserTraits.bind(this); + this.getGroupId = this.getGroupId.bind(this); + this.getGroupTraits = this.getGroupTraits.bind(this); + this.startSession = this.startSession.bind(this); + this.endSession = this.endSession.bind(this); + this.getSessionId = this.getSessionId.bind(this); + this.setAuthToken = this.setAuthToken.bind(this); + this.consent = this.consent.bind(this); + + RudderAnalytics.globalSingleton = this; + + state.autoTrack.pageLifecycle.visitId.value = generateUUID(); + state.autoTrack.pageLifecycle.pageLoadedTimestamp.value = Date.now(); + + // start loading if a load event was buffered or wait for explicit load call + this.triggerBufferedLoadEvent(); + + // Assign to global "rudderanalytics" object after processing the preload buffer (if any exists) + // for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly + (globalThis as typeof window).rudderanalytics = this; + } catch (error: any) { + dispatchErrorEvent(error); } - defaultErrorHandler.attachErrorListeners(); - - this.setDefaultInstanceKey = this.setDefaultInstanceKey.bind(this); - this.getAnalyticsInstance = this.getAnalyticsInstance.bind(this); - this.load = this.load.bind(this); - this.ready = this.ready.bind(this); - this.triggerBufferedLoadEvent = this.triggerBufferedLoadEvent.bind(this); - this.page = this.page.bind(this); - this.track = this.track.bind(this); - this.identify = this.identify.bind(this); - this.alias = this.alias.bind(this); - this.group = this.group.bind(this); - this.reset = this.reset.bind(this); - this.getAnonymousId = this.getAnonymousId.bind(this); - this.setAnonymousId = this.setAnonymousId.bind(this); - this.getUserId = this.getUserId.bind(this); - this.getUserTraits = this.getUserTraits.bind(this); - this.getGroupId = this.getGroupId.bind(this); - this.getGroupTraits = this.getGroupTraits.bind(this); - this.startSession = this.startSession.bind(this); - this.endSession = this.endSession.bind(this); - this.getSessionId = this.getSessionId.bind(this); - this.setAuthToken = this.setAuthToken.bind(this); - this.consent = this.consent.bind(this); - - RudderAnalytics.globalSingleton = this; - - state.autoTrack.pageLifecycle.visitId.value = generateUUID(); - state.autoTrack.pageLifecycle.pageLoadedTimestamp.value = Date.now(); - - // start loading if a load event was buffered or wait for explicit load call - this.triggerBufferedLoadEvent(); - - // Assign to global "rudderanalytics" object after processing the preload buffer (if any exists) - // for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly - (globalThis as typeof window).rudderanalytics = this; } /** @@ -107,6 +112,10 @@ class RudderAnalytics implements IRudderAnalytics { * TODO: to support multiple analytics instances in the near future */ setDefaultInstanceKey(writeKey: string) { + // IMP: Add try-catch block to handle any unhandled errors + // similar to other public methods + // if the implementation of this method goes beyond + // this simple implementation if (isString(writeKey) && writeKey) { this.defaultAnalyticsKey = writeKey; } @@ -115,19 +124,24 @@ class RudderAnalytics implements IRudderAnalytics { /** * Retrieve an existing analytics instance */ - getAnalyticsInstance(writeKey?: string): IAnalytics { - let instanceId = writeKey; - if (!isString(instanceId) || !instanceId) { - instanceId = this.defaultAnalyticsKey; - } + getAnalyticsInstance(writeKey?: string): IAnalytics | undefined { + try { + let instanceId = writeKey; + if (!isString(instanceId) || !instanceId) { + instanceId = this.defaultAnalyticsKey; + } - const analyticsInstanceExists = Boolean(this.analyticsInstances[instanceId]); + const analyticsInstanceExists = Boolean(this.analyticsInstances[instanceId]); - if (!analyticsInstanceExists) { - this.analyticsInstances[instanceId] = new Analytics(); - } + if (!analyticsInstanceExists) { + this.analyticsInstances[instanceId] = new Analytics(); + } - return this.analyticsInstances[instanceId] as IAnalytics; + return this.analyticsInstances[instanceId] as IAnalytics; + } catch (error: any) { + dispatchErrorEvent(error); + return undefined; + } } /** @@ -137,28 +151,32 @@ class RudderAnalytics implements IRudderAnalytics { * @param loadOptions Additional options for loading the SDK * @returns none */ - load(writeKey: string, dataPlaneUrl: string, loadOptions?: Partial) { - if (this.analyticsInstances[writeKey]) { - return; - } + load(writeKey: string, dataPlaneUrl: string, loadOptions?: Partial): void { + try { + if (this.analyticsInstances[writeKey]) { + return; + } - this.setDefaultInstanceKey(writeKey); - const preloadedEventsArray = this.getPreloadedEvents(); + this.setDefaultInstanceKey(writeKey); + const preloadedEventsArray = this.getPreloadedEvents(); - // Track page loaded lifecycle event if enabled - this.trackPageLifecycleEvents(preloadedEventsArray, loadOptions); + // Track page loaded lifecycle event if enabled + this.trackPageLifecycleEvents(preloadedEventsArray, loadOptions); - // The array will be mutated in the below method - promotePreloadedConsentEventsToTop(preloadedEventsArray); + // The array will be mutated in the below method + promotePreloadedConsentEventsToTop(preloadedEventsArray); - setExposedGlobal(GLOBAL_PRELOAD_BUFFER, clone(preloadedEventsArray)); + setExposedGlobal(GLOBAL_PRELOAD_BUFFER, clone(preloadedEventsArray)); - this.analyticsInstances[writeKey] = new Analytics(); - this.getAnalyticsInstance(writeKey).load( - writeKey, - dataPlaneUrl, - getSanitizedValue(loadOptions), - ); + this.analyticsInstances[writeKey] = new Analytics(); + this.getAnalyticsInstance(writeKey)?.load( + writeKey, + dataPlaneUrl, + getSanitizedValue(loadOptions), + ); + } catch (error: any) { + dispatchErrorEvent(error); + } } /** @@ -216,7 +234,7 @@ class RudderAnalytics implements IRudderAnalytics { * @param preloadedEventsArray */ // eslint-disable-next-line class-methods-use-this - private trackPageLoadedEvent( + trackPageLoadedEvent( events: PageLifecycleEvents[], options: ApiOptions, preloadedEventsArray: PreloadedEventCall[], @@ -242,7 +260,7 @@ class RudderAnalytics implements IRudderAnalytics { * @param useBeacon * @param options */ - private setupPageUnloadTracking( + setupPageUnloadTracking( events: PageLifecycleEvents[], useBeacon: boolean | undefined, options: ApiOptions, @@ -270,7 +288,7 @@ class RudderAnalytics implements IRudderAnalytics { }); } else { // throw warning if beacon is disabled - this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RS_APP)); + this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RSA)); } } } @@ -304,7 +322,11 @@ class RudderAnalytics implements IRudderAnalytics { * Get ready callback arguments and forward to ready call */ ready(callback: ApiCallback) { - this.getAnalyticsInstance().ready(callback); + try { + this.getAnalyticsInstance()?.ready(getSanitizedValue(callback)); + } catch (error: any) { + dispatchErrorEvent(error); + } } /** @@ -347,15 +369,13 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - this.getAnalyticsInstance().page( - pageArgumentsToCallOptions( - getSanitizedValue(category), - getSanitizedValue(name), - getSanitizedValue(properties), - getSanitizedValue(options), - callback, - ), - ); + try { + this.getAnalyticsInstance()?.page( + pageArgumentsToCallOptions(category, name, properties, options, callback), + ); + } catch (error: any) { + dispatchErrorEvent(error); + } } /** @@ -376,14 +396,13 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - this.getAnalyticsInstance().track( - trackArgumentsToCallOptions( - getSanitizedValue(event), - getSanitizedValue(properties), - getSanitizedValue(options), - callback, - ), - ); + try { + this.getAnalyticsInstance()?.track( + trackArgumentsToCallOptions(event, properties, options, callback), + ); + } catch (error: any) { + dispatchErrorEvent(error); + } } /** @@ -410,14 +429,13 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - this.getAnalyticsInstance().identify( - identifyArgumentsToCallOptions( - getSanitizedValue(userId), - getSanitizedValue(traits), - getSanitizedValue(options), - callback, - ), - ); + try { + this.getAnalyticsInstance()?.identify( + identifyArgumentsToCallOptions(userId, traits, options, callback), + ); + } catch (error: any) { + dispatchErrorEvent(error); + } } /** @@ -434,14 +452,11 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - this.getAnalyticsInstance().alias( - aliasArgumentsToCallOptions( - getSanitizedValue(to), - getSanitizedValue(from), - getSanitizedValue(options), - callback, - ), - ); + try { + this.getAnalyticsInstance()?.alias(aliasArgumentsToCallOptions(to, from, options, callback)); + } catch (error: any) { + dispatchErrorEvent(error); + } } /** @@ -468,70 +483,118 @@ class RudderAnalytics implements IRudderAnalytics { options?: Nullable | ApiCallback, callback?: ApiCallback, ) { - if (arguments.length === 0) { - this.logger.error(EMPTY_GROUP_CALL_ERROR(RS_APP)); - return; + try { + this.getAnalyticsInstance()?.group( + groupArgumentsToCallOptions(groupId, traits, options, callback), + ); + } catch (error: any) { + dispatchErrorEvent(error); } - - this.getAnalyticsInstance().group( - groupArgumentsToCallOptions( - getSanitizedValue(groupId), - getSanitizedValue(traits), - getSanitizedValue(options), - callback, - ), - ); } reset(resetAnonymousId?: boolean) { - this.getAnalyticsInstance().reset(getSanitizedValue(resetAnonymousId)); + try { + this.getAnalyticsInstance()?.reset(getSanitizedValue(resetAnonymousId)); + } catch (error: any) { + dispatchErrorEvent(error); + } } - getAnonymousId(options?: AnonymousIdOptions) { - return this.getAnalyticsInstance().getAnonymousId(getSanitizedValue(options)); + getAnonymousId(options?: AnonymousIdOptions): string | undefined { + try { + return this.getAnalyticsInstance()?.getAnonymousId(getSanitizedValue(options)); + } catch (error: any) { + dispatchErrorEvent(error); + return undefined; + } } - setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string) { - this.getAnalyticsInstance().setAnonymousId( - getSanitizedValue(anonymousId), - getSanitizedValue(rudderAmpLinkerParam), - ); + setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string): void { + try { + this.getAnalyticsInstance()?.setAnonymousId( + getSanitizedValue(anonymousId), + getSanitizedValue(rudderAmpLinkerParam), + ); + } catch (error: any) { + dispatchErrorEvent(error); + } } getUserId() { - return this.getAnalyticsInstance().getUserId(); + try { + return this.getAnalyticsInstance()?.getUserId(); + } catch (error: any) { + dispatchErrorEvent(error); + return undefined; + } } getUserTraits() { - return this.getAnalyticsInstance().getUserTraits(); + try { + return this.getAnalyticsInstance()?.getUserTraits(); + } catch (error: any) { + dispatchErrorEvent(error); + return undefined; + } } getGroupId() { - return this.getAnalyticsInstance().getGroupId(); + try { + return this.getAnalyticsInstance()?.getGroupId(); + } catch (error: any) { + dispatchErrorEvent(error); + return undefined; + } } getGroupTraits() { - return this.getAnalyticsInstance().getGroupTraits(); + try { + return this.getAnalyticsInstance()?.getGroupTraits(); + } catch (error: any) { + dispatchErrorEvent(error); + return undefined; + } } - startSession(sessionId?: number) { - return this.getAnalyticsInstance().startSession(sessionId); + startSession(sessionId?: number): void { + try { + this.getAnalyticsInstance()?.startSession(getSanitizedValue(sessionId)); + } catch (error: any) { + dispatchErrorEvent(error); + } } - endSession() { - return this.getAnalyticsInstance().endSession(); + endSession(): void { + try { + this.getAnalyticsInstance()?.endSession(); + } catch (error: any) { + dispatchErrorEvent(error); + } } getSessionId() { - return this.getAnalyticsInstance().getSessionId(); + try { + return this.getAnalyticsInstance()?.getSessionId(); + } catch (error: any) { + dispatchErrorEvent(error); + return undefined; + } } - setAuthToken(token: string) { - return this.getAnalyticsInstance().setAuthToken(getSanitizedValue(token)); + setAuthToken(token: string): void { + try { + this.getAnalyticsInstance()?.setAuthToken(getSanitizedValue(token)); + } catch (error: any) { + dispatchErrorEvent(error); + } } - consent(options?: ConsentOptions) { - return this.getAnalyticsInstance().consent(getSanitizedValue(options)); + consent(options?: ConsentOptions): void { + try { + this.getAnalyticsInstance()?.consent(getSanitizedValue(options)); + } catch (error: any) { + dispatchErrorEvent(error); + } } } diff --git a/packages/analytics-js/src/constants/logMessages.ts b/packages/analytics-js/src/constants/logMessages.ts index a28ee4b12e..0020c5fdb4 100644 --- a/packages/analytics-js/src/constants/logMessages.ts +++ b/packages/analytics-js/src/constants/logMessages.ts @@ -193,9 +193,6 @@ const STORAGE_UNAVAILABLE_WARNING = ( ): string => `${context}${LOG_CONTEXT_SEPARATOR}The storage type "${selectedStorageType}" is not available for entry "${entry}". The SDK will initialize the entry with "${finalStorageType}" storage type instead.`; -const EMPTY_GROUP_CALL_ERROR = (context: string): string => - `${context}${LOG_CONTEXT_SEPARATOR}The group() method must be called with at least one argument.`; - const READY_CALLBACK_INVOKE_ERROR = `Failed to invoke the ready callback`; const API_CALLBACK_INVOKE_ERROR = `API Callback Invocation Failed`; @@ -297,7 +294,6 @@ export { PLUGIN_EXT_POINT_MISSING_ERROR, PLUGIN_EXT_POINT_INVALID_ERROR, STORAGE_TYPE_VALIDATION_WARNING, - EMPTY_GROUP_CALL_ERROR, READY_CALLBACK_INVOKE_ERROR, API_CALLBACK_INVOKE_ERROR, INVALID_CONFIG_URL_WARNING, diff --git a/packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts b/packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts index 405d91e5d8..7d2fbc5f4c 100644 --- a/packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts +++ b/packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts @@ -14,6 +14,7 @@ import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constant import { BufferQueue } from '@rudderstack/analytics-js-common/services/BufferQueue/BufferQueue'; import type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient'; import type { IExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader/types'; +import { MANUAL_ERROR_IDENTIFIER } from '@rudderstack/analytics-js-common/utilities/errors'; import { NOTIFY_FAILURE_ERROR, REPORTING_PLUGIN_INIT_FAILURE_ERROR, @@ -168,6 +169,8 @@ class ErrorHandler implements IErrorHandler { } else { throw normalizedError; } + } else if ((error as any).error?.stack?.includes(MANUAL_ERROR_IDENTIFIER)) { + this.logger?.error('An unknown error occurred:', (error as ErrorEvent).error?.message); } }