From 6a582fc40e1d63f84cacf445e5af0508672f16bb Mon Sep 17 00:00:00 2001 From: Corey Psoinos Date: Thu, 2 Jan 2025 13:38:16 -0500 Subject: [PATCH 1/8] feat(heap): update browser destination code to load heap js v5 script --- .../destinations/heap/src/generated-types.ts | 6 +- .../destinations/heap/src/index.ts | 38 ++++++---- .../destinations/heap/src/init-script.ts | 69 +++++++++++++++++++ .../destinations/heap/src/test-utilities.ts | 1 + .../destinations/heap/src/types.ts | 32 ++++++++- 5 files changed, 130 insertions(+), 16 deletions(-) create mode 100644 packages/browser-destinations/destinations/heap/src/init-script.ts diff --git a/packages/browser-destinations/destinations/heap/src/generated-types.ts b/packages/browser-destinations/destinations/heap/src/generated-types.ts index 70f8bdb0c5..2caea905c7 100644 --- a/packages/browser-destinations/destinations/heap/src/generated-types.ts +++ b/packages/browser-destinations/destinations/heap/src/generated-types.ts @@ -14,9 +14,13 @@ export interface Settings { */ secureCookie?: boolean /** - * This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap). + * This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap). This field is deprecated in favor of "ingestServer". */ trackingServer?: string + /** + * This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/web#ingestserver). + */ + ingestServer?: string /** * This is an optional setting used to set the host that loads heap-js. This setting is used when heapJS is self-hosted. In most cased this should be left unset. The hostname should not contain https or app id it will be populated like so: https://${hostname}/js/heap-${appId}.js. For more information visit the heap [docs page](https://developers.heap.io/docs/self-hosting-heapjs). */ diff --git a/packages/browser-destinations/destinations/heap/src/index.ts b/packages/browser-destinations/destinations/heap/src/index.ts index 6f03e1f921..16c4073f9a 100644 --- a/packages/browser-destinations/destinations/heap/src/index.ts +++ b/packages/browser-destinations/destinations/heap/src/index.ts @@ -1,15 +1,17 @@ import type { Settings } from './generated-types' import type { BrowserDestinationDefinition } from '@segment/browser-destination-runtime/types' import { browserDestination } from '@segment/browser-destination-runtime/shim' -import { HeapApi, UserConfig } from './types' +import type { HeapApi, HeapMethods, UserConfig } from './types' import { defaultValues } from '@segment/actions-core' import trackEvent from './trackEvent' import identifyUser from './identifyUser' +import { initScript } from './init-script' import { isDefined } from './utils' declare global { interface Window { - heap: HeapApi + heapReadyCb: Array<{ name: HeapMethods; fn: () => void }> + heap: Record void> & HeapApi } } @@ -58,9 +60,16 @@ export const destination: BrowserDestinationDefinition = { required: false }, trackingServer: { - label: 'Tracking Server', + label: 'Tracking Server (deprecated)', description: - 'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap).', + 'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap). This field is deprecated in favor of "ingestServer".', + type: 'string', + required: false + }, + ingestServer: { + label: 'Ingest Server', + description: + 'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/web#ingestserver).', type: 'string', required: false }, @@ -89,24 +98,25 @@ export const destination: BrowserDestinationDefinition = { disableTextCapture: settings.disableTextCapture || false, secureCookie: settings.secureCookie || false } - - if (settings.trackingServer) { - config.trackingServer = settings.trackingServer + if (settings.ingestServer) { + config.ingestServer = settings.ingestServer } - // heap.appid and heap.config must be set before loading heap.js. - window.heap = window.heap || [] - window.heap.appid = settings.appId - window.heap.config = config + initScript(settings.appId, config) if (isDefined(settings.hostname)) { - await deps.loadScript(`https://${settings.hostname}/js/heap-${settings.appId}.js`) + try { + await deps.loadScript(`https://${settings.hostname}/config/${settings.appId}/heap_config.js`) + } catch { + // fall back to loading from Heap's CDN if self-hosted script is not found + await deps.loadScript(`https://cdn.us.heap-api.com/config/${settings.appId}/heap_config.js`) + } } else { - await deps.loadScript(`https://cdn.heapanalytics.com/js/heap-${settings.appId}.js`) + await deps.loadScript(`https://cdn.us.heap-api.com/config/${settings.appId}/heap_config.js`) } // Explained here: https://stackoverflow.com/questions/14859058/why-does-the-segment-io-loader-script-push-method-names-args-onto-a-queue-which - await deps.resolveWhen(() => Object.prototype.hasOwnProperty.call(window, 'heap'), 100) + await deps.resolveWhen(() => window.heap.loaded === true, 300) return window.heap }, diff --git a/packages/browser-destinations/destinations/heap/src/init-script.ts b/packages/browser-destinations/destinations/heap/src/init-script.ts new file mode 100644 index 0000000000..34f20b9b59 --- /dev/null +++ b/packages/browser-destinations/destinations/heap/src/init-script.ts @@ -0,0 +1,69 @@ +import type { HeapMethods, UserConfig } from './types' + +/** + * Initialize the Heap script with the provided environment ID and configuration. + */ +export const initScript = (envId: string, config: UserConfig) => { + // Ensure heapReadyCb exists on the window object + window.heapReadyCb = window.heapReadyCb || [] + + // Ensure heap exists on the window object + window.heap = window.heap || ({} as any) + + window.heap.load = function ( + envId: string, + clientConfig: UserConfig = { disableTextCapture: false, secureCookie: false } + ): void { + window.heap.envId = envId + window.heap.clientConfig = clientConfig + window.heap.clientConfig.shouldFetchServerConfig = false + + // Define all Heap API methods and add them to the heap object + const methods: HeapMethods[] = [ + 'init', + 'startTracking', + 'stopTracking', + 'track', + 'resetIdentity', + 'identify', + 'identifyHashed', + 'getSessionId', + 'getUserId', + 'getIdentity', + 'addUserProperties', + 'addEventProperties', + 'removeEventProperty', + 'clearEventProperties', + 'addAccountProperties', + 'addAdapter', + 'addTransformer', + 'addTransformerFn', + 'onReady', + 'addPageviewProperties', + 'removePageviewProperty', + 'clearPageviewProperties', + 'trackPageview' + ] + + const createMethodProxy = (methodName: HeapMethods) => { + return function (...args: any[]) { + // Push method calls to heapReadyCb until the script is fully loaded + window.heapReadyCb.push({ + name: methodName, + fn: () => { + if (window.heap[methodName]) { + window.heap[methodName](...args) + } + } + }) + } + } + + // Proxy all methods to heap + for (const method of methods) { + window.heap[method] = createMethodProxy(method) + } + } + + window.heap.load(envId, config) +} diff --git a/packages/browser-destinations/destinations/heap/src/test-utilities.ts b/packages/browser-destinations/destinations/heap/src/test-utilities.ts index 1f9f03ae09..f8367604ec 100644 --- a/packages/browser-destinations/destinations/heap/src/test-utilities.ts +++ b/packages/browser-destinations/destinations/heap/src/test-utilities.ts @@ -7,6 +7,7 @@ export const HEAP_TEST_ENV_ID = '1' export const createMockedHeapJsSdk = (): HeapApi => { return { appid: HEAP_TEST_ENV_ID, + envId: HEAP_TEST_ENV_ID, config: { disableTextCapture: true, secureCookie: true diff --git a/packages/browser-destinations/destinations/heap/src/types.ts b/packages/browser-destinations/destinations/heap/src/types.ts index 05b9014b8a..d5dd4cc439 100644 --- a/packages/browser-destinations/destinations/heap/src/types.ts +++ b/packages/browser-destinations/destinations/heap/src/types.ts @@ -1,5 +1,6 @@ export type UserConfig = { trackingServer?: string + ingestServer?: string disableTextCapture: boolean secureCookie: boolean } @@ -14,9 +15,38 @@ type EventProperties = { export type HeapApi = { appid: string + envId: string track: (eventName: string, eventProperties: EventProperties, library?: string) => void - load: () => void + load: (envId: string, clientConfig?: UserConfig) => void + loaded?: boolean config: UserConfig + clientConfig?: Partial & { shouldFetchServerConfig?: boolean } identify: (identity: string) => void addUserProperties: (properties: UserProperties) => void } + +// Define types for Heap methods +export type HeapMethods = + | 'init' + | 'startTracking' + | 'stopTracking' + | 'track' + | 'resetIdentity' + | 'identify' + | 'identifyHashed' + | 'getSessionId' + | 'getUserId' + | 'getIdentity' + | 'addUserProperties' + | 'addEventProperties' + | 'removeEventProperty' + | 'clearEventProperties' + | 'addAccountProperties' + | 'addAdapter' + | 'addTransformer' + | 'addTransformerFn' + | 'onReady' + | 'addPageviewProperties' + | 'removePageviewProperty' + | 'clearPageviewProperties' + | 'trackPageview' From 94674eb692240723c800b710c579b431b5bb45a5 Mon Sep 17 00:00:00 2001 From: Corey Psoinos Date: Thu, 2 Jan 2025 14:39:48 -0500 Subject: [PATCH 2/8] remove try/catch fallback for self-hosted --- .../browser-destinations/destinations/heap/src/index.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/packages/browser-destinations/destinations/heap/src/index.ts b/packages/browser-destinations/destinations/heap/src/index.ts index 16c4073f9a..d9c2f77fca 100644 --- a/packages/browser-destinations/destinations/heap/src/index.ts +++ b/packages/browser-destinations/destinations/heap/src/index.ts @@ -105,12 +105,7 @@ export const destination: BrowserDestinationDefinition = { initScript(settings.appId, config) if (isDefined(settings.hostname)) { - try { - await deps.loadScript(`https://${settings.hostname}/config/${settings.appId}/heap_config.js`) - } catch { - // fall back to loading from Heap's CDN if self-hosted script is not found - await deps.loadScript(`https://cdn.us.heap-api.com/config/${settings.appId}/heap_config.js`) - } + await deps.loadScript(`https://${settings.hostname}/config/${settings.appId}/heap_config.js`) } else { await deps.loadScript(`https://cdn.us.heap-api.com/config/${settings.appId}/heap_config.js`) } From a66aaa3c1661dd7d9c36bcfcc10cb6d6af62e250 Mon Sep 17 00:00:00 2001 From: Corey Psoinos Date: Thu, 2 Jan 2025 16:22:27 -0500 Subject: [PATCH 3/8] update tests --- .../__tests__/__snapshots__/index.test.ts.snap | 18 ++++++++++++++++++ .../heap/src/__tests__/index.test.ts | 10 +++++----- .../destinations/heap/src/test-utilities.ts | 6 +----- 3 files changed, 24 insertions(+), 10 deletions(-) create mode 100644 packages/browser-destinations/destinations/heap/src/__tests__/__snapshots__/index.test.ts.snap diff --git a/packages/browser-destinations/destinations/heap/src/__tests__/__snapshots__/index.test.ts.snap b/packages/browser-destinations/destinations/heap/src/__tests__/__snapshots__/index.test.ts.snap new file mode 100644 index 0000000000..8348373ffc --- /dev/null +++ b/packages/browser-destinations/destinations/heap/src/__tests__/__snapshots__/index.test.ts.snap @@ -0,0 +1,18 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Heap loading 1`] = ` +NodeList [ + , +] +`; diff --git a/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts b/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts index 3153c7c418..ba04dd2e12 100644 --- a/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts +++ b/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts @@ -1,6 +1,6 @@ import { Analytics, Context } from '@segment/analytics-next' import heapDestination, { destination } from '../index' -import { HEAP_TEST_ENV_ID, mockHeapJsHttpRequest } from '../test-utilities' +import { HEAP_TEST_ENV_ID } from '../test-utilities' const subscriptions = [ { @@ -16,19 +16,19 @@ describe('Heap', () => { test('loading', async () => { jest.spyOn(destination, 'initialize') - mockHeapJsHttpRequest() - const [event] = await heapDestination({ appId: HEAP_TEST_ENV_ID, subscriptions }) await event.load(Context.system(), {} as Analytics) expect(destination.initialize).toHaveBeenCalled() expect(window.heap.appid).toEqual(HEAP_TEST_ENV_ID) + + const scripts = window.document.querySelectorAll('script') + expect(scripts).toMatchSnapshot() }) + test('loading with cdn', async () => { jest.spyOn(destination, 'initialize') - mockHeapJsHttpRequest() - const [event] = await heapDestination({ appId: HEAP_TEST_ENV_ID, subscriptions, diff --git a/packages/browser-destinations/destinations/heap/src/test-utilities.ts b/packages/browser-destinations/destinations/heap/src/test-utilities.ts index f8367604ec..0cdb949390 100644 --- a/packages/browser-destinations/destinations/heap/src/test-utilities.ts +++ b/packages/browser-destinations/destinations/heap/src/test-utilities.ts @@ -1,6 +1,5 @@ import { HeapApi } from './types' import { Subscription } from '@segment/browser-destination-runtime/types' -import nock from 'nock' export const HEAP_TEST_ENV_ID = '1' @@ -18,6 +17,7 @@ export const createMockedHeapJsSdk = (): HeapApi => { addUserProperties: jest.fn() } } + export const trackEventSubscription: Subscription = { partnerAction: 'trackEvent', name: 'Track Event', @@ -59,7 +59,3 @@ export const identifyUserSubscription: Subscription = { } } } - -export const mockHeapJsHttpRequest = (): void => { - nock('https://cdn.heapanalytics.com').get(`/js/heap-${HEAP_TEST_ENV_ID}.js`).reply(200, {}) -} From de3accc331c339c463f5a9cd3d01d8bf2b4ec544 Mon Sep 17 00:00:00 2001 From: Corey Psoinos Date: Fri, 3 Jan 2025 09:50:43 -0500 Subject: [PATCH 4/8] fix tests --- .../destinations/heap/src/index.ts | 2 +- .../destinations/heap/src/test-utilities.ts | 34 ++++++++++++++++--- .../destinations/heap/src/types.ts | 2 +- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/packages/browser-destinations/destinations/heap/src/index.ts b/packages/browser-destinations/destinations/heap/src/index.ts index d9c2f77fca..01f1ae1807 100644 --- a/packages/browser-destinations/destinations/heap/src/index.ts +++ b/packages/browser-destinations/destinations/heap/src/index.ts @@ -11,7 +11,7 @@ import { isDefined } from './utils' declare global { interface Window { heapReadyCb: Array<{ name: HeapMethods; fn: () => void }> - heap: Record void> & HeapApi + heap: HeapApi } } diff --git a/packages/browser-destinations/destinations/heap/src/test-utilities.ts b/packages/browser-destinations/destinations/heap/src/test-utilities.ts index 0cdb949390..4794f74a4e 100644 --- a/packages/browser-destinations/destinations/heap/src/test-utilities.ts +++ b/packages/browser-destinations/destinations/heap/src/test-utilities.ts @@ -1,5 +1,5 @@ -import { HeapApi } from './types' -import { Subscription } from '@segment/browser-destination-runtime/types' +import type { HeapApi } from './types' +import nock from 'nock' export const HEAP_TEST_ENV_ID = '1' @@ -14,11 +14,31 @@ export const createMockedHeapJsSdk = (): HeapApi => { load: jest.fn(), track: jest.fn(), identify: jest.fn(), - addUserProperties: jest.fn() + addUserProperties: jest.fn(), + init: jest.fn(), + startTracking: jest.fn(), + stopTracking: jest.fn(), + resetIdentity: jest.fn(), + identifyHashed: jest.fn(), + getSessionId: jest.fn(), + getUserId: jest.fn(), + getIdentity: jest.fn(), + addEventProperties: jest.fn(), + removeEventProperty: jest.fn(), + clearEventProperties: jest.fn(), + addAccountProperties: jest.fn(), + addAdapter: jest.fn(), + addTransformer: jest.fn(), + addTransformerFn: jest.fn(), + onReady: jest.fn(), + addPageviewProperties: jest.fn(), + removePageviewProperty: jest.fn(), + clearPageviewProperties: jest.fn(), + trackPageview: jest.fn() } } -export const trackEventSubscription: Subscription = { +export const trackEventSubscription = { partnerAction: 'trackEvent', name: 'Track Event', enabled: true, @@ -42,7 +62,7 @@ export const trackEventSubscription: Subscription = { } } -export const identifyUserSubscription: Subscription = { +export const identifyUserSubscription = { partnerAction: 'identifyUser', name: 'Identify User', enabled: true, @@ -59,3 +79,7 @@ export const identifyUserSubscription: Subscription = { } } } + +export const mockHeapJsHttpRequest = (): void => { + nock('https://cdn.heapanalytics.com').get(`/js/heap-${HEAP_TEST_ENV_ID}.js`).reply(200, {}) +} diff --git a/packages/browser-destinations/destinations/heap/src/types.ts b/packages/browser-destinations/destinations/heap/src/types.ts index d5dd4cc439..92d2854095 100644 --- a/packages/browser-destinations/destinations/heap/src/types.ts +++ b/packages/browser-destinations/destinations/heap/src/types.ts @@ -13,7 +13,7 @@ type EventProperties = { [key: string]: unknown } -export type HeapApi = { +export type HeapApi = Record void> & { appid: string envId: string track: (eventName: string, eventProperties: EventProperties, library?: string) => void From 0eb2f6a06818708c6128b1dafe8aeaca2d730f73 Mon Sep 17 00:00:00 2001 From: Corey Psoinos Date: Fri, 3 Jan 2025 09:58:15 -0500 Subject: [PATCH 5/8] apply deprecated trackingServer config value for backward compatibility --- .../browser-destinations/destinations/heap/src/index.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/browser-destinations/destinations/heap/src/index.ts b/packages/browser-destinations/destinations/heap/src/index.ts index 01f1ae1807..a795e5450a 100644 --- a/packages/browser-destinations/destinations/heap/src/index.ts +++ b/packages/browser-destinations/destinations/heap/src/index.ts @@ -96,10 +96,10 @@ export const destination: BrowserDestinationDefinition = { const config: UserConfig = { disableTextCapture: settings.disableTextCapture || false, - secureCookie: settings.secureCookie || false - } - if (settings.ingestServer) { - config.ingestServer = settings.ingestServer + secureCookie: settings.secureCookie || false, + ...(settings.ingestServer && { ingestServer: settings.ingestServer }), + // For backward compatibility. See https://developers.heap.io/docs/web#ingestserver + ...(settings.trackingServer && { trackingServer: settings.trackingServer }) } initScript(settings.appId, config) From 4a697751cbe0627de77cac4ad52766b6f28b50c5 Mon Sep 17 00:00:00 2001 From: Corey Psoinos Date: Fri, 3 Jan 2025 10:16:48 -0500 Subject: [PATCH 6/8] remove non-functional script loading mock --- .../heap/src/identifyUser/__tests__/index.test.ts | 10 +--------- .../destinations/heap/src/test-utilities.ts | 5 ----- .../heap/src/trackEvent/__tests__/index.test.ts | 8 +------- 3 files changed, 2 insertions(+), 21 deletions(-) diff --git a/packages/browser-destinations/destinations/heap/src/identifyUser/__tests__/index.test.ts b/packages/browser-destinations/destinations/heap/src/identifyUser/__tests__/index.test.ts index 5e23b8589f..be78d96e2e 100644 --- a/packages/browser-destinations/destinations/heap/src/identifyUser/__tests__/index.test.ts +++ b/packages/browser-destinations/destinations/heap/src/identifyUser/__tests__/index.test.ts @@ -1,15 +1,9 @@ import { Analytics, Context } from '@segment/analytics-next' -import { - createMockedHeapJsSdk, - HEAP_TEST_ENV_ID, - identifyUserSubscription, - mockHeapJsHttpRequest -} from '../../test-utilities' +import { createMockedHeapJsSdk, HEAP_TEST_ENV_ID, identifyUserSubscription } from '../../test-utilities' import heapDestination from '../../index' describe('#identify', () => { it('should not call identify if user id is not provided and anonymous user id is provided', async () => { - mockHeapJsHttpRequest() window.heap = createMockedHeapJsSdk() const [identifyUser] = await heapDestination({ appId: HEAP_TEST_ENV_ID, subscriptions: [identifyUserSubscription] }) @@ -31,7 +25,6 @@ describe('#identify', () => { }) it('should call identify if user id is provided', async () => { - mockHeapJsHttpRequest() window.heap = createMockedHeapJsSdk() const [identifyUser] = await heapDestination({ appId: HEAP_TEST_ENV_ID, subscriptions: [identifyUserSubscription] }) @@ -53,7 +46,6 @@ describe('#identify', () => { }) it('should call addUserProprties if traits are provided', async () => { - mockHeapJsHttpRequest() window.heap = createMockedHeapJsSdk() const [identifyUser] = await heapDestination({ appId: HEAP_TEST_ENV_ID, subscriptions: [identifyUserSubscription] }) diff --git a/packages/browser-destinations/destinations/heap/src/test-utilities.ts b/packages/browser-destinations/destinations/heap/src/test-utilities.ts index 4794f74a4e..e7d5801201 100644 --- a/packages/browser-destinations/destinations/heap/src/test-utilities.ts +++ b/packages/browser-destinations/destinations/heap/src/test-utilities.ts @@ -1,5 +1,4 @@ import type { HeapApi } from './types' -import nock from 'nock' export const HEAP_TEST_ENV_ID = '1' @@ -79,7 +78,3 @@ export const identifyUserSubscription = { } } } - -export const mockHeapJsHttpRequest = (): void => { - nock('https://cdn.heapanalytics.com').get(`/js/heap-${HEAP_TEST_ENV_ID}.js`).reply(200, {}) -} diff --git a/packages/browser-destinations/destinations/heap/src/trackEvent/__tests__/index.test.ts b/packages/browser-destinations/destinations/heap/src/trackEvent/__tests__/index.test.ts index d7ead7d208..f6f1a24fb1 100644 --- a/packages/browser-destinations/destinations/heap/src/trackEvent/__tests__/index.test.ts +++ b/packages/browser-destinations/destinations/heap/src/trackEvent/__tests__/index.test.ts @@ -1,11 +1,6 @@ import { Analytics, Context, Plugin } from '@segment/analytics-next' import heapDestination from '../../index' -import { - createMockedHeapJsSdk, - HEAP_TEST_ENV_ID, - mockHeapJsHttpRequest, - trackEventSubscription -} from '../../test-utilities' +import { createMockedHeapJsSdk, HEAP_TEST_ENV_ID, trackEventSubscription } from '../../test-utilities' import { HEAP_SEGMENT_BROWSER_LIBRARY_NAME } from '../../constants' describe('#trackEvent', () => { @@ -16,7 +11,6 @@ describe('#trackEvent', () => { let identifySpy: jest.SpyInstance beforeAll(async () => { - mockHeapJsHttpRequest() window.heap = createMockedHeapJsSdk() eventWithUnrolling = ( From a94703608c5867ace03c49200999b0c686135ac1 Mon Sep 17 00:00:00 2001 From: Corey Psoinos Date: Fri, 3 Jan 2025 12:42:50 -0500 Subject: [PATCH 7/8] better backward compatibility with hjsv4 --- .../__snapshots__/index.test.ts.snap | 18 -------- .../heap/src/__tests__/index.test.ts | 45 +++++++++++++++++-- .../destinations/heap/src/generated-types.ts | 10 ++--- .../destinations/heap/src/index.ts | 21 ++++++--- .../destinations/heap/src/init-script.ts | 1 + 5 files changed, 61 insertions(+), 34 deletions(-) delete mode 100644 packages/browser-destinations/destinations/heap/src/__tests__/__snapshots__/index.test.ts.snap diff --git a/packages/browser-destinations/destinations/heap/src/__tests__/__snapshots__/index.test.ts.snap b/packages/browser-destinations/destinations/heap/src/__tests__/__snapshots__/index.test.ts.snap deleted file mode 100644 index 8348373ffc..0000000000 --- a/packages/browser-destinations/destinations/heap/src/__tests__/__snapshots__/index.test.ts.snap +++ /dev/null @@ -1,18 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Heap loading 1`] = ` -NodeList [ - , -] -`; diff --git a/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts b/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts index ba04dd2e12..1c29ce5197 100644 --- a/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts +++ b/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts @@ -1,6 +1,11 @@ import { Analytics, Context } from '@segment/analytics-next' import heapDestination, { destination } from '../index' import { HEAP_TEST_ENV_ID } from '../test-utilities' +import { loadScript } from '@segment/browser-destination-runtime/load-script' +import { resolveWhen } from '@segment/browser-destination-runtime/resolve-when' + +jest.mock('@segment/browser-destination-runtime/load-script') +jest.mock('@segment/browser-destination-runtime/resolve-when') const subscriptions = [ { @@ -13,20 +18,34 @@ const subscriptions = [ ] describe('Heap', () => { + beforeAll(() => { + ;(loadScript as jest.Mock).mockResolvedValue(true) + ;(resolveWhen as jest.Mock).mockResolvedValue(true) + }) + + beforeEach(() => { + // Reset global state + // @ts-expect-error + delete window.heap + }) + + afterEach(async () => { + jest.clearAllMocks() + }) + test('loading', async () => { jest.spyOn(destination, 'initialize') const [event] = await heapDestination({ appId: HEAP_TEST_ENV_ID, subscriptions }) await event.load(Context.system(), {} as Analytics) + expect(destination.initialize).toHaveBeenCalled() expect(window.heap.appid).toEqual(HEAP_TEST_ENV_ID) - - const scripts = window.document.querySelectorAll('script') - expect(scripts).toMatchSnapshot() + expect(loadScript).toHaveBeenCalledWith(`https://cdn.us.heap-api.com/config/${HEAP_TEST_ENV_ID}/heap_config.js`) }) - test('loading with cdn', async () => { + test('loading classic SDK with custom hostname', async () => { jest.spyOn(destination, 'initialize') const [event] = await heapDestination({ @@ -37,7 +56,25 @@ describe('Heap', () => { }) await event.load(Context.system(), {} as Analytics) + + expect(destination.initialize).toHaveBeenCalled() + expect(window.heap.appid).toEqual(HEAP_TEST_ENV_ID) + expect(loadScript).toHaveBeenCalledWith(`https://cdn.heapanalytics.com/js/heap-${HEAP_TEST_ENV_ID}.js`) + }) + + test('loading latest SDK with custom hostname', async () => { + jest.spyOn(destination, 'initialize') + + const [event] = await heapDestination({ + appId: HEAP_TEST_ENV_ID, + subscriptions, + hostname: 'cdn.heapanalytics.com' + }) + + await event.load(Context.system(), {} as Analytics) + expect(destination.initialize).toHaveBeenCalled() expect(window.heap.appid).toEqual(HEAP_TEST_ENV_ID) + expect(loadScript).toHaveBeenCalledWith(`https://cdn.heapanalytics.com/config/${HEAP_TEST_ENV_ID}/heap_config.js`) }) }) diff --git a/packages/browser-destinations/destinations/heap/src/generated-types.ts b/packages/browser-destinations/destinations/heap/src/generated-types.ts index 2caea905c7..25c4454185 100644 --- a/packages/browser-destinations/destinations/heap/src/generated-types.ts +++ b/packages/browser-destinations/destinations/heap/src/generated-types.ts @@ -6,23 +6,23 @@ export interface Settings { */ appId: string /** - * Setting to true will redact all target text on your website. For more information visit the heap [docs page](https://developers.heap.io/docs/web#global-data-redaction-via-disabling-text-capture). + * Setting to true will redact all target text on your website. For more information visit the Heap [docs page](https://developers.heap.io/docs/web#global-data-redaction-via-disabling-text-capture). */ disableTextCapture?: boolean /** - * This option is turned off by default to accommodate websites not served over HTTPS. If your application uses HTTPS, we recommend enabling secure cookies to prevent Heap cookies from being observed by unauthorized parties. For more information visit the heap [docs page](https://developers.heap.io/docs/web#securecookie). + * This option is turned off by default to accommodate websites not served over HTTPS. If your application uses HTTPS, we recommend enabling secure cookies to prevent Heap cookies from being observed by unauthorized parties. For more information visit the Heap [docs page](https://developers.heap.io/docs/web#securecookie). */ secureCookie?: boolean /** - * This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap). This field is deprecated in favor of "ingestServer". + * This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the Heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap). This field is deprecated in favor of `ingestServer`. If `trackingServer` is set and `ingestServer` is not set, then the Classic SDK will be loaded. If both are set, `ingestServer` will take precedence, and the latest stable version of the Heap SDK will be loaded. */ trackingServer?: string /** - * This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/web#ingestserver). + * This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the Heap [docs page](https://developers.heap.io/docs/web#ingestserver). */ ingestServer?: string /** - * This is an optional setting used to set the host that loads heap-js. This setting is used when heapJS is self-hosted. In most cased this should be left unset. The hostname should not contain https or app id it will be populated like so: https://${hostname}/js/heap-${appId}.js. For more information visit the heap [docs page](https://developers.heap.io/docs/self-hosting-heapjs). + * This is an optional setting used to set the host that loads the Heap SDK. This setting is used when the Heap SDK is self-hosted. In most cased this should be left unset. The hostname should not contain https or app id. When _both_ `hostname` and `trackingServer` are set, the Classic SDK will be loaded via: `https://${hostname}/js/heap-${appId}.js`. If `hostname` is set and `trackingServer` is not set, then the latest version of the Heap SDK will be loaded via: `https://${settings.hostname}/config/${settings.appId}/heap_config.js`. For more information visit the Heap [docs page](https://developers.heap.io/docs/self-hosting-heapjs). */ hostname?: string /** diff --git a/packages/browser-destinations/destinations/heap/src/index.ts b/packages/browser-destinations/destinations/heap/src/index.ts index a795e5450a..c81e39f749 100644 --- a/packages/browser-destinations/destinations/heap/src/index.ts +++ b/packages/browser-destinations/destinations/heap/src/index.ts @@ -48,35 +48,35 @@ export const destination: BrowserDestinationDefinition = { disableTextCapture: { label: 'Global data redaction via Disabling Text Capture', description: - 'Setting to true will redact all target text on your website. For more information visit the heap [docs page](https://developers.heap.io/docs/web#global-data-redaction-via-disabling-text-capture).', + 'Setting to true will redact all target text on your website. For more information visit the Heap [docs page](https://developers.heap.io/docs/web#global-data-redaction-via-disabling-text-capture).', type: 'boolean', required: false }, secureCookie: { label: 'Secure Cookie', description: - 'This option is turned off by default to accommodate websites not served over HTTPS. If your application uses HTTPS, we recommend enabling secure cookies to prevent Heap cookies from being observed by unauthorized parties. For more information visit the heap [docs page](https://developers.heap.io/docs/web#securecookie).', + 'This option is turned off by default to accommodate websites not served over HTTPS. If your application uses HTTPS, we recommend enabling secure cookies to prevent Heap cookies from being observed by unauthorized parties. For more information visit the Heap [docs page](https://developers.heap.io/docs/web#securecookie).', type: 'boolean', required: false }, trackingServer: { label: 'Tracking Server (deprecated)', description: - 'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap). This field is deprecated in favor of "ingestServer".', + 'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the Heap [docs page](https://developers.heap.io/docs/set-up-first-party-data-collection-in-heap). This field is deprecated in favor of `ingestServer`. If `trackingServer` is set and `ingestServer` is not set, then the Classic SDK will be loaded. If both are set, `ingestServer` will take precedence, and the latest stable version of the Heap SDK will be loaded.', type: 'string', required: false }, ingestServer: { label: 'Ingest Server', description: - 'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the heap [docs page](https://developers.heap.io/docs/web#ingestserver).', + 'This is an optional setting. This is used to set up first-party data collection. For most cased this should not be set. For more information visit the Heap [docs page](https://developers.heap.io/docs/web#ingestserver).', type: 'string', required: false }, hostname: { label: 'Hostname', description: - 'This is an optional setting used to set the host that loads heap-js. This setting is used when heapJS is self-hosted. In most cased this should be left unset. The hostname should not contain https or app id it will be populated like so: https://${hostname}/js/heap-${appId}.js. For more information visit the heap [docs page](https://developers.heap.io/docs/self-hosting-heapjs).', + 'This is an optional setting used to set the host that loads the Heap SDK. This setting is used when the Heap SDK is self-hosted. In most cased this should be left unset. The hostname should not contain https or app id. When _both_ `hostname` and `trackingServer` are set, the Classic SDK will be loaded via: `https://${hostname}/js/heap-${appId}.js`. If `hostname` is set and `trackingServer` is not set, then the latest version of the Heap SDK will be loaded via: `https://${settings.hostname}/config/${settings.appId}/heap_config.js`. For more information visit the Heap [docs page](https://developers.heap.io/docs/self-hosting-heapjs).', type: 'string', required: false }, @@ -104,9 +104,16 @@ export const destination: BrowserDestinationDefinition = { initScript(settings.appId, config) - if (isDefined(settings.hostname)) { + // if both hostname and trackingServer are set, load classic SDK from hostname + if (isDefined(settings.hostname) && isDefined(settings.trackingServer)) { + await deps.loadScript(`https://${settings.hostname}/js/heap-${settings.appId}.js`) + } + // if only hostname is set, load latest version of SDK from hostname + else if (isDefined(settings.hostname) && !isDefined(settings.trackingServer)) { await deps.loadScript(`https://${settings.hostname}/config/${settings.appId}/heap_config.js`) - } else { + } + // default to loading latest version of SDK from heap CDN + else { await deps.loadScript(`https://cdn.us.heap-api.com/config/${settings.appId}/heap_config.js`) } diff --git a/packages/browser-destinations/destinations/heap/src/init-script.ts b/packages/browser-destinations/destinations/heap/src/init-script.ts index 34f20b9b59..df53196cc8 100644 --- a/packages/browser-destinations/destinations/heap/src/init-script.ts +++ b/packages/browser-destinations/destinations/heap/src/init-script.ts @@ -14,6 +14,7 @@ export const initScript = (envId: string, config: UserConfig) => { envId: string, clientConfig: UserConfig = { disableTextCapture: false, secureCookie: false } ): void { + window.heap.appid = envId window.heap.envId = envId window.heap.clientConfig = clientConfig window.heap.clientConfig.shouldFetchServerConfig = false From 220f8531da4e8b4d1d4e34141b1d3ff0b04809ca Mon Sep 17 00:00:00 2001 From: Corey Psoinos Date: Fri, 3 Jan 2025 14:00:46 -0500 Subject: [PATCH 8/8] assert heap.envId, not heap.appid --- .../destinations/heap/src/__tests__/index.test.ts | 6 +++--- .../destinations/heap/src/init-script.ts | 1 - 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts b/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts index 1c29ce5197..3a19cbc640 100644 --- a/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts +++ b/packages/browser-destinations/destinations/heap/src/__tests__/index.test.ts @@ -41,7 +41,7 @@ describe('Heap', () => { await event.load(Context.system(), {} as Analytics) expect(destination.initialize).toHaveBeenCalled() - expect(window.heap.appid).toEqual(HEAP_TEST_ENV_ID) + expect(window.heap.envId).toEqual(HEAP_TEST_ENV_ID) expect(loadScript).toHaveBeenCalledWith(`https://cdn.us.heap-api.com/config/${HEAP_TEST_ENV_ID}/heap_config.js`) }) @@ -58,7 +58,7 @@ describe('Heap', () => { await event.load(Context.system(), {} as Analytics) expect(destination.initialize).toHaveBeenCalled() - expect(window.heap.appid).toEqual(HEAP_TEST_ENV_ID) + expect(window.heap.envId).toEqual(HEAP_TEST_ENV_ID) expect(loadScript).toHaveBeenCalledWith(`https://cdn.heapanalytics.com/js/heap-${HEAP_TEST_ENV_ID}.js`) }) @@ -74,7 +74,7 @@ describe('Heap', () => { await event.load(Context.system(), {} as Analytics) expect(destination.initialize).toHaveBeenCalled() - expect(window.heap.appid).toEqual(HEAP_TEST_ENV_ID) + expect(window.heap.envId).toEqual(HEAP_TEST_ENV_ID) expect(loadScript).toHaveBeenCalledWith(`https://cdn.heapanalytics.com/config/${HEAP_TEST_ENV_ID}/heap_config.js`) }) }) diff --git a/packages/browser-destinations/destinations/heap/src/init-script.ts b/packages/browser-destinations/destinations/heap/src/init-script.ts index df53196cc8..34f20b9b59 100644 --- a/packages/browser-destinations/destinations/heap/src/init-script.ts +++ b/packages/browser-destinations/destinations/heap/src/init-script.ts @@ -14,7 +14,6 @@ export const initScript = (envId: string, config: UserConfig) => { envId: string, clientConfig: UserConfig = { disableTextCapture: false, secureCookie: false } ): void { - window.heap.appid = envId window.heap.envId = envId window.heap.clientConfig = clientConfig window.heap.clientConfig.shouldFetchServerConfig = false