Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/toolbar/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"@codemirror/view": "^6.38.8",
"@launchpad-ui/components": "^0.17.7",
"@launchpad-ui/tokens": "^0.15.1",
"@launchdarkly/session-replay": "^0.4.9",
"@lezer/highlight": "^1.2.3",
"@react-aria/focus": "^3.21.2",
"@react-stately/flags": "^3.1.2",
Expand Down
64 changes: 56 additions & 8 deletions packages/toolbar/src/core/tests/InternalClientProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,35 @@ const mockLDClient = {

const mockInitialize = vi.fn();

// Mock Session Replay
const mockLDRecord = {
start: vi.fn(),
stop: vi.fn(),
};

// Create a proper mock class for SessionReplay
class MockSessionReplay {
options: { manualStart: boolean; privacySetting: string };

constructor(options?: { manualStart?: boolean; privacySetting?: string }) {
this.options = {
manualStart: options?.manualStart ?? true,
privacySetting: options?.privacySetting ?? 'default',
};
}
}

// Mock the SDK module
vi.mock('launchdarkly-js-client-sdk', () => ({
initialize: mockInitialize,
}));

// Mock the Session Replay module
vi.mock('@launchdarkly/session-replay', () => ({
default: MockSessionReplay,
LDRecord: mockLDRecord,
}));

import {
InternalClientProvider,
useInternalClient,
Expand Down Expand Up @@ -61,14 +85,19 @@ describe('InternalClientProvider', () => {
// Reset all mock functions to default behavior
mockLDClient.waitForInitialization.mockResolvedValue(undefined);
mockLDClient.identify.mockResolvedValue(undefined);
mockLDClient.variation.mockReturnValue(true);
// Return false for session replay flag by default to prevent it from starting
mockLDClient.variation.mockReturnValue(false);
mockLDClient.close.mockImplementation(() => {});
mockLDClient.on.mockImplementation(() => {});
mockLDClient.off.mockImplementation(() => {});
mockLDClient.track.mockImplementation(() => {});

mockInitialize.mockReturnValue(mockLDClient);

// Clear Session Replay mocks
mockLDRecord.start.mockClear();
mockLDRecord.stop.mockClear();

// Clear the internal client singleton
setToolbarFlagClient(null);

Expand Down Expand Up @@ -130,7 +159,9 @@ describe('InternalClientProvider', () => {
key: 'toolbar-anonymous',
anonymous: true,
},
undefined,
expect.objectContaining({
observabilityPlugins: expect.any(Array),
}),
);
});
});
Expand All @@ -149,7 +180,13 @@ describe('InternalClientProvider', () => {
);

await waitFor(() => {
expect(mockInitialize).toHaveBeenCalledWith('test-client-id-123', customContext, undefined);
expect(mockInitialize).toHaveBeenCalledWith(
'test-client-id-123',
customContext,
expect.objectContaining({
observabilityPlugins: expect.any(Array),
}),
);
});
});

Expand Down Expand Up @@ -203,21 +240,32 @@ describe('InternalClientProvider', () => {
);

await waitFor(() => {
expect(mockInitialize).toHaveBeenCalledWith('test-client-id-123', expect.any(Object), {
baseUrl: 'https://app.ld.catamorphic.com',
});
expect(mockInitialize).toHaveBeenCalledWith(
'test-client-id-123',
expect.any(Object),
expect.objectContaining({
baseUrl: 'https://app.ld.catamorphic.com',
observabilityPlugins: expect.any(Array),
}),
);
});
});

