Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Refactor

Blue Mousee0f5ca4842e8
diff --git a/docs/content/docs/add-script.mdx b/docs/content/docs/add-script.mdx
index 75cc7b77f..48e6bc0e1 100644
--- a/docs/content/docs/add-script.mdx
+++ b/docs/content/docs/add-script.mdx
@@ -49,7 +49,7 @@ It's important to remember to replace `YOUR_PROJECT_ID` with your actual Project
Done. Now you can start using Swetrix on your website.
-To record session replays, start the recorder from your site code after initialising Swetrix. See [`startSessionReplay()`](/swetrix-js-reference#startsessionreplay) for setup and privacy options.
+To record session replays, start the recorder from your site code after initialising Swetrix. The replay recorder is loaded asynchronously only when you preload or start it. See [`startSessionReplay()`](/swetrix-js-reference#startsessionreplay) for setup and privacy options.
</TabsContent>
<TabsContent value="npm">
@@ -85,7 +85,7 @@ Swetrix.init("YOUR_PROJECT_ID");
Swetrix.trackViews();
```
-To record session replays, call `Swetrix.startSessionReplay()` after `Swetrix.init()`. See [`startSessionReplay()`](/swetrix-js-reference#startsessionreplay) for setup and privacy options.
+To record session replays, call `Swetrix.startSessionReplay()` after `Swetrix.init()`. The npm package dynamically imports the installed replay recorder only when you preload or start it. See [`startSessionReplay()`](/swetrix-js-reference#startsessionreplay) for setup and privacy options.
</Step>
</Steps>
diff --git a/docs/content/docs/analytics-dashboard/session-replays.mdx b/docs/content/docs/analytics-dashboard/session-replays.mdx
index 7cafb8d1b..d8331dd54 100644
--- a/docs/content/docs/analytics-dashboard/session-replays.mdx
+++ b/docs/content/docs/analytics-dashboard/session-replays.mdx
@@ -22,7 +22,7 @@ To collect replays, install the Swetrix tracking script as usual, initialise it
```javascript
swetrix.init("YOUR_PROJECT_ID", {
- sessionReplay: true,
+ preloadSessionReplay: true,
});
await swetrix.startSessionReplay({
@@ -30,7 +30,7 @@ await swetrix.startSessionReplay({
});
```
-The optional `sessionReplay: true` setting preloads the replay recorder. Recording still begins only after `startSessionReplay()` is called.
+The optional `preloadSessionReplay: true` setting preloads the replay recorder. Recording still begins only after `startSessionReplay()` is called.
See the [tracking script reference](/swetrix-js-reference#startsessionreplay) for all privacy modes, recorder options, and code examples.
diff --git a/docs/content/docs/script-reference.mdx b/docs/content/docs/script-reference.mdx
index 86444510d..a092d1084 100644
--- a/docs/content/docs/script-reference.mdx
+++ b/docs/content/docs/script-reference.mdx
@@ -25,18 +25,18 @@ swetrix.init("YOUR_PROJECT_ID", {
respectDNT: false,
apiURL: "https://api.swetrix.com/log",
profileId: "user-123",
- sessionReplay: true,
+ preloadSessionReplay: true,
});
```
-| Name | Description | Default value |
-| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- |
-| devMode | When set to `true`, localhost events will be sent to server. | `false` |
-| disabled | When set to true, the tracking library won't send any data to server.<br />Useful for development purposes when this value is set based on '.env' var. | `false` |
-| respectDNT | By setting this flag to true, we will not collect ANY kind of data about the user with the DNT setting. <br />This setting is not true by default because our service anonymises all incoming data and does not pass it on to any third parties under any circumstances. | `false` |
-| apiURL | If you use Swetrix Cloud, you don't need to change this parameter. If you're self-hosting Swetrix CE, you should put the URL of your API instance here, like `[BASE_URL]/backend/v1/log`. | `'https://api.swetrix.com/log'` |
-| profileId | Optional profile ID for long-term user tracking (MAU/DAU). If set, it will be used for all pageviews and events unless overridden per-call. This allows you to track users across sessions and devices. | `undefined` |
-| sessionReplay | Set to `true` to preload the session replay recorder after `init()`, or pass `{ rrwebUrl: "https://example.com/rrweb.min.js" }` to load it from a custom URL. Recording only starts after you call `startSessionReplay()`. | `undefined` |
+| Name | Description | Default value |
+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- |
+| devMode | When set to `true`, localhost events will be sent to server. | `false` |
+| disabled | When set to true, the tracking library won't send any data to server.<br />Useful for development purposes when this value is set based on '.env' var. | `false` |
+| respectDNT | By setting this flag to true, we will not collect ANY kind of data about the user with the DNT setting. <br />This setting is not true by default because our service anonymises all incoming data and does not pass it on to any third parties under any circumstances. | `false` |
+| apiURL | If you use Swetrix Cloud, you don't need to change this parameter. If you're self-hosting Swetrix CE, you should put the URL of your API instance here, like `[BASE_URL]/backend/v1/log`. | `'https://api.swetrix.com/log'` |
+| profileId | Optional profile ID for long-term user tracking (MAU/DAU). If set, it will be used for all pageviews and events unless overridden per-call. This allows you to track users across sessions and devices. | `undefined` |
+| preloadSessionReplay | Set to `true` to preload the session replay recorder after `init()`, or pass `{ rrwebUrl: "https://example.com/rrweb.min.js" }` to load it from a custom URL. Recording only starts after you call `startSessionReplay()`. | `undefined` |
## track()
@@ -246,11 +246,11 @@ This function starts recording the current browser session so you can watch it l
masking settings, consent requirements, and legal basis for collecting this data.
</Callout>
-Call `startSessionReplay()` after `init()`. If you set `sessionReplay: true` in `init()`, Swetrix preloads the recorder first so starting a replay is faster. If you do not preload it, `startSessionReplay()` loads the recorder when it is called.
+Call `startSessionReplay()` after `init()`. If you set `preloadSessionReplay: true` in `init()`, Swetrix preloads the recorder first so starting a replay is faster. If you do not preload it, `startSessionReplay()` loads the recorder when it is called.
```javascript
swetrix.init("YOUR_PROJECT_ID", {
- sessionReplay: true,
+ preloadSessionReplay: true,
});
const replay = await swetrix.startSessionReplay({
@@ -266,7 +266,7 @@ When using the npm package:
import { init, startSessionReplay } from "swetrix";
init("YOUR_PROJECT_ID", {
- sessionReplay: true,
+ preloadSessionReplay: true,
});
const replay = await startSessionReplay({
@@ -274,6 +274,8 @@ const replay = await startSessionReplay({
});
```
+For npm installs, Swetrix dynamically imports the installed `rrweb` package only when the recorder is preloaded or started, so it can be split into an async chunk by your bundler. For script-tag installs, Swetrix loads the standalone replay recorder with an async script tag.
+
| Name | Description | Default value |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |
| privacy | Controls how much page content is masked. Use `total` to mask all text and inputs and block media/canvas content, `normal` to mask all inputs, or `none` to only force password inputs to stay masked unless you add your own `rrweb` masking options. | `total` |
diff --git a/packages/tracker-js/README.md b/packages/tracker-js/README.md
index afa66f8f0..2f2415c37 100644
--- a/packages/tracker-js/README.md
+++ b/packages/tracker-js/README.md
@@ -65,6 +65,7 @@ init('YOUR_PROJECT_ID', {
disabled: false,
respectDNT: false,
profileId: 'user-123',
+ preloadSessionReplay: false,
})
```
@@ -75,6 +76,7 @@ init('YOUR_PROJECT_ID', {
| `disabled` | When `true`, no data is sent. Useful for dev environments. | `false` |
| `respectDNT` | When `true`, disables tracking for users with Do Not Track enabled. | `false` |
| `profileId` | Profile ID for long-term user tracking (MAU/DAU). | `undefined` |
+| `preloadSessionReplay` | Preload the session replay recorder after `init()`. Recording only starts after `startSessionReplay()`. | `undefined` |
### `trackViews(options?)`
@@ -198,6 +200,8 @@ clearExperimentsCache()
Start recording a session replay. Session replays use `total` privacy by default, which masks text and inputs and blocks media/canvas capture unless you explicitly choose another mode.
+If you use the npm package, rrweb is dynamically imported from your installed dependencies only when the recorder is preloaded or started. If you use the CDN/script-tag build, the standalone replay recorder is loaded with an async script tag.
+
```javascript
const replay = await startSessionReplay({
privacy: 'total',
diff --git a/packages/tracker-js/rollup.config.mjs b/packages/tracker-js/rollup.config.mjs
index f19f5cc6d..232c36a74 100644
--- a/packages/tracker-js/rollup.config.mjs
+++ b/packages/tracker-js/rollup.config.mjs
@@ -11,6 +11,7 @@ const require = createRequire(import.meta.url)
const rrwebDistFile = 'replaylibrary.min.js'
const rrwebPackageFile = 'rrweb.umd.min.cjs'
const rrwebDistPath = join(dirname(require.resolve('rrweb')), rrwebPackageFile)
+const external = ['rrweb']
const copyRrweb = () => ({
name: 'copy-rrweb',
@@ -26,6 +27,7 @@ const copyRrweb = () => ({
export default [
{
input: 'src/index.ts',
+ external,
output: [
{ file: pkg.main, format: 'cjs', sourcemap: true },
{ file: pkg.module, format: 'es', sourcemap: true },
@@ -42,6 +44,7 @@ export default [
},
{
input: 'src/index.ts',
+ external,
output: [{ file: pkg.browser, format: 'umd', name: 'swetrix', sourcemap: true }],
plugins: [
typescript({
diff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.ts
index 88b47f88e..0b8cbb593 100644
--- a/packages/tracker-js/src/Lib.ts
+++ b/packages/tracker-js/src/Lib.ts
@@ -28,6 +28,12 @@ interface RrwebGlobal {
Replayer?: unknown
}
+type RrwebModule = RrwebGlobal & {
+ default?: RrwebGlobal
+}
+
+type SessionReplayPreloadOption = boolean | { rrwebUrl?: string }
+
declare global {
interface Window {
rrweb?: RrwebGlobal
@@ -64,7 +70,7 @@ export interface LibOptions {
/**
* Preload session replay recorder code. Recording only starts after calling startSessionReplay().
*/
- sessionReplay?: boolean | { rrwebUrl?: string }
+ preloadSessionReplay?: SessionReplayPreloadOption
}
export interface TrackEventOptions {
@@ -314,7 +320,7 @@ export class Lib {
this.heartbeat = this.heartbeat.bind(this)
this.captureError = this.captureError.bind(this)
- if (options?.sessionReplay) {
+ if (this.getSessionReplayPreloadOption()) {
void this.preloadSessionReplay().catch(() => undefined)
}
}
@@ -1071,7 +1077,7 @@ export class Lib {
}
private getSessionReplayUrl(): string {
- const replayOption = this.options?.sessionReplay
+ const replayOption = this.getSessionReplayPreloadOption()
if (
replayOption &&
typeof replayOption === 'object' &&
@@ -1083,23 +1089,16 @@ export class Lib {
return this.getDefaultSessionReplayUrl()
}
+ private getSessionReplayPreloadOption(): SessionReplayPreloadOption | undefined {
+ return this.options?.preloadSessionReplay
+ }
+
private getDefaultSessionReplayUrl(): string {
if (!isInBrowser()) {
return DEFAULT_RRWEB_URL
}
- const trackerScript = Array.from(document.scripts).find((script) => {
- if (!script.src) {
- return false
- }
-
- try {
- const { pathname } = new URL(script.src)
- return /(^|\/)swetrix(\.min)?\.js$/i.test(pathname)
- } catch {
- return false
- }
- })
+ const trackerScript = this.getTrackerScript()
if (trackerScript?.src) {
const { hostname, pathname } = new URL(trackerScript.src)
@@ -1116,6 +1115,23 @@ export class Lib {
return DEFAULT_RRWEB_URL
}
+ private getTrackerScript(): HTMLScriptElement | undefined {
+ const trackerScript = Array.from(document.scripts).find((script) => {
+ if (!script.src) {
+ return false
+ }
+
+ try {
+ const { pathname } = new URL(script.src)
+ return /(^|\/)swetrix(\.min)?\.js$/i.test(pathname)
+ } catch {
+ return false
+ }
+ })
+
+ return trackerScript
+ }
+
private preloadSessionReplay(): Promise<void> {
if (!isInBrowser()) {
return Promise.resolve()
@@ -1140,15 +1156,7 @@ export class Lib {
return this.rrwebLoader
}
- this.rrwebLoader = new Promise<void>((resolve, reject) => {
- const script = document.createElement('script')
- script.async = true
- script.src = this.getSessionReplayUrl()
- script.crossOrigin = 'anonymous'
- script.onload = () => resolve()
- script.onerror = () => reject(new Error('Failed to load rrweb'))
- document.head.appendChild(script)
- })
+ this.rrwebLoader = this.loadSessionReplayRecorder()
window.__SWETRIX_RRWEB_LOADING__ = this.rrwebLoader
const loader = this.rrwebLoader
@@ -1164,6 +1172,51 @@ export class Lib {
return this.rrwebLoader
}
+ private async loadSessionReplayRecorder(): Promise<void> {
+ const replayOption = this.getSessionReplayPreloadOption()
+ const hasCustomReplayUrl =
+ replayOption && typeof replayOption === 'object' && replayOption.rrwebUrl
+
+ if (hasCustomReplayUrl || this.getTrackerScript()) {
+ await this.loadSessionReplayScript(this.getSessionReplayUrl())
+ return
+ }
+
+ if (await this.loadSessionReplayPackage()) {
+ return
+ }
+
+ await this.loadSessionReplayScript(this.getDefaultSessionReplayUrl())
+ }
+
+ private async loadSessionReplayPackage(): Promise<boolean> {
+ try {
+ const rrwebModule = (await import('rrweb')) as RrwebModule
+ const rrweb = rrwebModule.record ? rrwebModule : rrwebModule.default
+
+ if (!rrweb?.record) {
+ return false
+ }
+
+ window.rrweb = rrweb
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ private loadSessionReplayScript(url: string): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ const script = document.createElement('script')
+ script.async = true
+ script.src = url
+ script.crossOrigin = 'anonymous'
+ script.onload = () => resolve()
+ script.onerror = () => reject(new Error('Failed to load rrweb'))
+ document.head.appendChild(script)
+ })
+ }
+
private getSessionReplayRecordOptions(
privacy: unknown,
userOptions: RrwebRecordOptions | undefined,
diff --git a/packages/tracker-js/src/types/rrweb-shim.d.ts b/packages/tracker-js/src/types/rrweb-shim.d.ts
new file mode 100644
index 000000000..d20456a6c
--- /dev/null
+++ b/packages/tracker-js/src/types/rrweb-shim.d.ts
@@ -0,0 +1,11 @@
+declare module 'rrweb' {
+ export const record: unknown
+ export const Replayer: unknown
+
+ const rrweb: {
+ record?: unknown
+ Replayer?: unknown
+ }
+
+ export default rrweb
+}
diff --git a/packages/tracker-js/tests/sessionReplay.test.ts b/packages/tracker-js/tests/sessionReplay.test.ts
index c3254f46e..b0c884da5 100644
--- a/packages/tracker-js/tests/sessionReplay.test.ts
+++ b/packages/tracker-js/tests/sessionReplay.test.ts
@@ -5,6 +5,11 @@ import { setLocation } from './testUtils'
const PROJECT_ID = 'test-project-id'
const RRWEB_URL = 'https://cdn.jsdelivr.net/npm/swetrix@latest/dist/replaylibrary.min.js'
+const mockRrwebRecord = jest.fn()
+
+jest.mock('rrweb', () => ({
+ record: mockRrwebRecord,
+}))
const loadTracker = async () => {
jest.resetModules()
@@ -18,25 +23,17 @@ const resetReplayGlobals = () => {
document.body.innerHTML = ''
}
-const resolveRrwebScript = (
- record: jest.Mock,
-): { recordOptions: () => any } => {
- let options: any
- ;(window as any).rrweb = {
- record: jest.fn((recordOptions) => {
- options = recordOptions
- return jest.fn()
- }),
- }
-
- const script = document.querySelector<HTMLScriptElement>(
- `script[src="${RRWEB_URL}"]`,
- )
- expect(script).toBeTruthy()
- ;(window as any).rrweb.record = record
- script!.dispatchEvent(new Event('load'))
+const usePackageRrweb = () => {
+ const stopRecording = jest.fn()
+ mockRrwebRecord.mockImplementation((recordOptions) => {
+ ;(mockRrwebRecord as any).options = recordOptions
+ return stopRecording
+ })
- return { recordOptions: () => options }
+ return {
+ recordOptions: () => (mockRrwebRecord as any).options,
+ stopRecording,
+ }
}
describe('Session replay tracking', () => {
@@ -44,6 +41,8 @@ describe('Session replay tracking', () => {
beforeEach(() => {
jest.clearAllMocks()
+ mockRrwebRecord.mockReset()
+ delete (mockRrwebRecord as any).options
jest.useRealTimers()
resetReplayGlobals()
setLocation({ hostname: 'example.com', pathname: '/checkout' })
@@ -62,15 +61,15 @@ describe('Session replay tracking', () => {
})
})
- test('init with sessionReplay preloads rrweb but does not record', async () => {
+ test('init with preloadSessionReplay loads npm rrweb but does not record', async () => {
const { init } = await loadTracker()
- init(PROJECT_ID, { devMode: true, sessionReplay: true })
+ init(PROJECT_ID, { devMode: true, preloadSessionReplay: true })
+ await (window as any).__SWETRIX_RRWEB_LOADING__
- const script = document.querySelector<HTMLScriptElement>(
- `script[src="${RRWEB_URL}"]`,
- )
- expect(script).toBeTruthy()
+ expect((window as any).rrweb.record).toBe(mockRrwebRecord)
+ expect(document.querySelector(`script[src="${RRWEB_URL}"]`)).toBeNull()
+ expect(mockRrwebRecord).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
})
@@ -80,32 +79,43 @@ describe('Session replay tracking', () => {
document.head.appendChild(script)
const { init } = await loadTracker()
- init(PROJECT_ID, { devMode: true, sessionReplay: true })
+ init(PROJECT_ID, { devMode: true, preloadSessionReplay: true })
expect(
document.querySelector<HTMLScriptElement>(
`script[src="${RRWEB_URL}"]`,
),
).toBeTruthy()
+ expect(mockRrwebRecord).not.toHaveBeenCalled()
})
- test('startSessionReplay loads rrweb, records events, and flushes chunks', async () => {
- const record = jest.fn((options) => {
- ;(record as any).options = options
- return jest.fn()
+ test('preloadSessionReplay can load rrweb from a custom script URL', async () => {
+ const rrwebUrl = 'https://cdn.example.com/rrweb.min.js'
+ const { init } = await loadTracker()
+
+ init(PROJECT_ID, {
+ devMode: true,
+ preloadSessionReplay: { rrwebUrl },
})
+
+ expect(
+ document.querySelector<HTMLScriptElement>(`script[src="${rrwebUrl}"]`),
+ ).toBeTruthy()
+ expect(mockRrwebRecord).not.toHaveBeenCalled()
+ })
+
+ test('startSessionReplay imports npm rrweb, records events, and flushes chunks', async () => {
+ const { recordOptions } = usePackageRrweb()
const { init, startSessionReplay } = await loadTracker()
init(PROJECT_ID, { devMode: true })
- const startPromise = startSessionReplay({
+ const actions = await startSessionReplay({
flushIntervalMs: 60_000,
maxEventsPerChunk: 2,
})
- resolveRrwebScript(record)
-
- const actions = await startPromise
- const recordOptions = (record as any).options
- expect(recordOptions.maskTextSelector).toBe('*')
+ const options = recordOptions()
+ expect(options.maskTextSelector).toBe('*')
+ expect(document.querySelector(`script[src="${RRWEB_URL}"]`)).toBeNull()
const startCall = fetchMock.mock.calls.find(([url]) =>
String(url).includes('/session-replay/start'),
@@ -115,8 +125,8 @@ describe('Session replay tracking', () => {
expect.objectContaining({ privacy: 'total' }),
)
- recordOptions.emit({ type: 2, timestamp: 100 })
- recordOptions.emit({ type: 3, timestamp: 200 })
+ options.emit({ type: 2, timestamp: 100 })
+ options.emit({ type: 3, timestamp: 200 })
await actions.flush()
@@ -145,26 +155,20 @@ describe('Session replay tracking', () => {
expect(fetchMock).not.toHaveBeenCalled()
expect(document.querySelector(`script[src="${RRWEB_URL}"]`)).toBeNull()
+ expect(mockRrwebRecord).not.toHaveBeenCalled()
})
test('maxDurationMs stops recording and flushes buffered events', async () => {
jest.useFakeTimers()
- const stopRecording = jest.fn()
- const record = jest.fn((options) => {
- ;(record as any).options = options
- return stopRecording
- })
+ const { recordOptions, stopRecording } = usePackageRrweb()
const { init, startSessionReplay } = await loadTracker()
init(PROJECT_ID, { devMode: true })
- const startPromise = startSessionReplay({
+ await startSessionReplay({
flushIntervalMs: 60_000,
maxDurationMs: 1000,
})
- resolveRrwebScript(record)
-
- await startPromise
- ;(record as any).options.emit({ type: 2, timestamp: 100 })
+ recordOptions().emit({ type: 2, timestamp: 100 })
await jest.advanceTimersByTimeAsync(1000)
await Promise.resolve()
@@ -180,22 +184,15 @@ describe('Session replay tracking', () => {
test('idleTimeoutMs stops after inactivity and resets on activity', async () => {
jest.useFakeTimers()
- const stopRecording = jest.fn()
- const record = jest.fn((options) => {
- ;(record as any).options = options
- return stopRecording
- })
+ const { recordOptions, stopRecording } = usePackageRrweb()
const { init, startSessionReplay } = await loadTracker()
init(PROJECT_ID, { devMode: true })
- const startPromise = startSessionReplay({
+ await startSessionReplay({
flushIntervalMs: 60_000,
idleTimeoutMs: 1000,
})
- resolveRrwebScript(record)
-
- await startPromise
- ;(record as any).options.emit({ type: 2, timestamp: 200 })
+ recordOptions().emit({ type: 2, timestamp: 200 })
await jest.advanceTimersByTimeAsync(900)
window.dispatchEvent(new Event('mousemove'))
@@ -253,19 +250,13 @@ describe('Session replay tracking', () => {
})
test('invalid privacy values fall back to total privacy', async () => {
- const record = jest.fn((options) => {
- ;(record as any).options = options
- return jest.fn()
- })
+ const { recordOptions } = usePackageRrweb()
const { init, startSessionReplay } = await loadTracker()
init(PROJECT_ID, { devMode: true })
- const startPromise = startSessionReplay({
+ const actions = await startSessionReplay({
privacy: 'totl' as any,
})
- resolveRrwebScript(record)
-
- const actions = await startPromise
const startCall = fetchMock.mock.calls.find(([url]) =>
String(url).includes('/session-replay/start'),
)
@@ -274,19 +265,23 @@ describe('Session replay tracking', () => {
expect(JSON.parse(startCall![1].body as string)).toEqual(
expect.objectContaining({ privacy: 'total' }),
)
- expect((record as any).options.maskTextSelector).toBe('*')
+ expect(recordOptions().maskTextSelector).toBe('*')
await actions.stop()
})
- test('rrweb loader clears failed loads so startSessionReplay can retry', async () => {
+ test('script rrweb loader clears failed loads so startSessionReplay can retry', async () => {
const record = jest.fn(() => jest.fn())
+ const trackerScript = document.createElement('script')
+ trackerScript.src = 'https://example.com/swetrix.js'
+ document.head.appendChild(trackerScript)
+ const rrwebUrl = 'https://example.com/replaylibrary.min.js'
const { init, startSessionReplay } = await loadTracker()
init(PROJECT_ID, { devMode: true })
const failedStart = startSessionReplay()
const failedScript = document.querySelector<HTMLScriptElement>(
- `script[src="${RRWEB_URL}"]`,
+ `script[src="${rrwebUrl}"]`,
)
expect(failedScript).toBeTruthy()
failedScript!.dispatchEvent(new Event('error'))
@@ -296,7 +291,7 @@ describe('Session replay tracking', () => {
const retryStart = startSessionReplay()
const scripts = document.querySelectorAll<HTMLScriptElement>(
- `script[src="${RRWEB_URL}"]`,
+ `script[src="${rrwebUrl}"]`,
)
expect(scripts[1]).toBeTruthy()
expect(scripts[1]).not.toBe(failedScript)
@@ -311,22 +306,16 @@ describe('Session replay tracking', () => {
})
test('user rrweb emit is composed with Swetrix uploads', async () => {
- const record = jest.fn((options) => {
- ;(record as any).options = options
- return jest.fn()
- })
+ const { recordOptions } = usePackageRrweb()
const userEmit = jest.fn()
const { init, startSessionReplay } = await loadTracker()
init(PROJECT_ID, { devMode: true })
- const startPromise = startSessionReplay({
+ const actions = await startSessionReplay({
rrweb: { emit: userEmit, maskAllInputs: true },
})
- resolveRrwebScript(record)
-
- const actions = await startPromise
const event = { type: 2, timestamp: 300 }
- ;(record as any).options.emit(event)
+ recordOptions().emit(event)
await actions.flush()
expect(userEmit).toHaveBeenCalledWith(event)
@@ -356,8 +345,10 @@ describe('Session replay tracking', () => {
expect(fetchMock).not.toHaveBeenCalled()
expect(document.querySelector(`script[src="${RRWEB_URL}"]`)).toBeNull()
+ expect(mockRrwebRecord).not.toHaveBeenCalled()
resetReplayGlobals()
+ mockRrwebRecord.mockReset()
Object.defineProperty(navigator, 'doNotTrack', {
value: null,
writable: true,
@@ -371,5 +362,6 @@ describe('Session replay tracking', () => {
expect(fetchMock).not.toHaveBeenCalled()
expect(document.querySelector(`script[src="${RRWEB_URL}"]`)).toBeNull()
+ expect(mockRrwebRecord).not.toHaveBeenCalled()
})
})
diff --git a/packages/tracker-js/tsconfig.esnext.json b/packages/tracker-js/tsconfig.esnext.json
index 143a535a1..b9241802a 100644
--- a/packages/tracker-js/tsconfig.esnext.json
+++ b/packages/tracker-js/tsconfig.esnext.json
@@ -8,6 +8,10 @@
"sourceMap": true,
"declaration": true,
"outDir": "dist/esnext",
+ "baseUrl": ".",
+ "paths": {
+ "rrweb": ["src/types/rrweb-shim.d.ts"]
+ },
"types": []
},
"include": ["src"]
diff --git a/packages/tracker-js/tsconfig.json b/packages/tracker-js/tsconfig.json
index 8df177773..469d1fc3f 100644
--- a/packages/tracker-js/tsconfig.json
+++ b/packages/tracker-js/tsconfig.json
@@ -8,6 +8,10 @@
"sourceMap": true,
"declaration": false,
"allowSyntheticDefaultImports": true,
+ "baseUrl": ".",
+ "paths": {
+ "rrweb": ["src/types/rrweb-shim.d.ts"]
+ },
"types": []
},
"include": ["src"]