Skip to content

Commit ff63953

Browse files
Rework Analytics initialization (#357)
1 parent a8b3dc5 commit ff63953

213 files changed

Lines changed: 7250 additions & 6798 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

CHANGELOG.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,13 @@ Our versioning strategy is as follows:
2626
* `[react]` Added React hooks for search functionality
2727
- `useSearch` hook for paginated search queries with automatic state management, request cancellation, request status tracking.
2828
- `useInfiniteSearch` hook for infinite scroll/search patterns with `loadMore` functionality, request cancellation, request status tracking.
29-
* `[analytics]` `[core]` `[create-content-sdk-app]` `[nextjs]` `[react]` Reorganize Analytics packages ([#340](https://github.com/Sitecore/content-sdk/pull/340))([#341](https://github.com/Sitecore/content-sdk/pull/341))
3029

3130
* `[nextjs]` `[Pages Router]` Adjust static path generation when multisite is disabled ([#345](https://github.com/Sitecore/content-sdk/pull/345))
3231

32+
* Introduce Analytics packages:
33+
* `[analytics]` `[core]` `[create-content-sdk-app]` `[nextjs]` `[react]` Reorganize Analytics packages ([#340](https://github.com/Sitecore/content-sdk/pull/340))([#341](https://github.com/Sitecore/content-sdk/pull/341))
34+
* `[sdk]` Rework Analytics initialization ([#357](https://github.com/Sitecore/content-sdk/pull/357))
35+
3336
### 🛠 Breaking Changes
3437

3538
* Decouple `@sitecore-content-sdk/content` from `@sitecore-content-sdk/core` ([#351](https://github.com/Sitecore/content-sdk/pull/351)):

packages/analytics-core/browser.d.ts

Lines changed: 0 additions & 2 deletions
This file was deleted.

packages/analytics-core/package.json

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"url": "https://github.com/sitecore/content-sdk/issues"
88
},
99
"dependencies": {
10+
"@sitecore-content-sdk/core": "1.5.0-canary.6",
1011
"debug": "^4.4.3"
1112
},
1213
"description": "> TODO: description",
@@ -29,26 +30,24 @@
2930
"ts-jest": "^29.1.0",
3031
"ts-node": "^10.9.2"
3132
},
33+
"main": "dist/cjs/index.js",
34+
"module": "dist/esm/index.js",
35+
"types": "types/src/index.d.ts",
3236
"exports": {
33-
"./browser": {
34-
"import": "./dist/esm/src/browser.js",
35-
"require": "./dist/cjs/src/browser.js",
36-
"types": "./types/src/browser/index.d.ts"
37+
".": {
38+
"import": "./dist/esm/src/index.js",
39+
"require": "./dist/cjs/src/index.js",
40+
"types": "./types/src/index.d.ts"
3741
},
3842
"./internal": {
3943
"import": "./dist/esm/src/internal.js",
4044
"require": "./dist/cjs/src/internal.js",
41-
"types": "./types/src/internal/index.d.ts"
42-
},
43-
"./server": {
44-
"import": "./dist/esm/src/server.js",
45-
"require": "./dist/cjs/src/server.js",
46-
"types": "./types/src/server/index.d.ts"
45+
"types": "./types/src/internal.d.ts"
4746
},
4847
"./utils": {
4948
"import": "./dist/esm/src/utils.js",
5049
"require": "./dist/cjs/src/utils.js",
51-
"types": "./types/src/utils/index.d.ts"
50+
"types": "./types/src/utils.d.ts"
5251
}
5352
},
5453
"files": [

packages/analytics-core/server.d.ts

Lines changed: 0 additions & 2 deletions
This file was deleted.

packages/analytics-core/src/browser-id/construct-get-browser-id-url.spec.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { SITECORE_EDGE_URL } from '../consts';
22
import { constructGetBrowserIdUrl } from './construct-get-browser-id-url';
3+
import { expect } from '@jest/globals';
34

45
describe('constructGetBrowserIdUrl', () => {
56
it('should correctly create the URL for retrieving the browser Id from EDGE events proxy', () => {

packages/analytics-core/src/browser-id/fetch-browser-id-from-edge-proxy.spec.ts

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import * as utils from '../utils';
2-
import { ErrorMessages, LIBRARY_VERSION, SITECORE_EDGE_URL } from '../consts';
2+
import { ERROR_MESSAGES, LIBRARY_VERSION, SITECORE_EDGE_URL } from '../consts';
33
import type { EPResponse } from '../interfaces';
44
import * as constructGetBrowserIdUrl from './construct-get-browser-id-url';
55
import { fetchBrowserIdFromEdgeProxy } from './fetch-browser-id-from-edge-proxy';
6+
import { jest, expect } from '@jest/globals';
67

78
describe('fetchBrowserIdFromEdgeProxy', () => {
89
const constructBrowserIdUrlSpy = jest.spyOn(constructGetBrowserIdUrl, 'constructGetBrowserIdUrl');
@@ -87,7 +88,7 @@ describe('fetchBrowserIdFromEdgeProxy', () => {
8788

8889
global.fetch = jest.fn(() => Promise.reject(abortError));
8990

90-
const expectedError = ErrorMessages.IE_0003;
91+
const expectedError = ERROR_MESSAGES.IE_0003;
9192

9293
expect(async () => {
9394
await fetchBrowserIdFromEdgeProxy(SITECORE_EDGE_URL, sitecoreEdgeContextId);
@@ -97,7 +98,7 @@ describe('fetchBrowserIdFromEdgeProxy', () => {
9798
it('should throw IE-0003 error if fetch returns null - fetchWithTimeout', async () => {
9899
const fetchWithTimeoutSpy = jest.spyOn(utils, 'fetchWithTimeout').mockResolvedValue(null);
99100

100-
const expectedError = ErrorMessages.IE_0003;
101+
const expectedError = ERROR_MESSAGES.IE_0003;
101102

102103
expect(async () => {
103104
await fetchBrowserIdFromEdgeProxy(SITECORE_EDGE_URL, sitecoreEdgeContextId, 100);
@@ -110,7 +111,7 @@ describe('fetchBrowserIdFromEdgeProxy', () => {
110111
.spyOn(utils, 'fetchWithTimeout')
111112
.mockRejectedValueOnce({ message: 'random error' });
112113

113-
const expectedError = ErrorMessages.IE_0003;
114+
const expectedError = ERROR_MESSAGES.IE_0003;
114115

115116
expect(async () => {
116117
await fetchBrowserIdFromEdgeProxy(SITECORE_EDGE_URL, sitecoreEdgeContextId, 100);
@@ -120,23 +121,23 @@ describe('fetchBrowserIdFromEdgeProxy', () => {
120121

121122
it('should throw [IV-0006] when we pass negative timeout value', async () => {
122123
const fetchWithTimeoutSpy = jest.spyOn(utils, 'fetchWithTimeout').mockRejectedValueOnce({
123-
message: utils.ErrorMessages.IV_0006,
124+
message: utils.ERROR_MESSAGES.IV_0006,
124125
});
125126

126127
expect(async () => {
127128
await fetchBrowserIdFromEdgeProxy(SITECORE_EDGE_URL, sitecoreEdgeContextId, -100);
128-
}).rejects.toThrow(utils.ErrorMessages.IV_0006);
129+
}).rejects.toThrow(utils.ERROR_MESSAGES.IV_0006);
129130
expect(fetchWithTimeoutSpy).toHaveBeenCalledTimes(1);
130131
});
131132

132133
it('should throw [IE-0002] when we get an AbortError', async () => {
133134
const fetchWithTimeoutSpy = jest.spyOn(utils, 'fetchWithTimeout').mockRejectedValueOnce({
134-
message: utils.ErrorMessages.IE_0002,
135+
message: utils.ERROR_MESSAGES.IE_0002,
135136
});
136137

137138
await expect(async () => {
138139
await fetchBrowserIdFromEdgeProxy(SITECORE_EDGE_URL, sitecoreEdgeContextId, 100);
139-
}).rejects.toThrow(utils.ErrorMessages.IE_0002);
140+
}).rejects.toThrow(utils.ERROR_MESSAGES.IE_0002);
140141
expect(fetchWithTimeoutSpy).toHaveBeenCalledTimes(1);
141142
});
142143
});

packages/analytics-core/src/browser-id/fetch-browser-id-from-edge-proxy.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { EPResponse, ProxySettings } from '../interfaces';
2-
import { ErrorMessages, LIBRARY_VERSION } from '../consts';
3-
import { ErrorMessages as UtilsErrorMessages, fetchWithTimeout } from '../utils';
2+
import { ERROR_MESSAGES, LIBRARY_VERSION } from '../consts';
3+
import { ERROR_MESSAGES as UTILS_ERROR_MESSAGES, fetchWithTimeout } from '../utils';
44
import { constructGetBrowserIdUrl } from './construct-get-browser-id-url';
55

66
/**
@@ -33,8 +33,8 @@ export async function fetchBrowserIdFromEdgeProxy(
3333
})
3434
.catch((err) => {
3535
if (
36-
err.message === UtilsErrorMessages.IV_0006 ||
37-
err.message === UtilsErrorMessages.IE_0002
36+
err.message === UTILS_ERROR_MESSAGES.IV_0006 ||
37+
err.message === UTILS_ERROR_MESSAGES.IE_0002
3838
)
3939
throw new Error(err.message);
4040

@@ -45,7 +45,7 @@ export async function fetchBrowserIdFromEdgeProxy(
4545
.then((res) => res.json())
4646
.catch(() => undefined);
4747

48-
if (!payload?.ref) throw new Error(ErrorMessages.IE_0003);
48+
if (!payload?.ref) throw new Error(ERROR_MESSAGES.IE_0003);
4949

5050
const { ref: browserId, customer_ref: guestId }: EPResponse = payload;
5151
return { browserId, guestId };
Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,49 @@
1-
import * as coreBrowserModule from '../initializer/browser/initializer';
1+
import * as pluginsModule from '../initialization/plugin';
22
import { getBrowserId } from './get-browser-id';
3+
import { jest, expect } from '@jest/globals';
34

4-
jest.mock('../initializer/browser/initializer');
5+
jest.mock('../initialization/plugin');
56

67
describe('getBrowserId', () => {
7-
const getCloudSDKSettingsSpy = jest
8-
.spyOn(coreBrowserModule, 'getCloudSDKSettings')
9-
.mockReturnValue({
10-
cookieSettings: {
11-
domain: 'cDomain',
12-
expiryDays: 730,
13-
name: { browserId: 'bid_name' },
14-
path: '/',
15-
},
16-
siteName: '456',
17-
sitecoreEdgeContextId: '123',
18-
sitecoreEdgeUrl: '',
19-
});
8+
const mockEnvironment = {
9+
getBrowserId: jest.fn(),
10+
};
11+
12+
const getAnalyticsPluginSpy = jest.spyOn(pluginsModule, 'getAnalyticsPlugin').mockReturnValue({
13+
environment: mockEnvironment,
14+
} as unknown as ReturnType<typeof pluginsModule.getAnalyticsPlugin>);
2015

2116
afterEach(() => {
2217
jest.clearAllMocks();
2318
});
2419

25-
it('should return the cookie value when cookie exists on the page', async () => {
26-
jest.spyOn(document, 'cookie', 'get').mockReturnValueOnce(`bid_name=bid_value`);
27-
28-
const mockCoreBrowserModule = coreBrowserModule as { initCoreState: Promise<void> };
29-
mockCoreBrowserModule.initCoreState = Promise.resolve();
20+
it('should return the browser ID when environment returns a value', () => {
21+
mockEnvironment.getBrowserId.mockReturnValueOnce('bid_value');
3022

3123
const browserId = getBrowserId();
24+
3225
expect(browserId).toEqual('bid_value');
33-
expect(getCloudSDKSettingsSpy).toHaveBeenCalledTimes(1);
26+
expect(getAnalyticsPluginSpy).toHaveBeenCalledTimes(1);
27+
expect(mockEnvironment.getBrowserId).toHaveBeenCalledTimes(1);
3428
});
3529

36-
it('should return empty string if there is a cookie but not the correct one', async () => {
37-
jest.spyOn(document, 'cookie', 'get').mockReturnValueOnce('WrongCookieName=cookieValue');
38-
39-
const mockCoreBrowserModule = coreBrowserModule as { initCoreState: Promise<void> };
40-
mockCoreBrowserModule.initCoreState = Promise.resolve();
30+
it('should return empty string when environment returns null', () => {
31+
mockEnvironment.getBrowserId.mockReturnValueOnce(null);
4132

4233
const browserId = getBrowserId();
34+
4335
expect(browserId).toEqual('');
44-
expect(getCloudSDKSettingsSpy).toHaveBeenCalledTimes(1);
36+
expect(getAnalyticsPluginSpy).toHaveBeenCalledTimes(1);
37+
expect(mockEnvironment.getBrowserId).toHaveBeenCalledTimes(1);
4538
});
46-
it('should return empty string if no cookie exists on the page', async () => {
47-
const mockCoreBrowserModule = coreBrowserModule as { initCoreState: Promise<void> };
48-
mockCoreBrowserModule.initCoreState = Promise.resolve();
39+
40+
it('should return empty string when environment returns undefined', () => {
41+
mockEnvironment.getBrowserId.mockReturnValueOnce(undefined);
4942

5043
const browserId = getBrowserId();
44+
5145
expect(browserId).toBe('');
52-
expect(getCloudSDKSettingsSpy).toHaveBeenCalledTimes(1);
46+
expect(getAnalyticsPluginSpy).toHaveBeenCalledTimes(1);
47+
expect(mockEnvironment.getBrowserId).toHaveBeenCalledTimes(1);
5348
});
5449
});
Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
1-
import { getCookieValueClientSide } from '../utils';
2-
import { getCloudSDKSettings } from '../initializer/browser/initializer';
1+
import { getAnalyticsPlugin } from '../internal';
32

43
/**
54
* Gets the browser ID from the cookie.
65
* @returns {string} The browser ID if the cookie exists.
76
*/
87
export function getBrowserId(): string {
9-
const cloudSDKSettings = getCloudSDKSettings();
10-
11-
return getCookieValueClientSide(cloudSDKSettings.cookieSettings.name.browserId);
8+
return getAnalyticsPlugin().environment.getBrowserId() || '';
129
}

packages/analytics-core/src/browser.ts

Lines changed: 0 additions & 5 deletions
This file was deleted.

0 commit comments

Comments
 (0)