test('does not provide options when baseUrl is not specified', async () => {
test('includes observabilityPlugins even when baseUrl is not specified', async () => {
render(
<InternalClientProvider clientSideId="test-client-id-123">
<TestConsumer />
</InternalClientProvider>,
);

await waitFor(() => {
expect(mockInitialize).toHaveBeenCalledWith('test-client-id-123', expect.any(Object), undefined);
expect(mockInitialize).toHaveBeenCalledWith(
'test-client-id-123',
expect.any(Object),
expect.objectContaining({
observabilityPlugins: expect.any(Array),
}),
);
});
});
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import type { LDClient, LDContext } from 'launchdarkly-js-client-sdk';
import { setToolbarFlagClient } from '../../../../flags/createToolbarFlagFunction';
import { enableSessionReplay } from '../../../../flags/toolbarFlags';

export interface AuthState {
authenticated: boolean;
Expand Down Expand Up @@ -97,7 +98,10 @@ export function InternalClientProvider({
setLoading(true);
setError(null);

const { initialize } = await import('launchdarkly-js-client-sdk');
const [{ initialize }, SessionReplay] = await Promise.all([
import('launchdarkly-js-client-sdk'),
import('@launchdarkly/session-replay').then((m) => m.default),
]);

const context = initialContext || {
kind: 'user',
Expand All @@ -112,8 +116,23 @@ export function InternalClientProvider({
...(baseUrl && { baseUrl }),
...(streamUrl && { streamUrl }),
...(eventsUrl && { eventsUrl }),
// Add Session Replay plugin with manual start
observabilityPlugins: [
new SessionReplay({
manualStart: true,
privacySetting: 'default',
}),
],
}
: undefined;
: {
// Add Session Replay plugin with manual start
observabilityPlugins: [
new SessionReplay({
manualStart: true,
privacySetting: 'default',
}),
],
};
Comment on lines +119 to +135
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit, non blocking: we can simplify this so we dont have branching!

const sessionReplayPlugin = new SessionReplay({
  manualStart: true,
  privacySetting: 'default',
});

const options = {
  ...(baseUrl && { baseUrl }),
  ...(streamUrl && { streamUrl }),
  ...(eventsUrl && { eventsUrl }),
  observabilityPlugins: [sessionReplayPlugin],
};


const ldClient = initialize(clientSideId, context, options);
clientToCleanup = ldClient;
Expand Down Expand Up @@ -149,6 +168,46 @@ export function InternalClientProvider({
};
}, [clientSideId, initialContext, baseUrl, streamUrl, eventsUrl]); // Re-initialize if any config changes

// Monitor Session Replay flag and start/stop recording accordingly
useEffect(() => {
if (!client) {
return;
}

const checkAndUpdateSessionReplay = async () => {
try {
const shouldEnableReplay = enableSessionReplay();

if (shouldEnableReplay) {
const { LDRecord } = await import('@launchdarkly/session-replay');
LDRecord.start({ forceNew: false, silent: false });
console.log('[InternalClientProvider] Session Replay started');
} else {
const { LDRecord } = await import('@launchdarkly/session-replay');
LDRecord.stop();
console.log('[InternalClientProvider] Session Replay stopped');
}
} catch (err) {
console.error('[InternalClientProvider] Failed to control Session Replay:', err);
}
};

// Check initial state
checkAndUpdateSessionReplay();

// Listen for flag changes
const flagKey = 'toolbar-enable-session-replay';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could be a constant, i see this used in packages/toolbar/src/flags/toolbarFlags.ts

const handleFlagChange = () => {
checkAndUpdateSessionReplay();
};

client.on(`change:${flagKey}`, handleFlagChange);

return () => {
client.off(`change:${flagKey}`, handleFlagChange);
};
}, [client]);

const value: InternalClientContextValue = {
client,
loading,
Expand Down
7 changes: 5 additions & 2 deletions packages/toolbar/src/flags/toolbarFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@ import { createToolbarFlagFunction } from './createToolbarFlagFunction';
* export const myFeature = createToolbarFlagFunction('my-feature-key', defaultValue);
*/

// Placeholder - remove once real toolbar flags are added
export const __placeholder = createToolbarFlagFunction('__placeholder', false);
/**
* Controls whether Session Replay is enabled for the toolbar.
* When enabled, Session Replay will record and send session data to LaunchDarkly.
*/
export const enableSessionReplay = createToolbarFlagFunction('toolbar-enable-session-replay', false);
37 changes: 37 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading