📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
feat: Selective URL query & hash tracking
Blue Mouse40e7af3fe54f
diff --git a/docs/content/docs/script-reference.mdx b/docs/content/docs/script-reference.mdxindex 850fba364..572520440 100644--- a/docs/content/docs/script-reference.mdx+++ b/docs/content/docs/script-reference.mdx@@ -98,8 +98,8 @@ Here's an example of how to use this function with all the available options:swetrix.trackViews({unique: false,heartbeatOnBackground: false,- hash: false,- search: false,+ hash: ["pricing", "features"],+ search: ["query", "page"],callback: undefined,});```@@ -109,8 +109,8 @@ swetrix.trackViews({| unique | If true, only unique events will be saved. This param is useful when tracking single-page landing websites. | `false` || callback | A callback used to edit / prevent sending pageviews.<br />It accepts an object with pageview event data as a parameter which has the following structure: <br />lc: string \| undefined<br />tz: string \| undefined<br />ref: string \| undefined<br />so: string \| undefined<br />me: string \| undefined<br />ca: string \| undefined<br />te: string \| undefined<br />co: string \| undefined<br />qs: string \| undefined<br />meta: object \| undefined ("object" values must be string, number, boolean, null, or undefined)<br />pg: string \| null \| undefined<br />profileId: string \| undefined<br /><br />The callback is supposed to return the edited payload or `false` to prevent sending the pageview. If `true` is returned, the payload will be sent as-is. | `undefined` || heartbeatOnBackground | Send Heartbeat requests when the website tab is not active in the browser.<br />Setting this to `true` means users who keep your website open in an inactive browser tab or window can still be counted in realtime statistics.<br />Setting this to true is usually useful for services like Spotify or Youtube. | `false` |-| hash | Set to `true` to enable hash-based routing. For example if you have pages like `/#/path` or want to track pages like `/path#hash`. | `false` |-| search | Set to `true` to enable search-based routing. For example if you have pages like `/path?search`. Although it's not recommended in most cases, you can set both `hash` and `search` to `true` at the same time, in which case the pageview event will be fired when either the hash or the search part of the URL changes (again, both the hash and the search are sent to the server). | `false` |+| hash | Set to `true` to enable hash-based routing for every hash, or provide an array of exact hash values to include. For example, `['pricing', 'features']` includes `/path#pricing` and `/path#features` while ignoring other hashes. A leading `#` is optional in array values. | `false` |+| search | Set to `true` to enable search-based routing for every query parameter, or provide an array of parameter names to include. For example, `['search', 'page']` includes those parameters while ignoring unrelated ones. You can enable both `hash` and `search`; a pageview is fired only when an included part of the URL changes. | `false` |The `trackViews` function returns a `Promise` with an object with some methods allowing you to alter the behaviour of page tracking:@@ -241,7 +241,7 @@ The data we collect includes the following params if available:6. `message` - error message (e.g. Malformed input)7. `lineno` / `colno` - on what line and column in your code did the error occur8. `filename` - in what file did the error occur-9. `stackTrace` - the stack trace of the error (e.g. `Uncaught Error\n at query (:10:11)\n at database (:6:5)`)+9. `stackTrace` - the stack trace of the error, up to 64,000 characters (e.g. `Uncaught Error\n at query (:10:11)\n at database (:6:5)`)10. `meta` - an object that contains event-related metadata. You can set it via a `callback` function.Here's an example of how to use this function with all the available options:@@ -278,7 +278,7 @@ This function takes a payload object with the following fields:3. (optional) `lineno` - on what line in your code did the error occur (e.g. 1520)4. (optional) `colno` - on what column in your code did the error occur (e.g. 26)5. (optional) `filename` - in what file did the error occur (e.g. https://example.com/broken.js)-6. (optional) `stackTrace` - the stack trace of the error (e.g. `Uncaught Error\n at query (:10:11)\n at database (:6:5)`)+6. (optional) `stackTrace` - the stack trace of the error, up to 64,000 characters (e.g. `Uncaught Error\n at query (:10:11)\n at database (:6:5)`)7. (optional) `meta` - an object that contains event-related metadata. The values of the object must be a primitive type (string, number, boolean, null) which will be converted to a string, the maximum number of keys allowed is `100` and the total length of the values combined must be less than `2000` characters.Here is an example of how to use this function:diff --git a/packages/tracker-js/README.md b/packages/tracker-js/README.mdindex edfda43c0..1cfe8f69f 100644--- a/packages/tracker-js/README.md+++ b/packages/tracker-js/README.md@@ -69,14 +69,14 @@ init('YOUR_PROJECT_ID', {})```-| Option | Description | Default |-|---|---|---|-| `apiURL` | API endpoint. Change this if you're self-hosting. | `'https://api.swetrix.com/log'` |-| `devMode` | When `true`, localhost events are sent to the server. | `false` |-| `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` |+| Option | Description | Default |+| ---------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------- |+| `apiURL` | API endpoint. Change this if you're self-hosting. | `'https://api.swetrix.com/log'` |+| `devMode` | When `true`, localhost events are sent to the server. | `false` |+| `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?)`@@ -84,8 +84,8 @@ Automatically tracks page views, including navigation changes in SPAs. Returns a```javascriptconst { stop } = await trackViews({- hash: false,- search: false,+ hash: ['pricing', 'features'],+ search: ['query', 'page'],unique: false,heartbeatOnBackground: false,callback: undefined,@@ -95,13 +95,13 @@ const { stop } = await trackViews({stop()```-| Option | Description | Default |-|---|---|---|-| `hash` | Track hash-based routing (e.g. `/#/path`). | `false` |-| `search` | Track search/query-based routing (e.g. `/path?query`). | `false` |-| `unique` | Only count unique page views per session. | `false` |-| `heartbeatOnBackground` | Send heartbeat when the tab is not active. | `false` |-| `callback` | A function to edit or prevent pageview payloads. Return `false` to block, `true` to send as-is, or return a modified payload object. | `undefined` |+| Option | Description | Default |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------- |+| `hash` | Set to `true` to track every hash (e.g. `/#/path`), or provide an array of exact hash values to include (e.g. `['pricing', 'features']`). A leading `#` is optional in array values. | `false` |+| `search` | Set to `true` to track every query parameter (e.g. `/path?query=value`), or provide an array of parameter names to include (e.g. `['query', 'page']`). | `false` |+| `unique` | Only count unique page views per session. | `false` |+| `heartbeatOnBackground` | Send heartbeat when the tab is not active. | `false` |+| `callback` | A function to edit or prevent pageview payloads. Return `false` to block, `true` to send as-is, or return a modified payload object. | `undefined` |### `track(event)`@@ -116,12 +116,12 @@ track({})```-| Option | Description | Default |-|---|---|---|-| `ev` | Event name (max 256 chars). | **required** |-| `unique` | Only count once per session. | `false` |-| `meta` | Key-value metadata (max 20 keys, 1000 chars total). | `{}` |-| `profileId` | Optional profile ID. Overrides the global `profileId` for this event. | `undefined` |+| Option | Description | Default |+| ----------- | --------------------------------------------------------------------- | ------------ |+| `ev` | Event name (max 256 chars). | **required** |+| `unique` | Only count once per session. | `false` |+| `meta` | Key-value metadata (max 20 keys, 1000 chars total). | `{}` |+| `profileId` | Optional profile ID. Overrides the global `profileId` for this event. | `undefined` |### `trackErrors(options?)`@@ -134,10 +134,10 @@ const { stop } = trackErrors({})```-| Option | Description | Default |-|---|---|---|-| `sampleRate` | Fraction of errors to send (`0` to `1`). | `1` |-| `callback` | Edit or prevent error payloads. Return `false` to block. | `undefined` |+| Option | Description | Default |+| ------------ | -------------------------------------------------------- | ----------- |+| `sampleRate` | Fraction of errors to send (`0` to `1`). | `1` |+| `callback` | Edit or prevent error payloads. Return `false` to block. | `undefined` |### `trackError(payload)`@@ -217,19 +217,19 @@ await replay.flush()await replay.stop()```-| Option | Description | Default |-|---|---|---|-| `privacy` | Privacy mode: `total`, `normal`, or `none`. | `'total'` |-| `maskAllText` | Mask all non-input text with asterisks. Defaults to `true` when `privacy` is `total`, otherwise `false`. | privacy-based |-| `sampleRate` | Fraction of sessions to record (`0` to `1`). | `1` |-| `maxDurationMs` | Stop recording after this duration. | `undefined` |-| `idleTimeoutMs` | Stop recording after this much visitor inactivity. | `undefined` |-| `flushIntervalMs` | Upload buffered replay events at this interval. | `5000` |-| `maxEventsPerChunk` | Upload once this many events are buffered. | `100` |-| `maxBytesPerChunk` | Upload once buffered replay events reach this approximate byte size. | `524288` |-| `maxBytesPerEvent` | Drop a single replay event if it is larger than this many bytes. | `5242880` |-| `recordIframes` | Allow iframe elements to be captured. Iframes are blocked by default to reduce replay size and avoid recording embedded third-party content. | `false` |-| `rrweb` | Additional rrweb record options. | `undefined` |+| Option | Description | Default |+| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |+| `privacy` | Privacy mode: `total`, `normal`, or `none`. | `'total'` |+| `maskAllText` | Mask all non-input text with asterisks. Defaults to `true` when `privacy` is `total`, otherwise `false`. | privacy-based |+| `sampleRate` | Fraction of sessions to record (`0` to `1`). | `1` |+| `maxDurationMs` | Stop recording after this duration. | `undefined` |+| `idleTimeoutMs` | Stop recording after this much visitor inactivity. | `undefined` |+| `flushIntervalMs` | Upload buffered replay events at this interval. | `5000` |+| `maxEventsPerChunk` | Upload once this many events are buffered. | `100` |+| `maxBytesPerChunk` | Upload once buffered replay events reach this approximate byte size. | `524288` |+| `maxBytesPerEvent` | Drop a single replay event if it is larger than this many bytes. | `5242880` |+| `recordIframes` | Allow iframe elements to be captured. Iframes are blocked by default to reduce replay size and avoid recording embedded third-party content. | `false` |+| `rrweb` | Additional rrweb record options. | `undefined` |To mask text while keeping media less restricted than `total` privacy, combine `normal` privacy with `maskAllText`:diff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.tsindex 354370c2f..c02c29789 100644--- a/packages/tracker-js/src/Lib.ts+++ b/packages/tracker-js/src/Lib.ts@@ -219,8 +219,7 @@ export interface ErrorActions {const SESSION_REPLAY_PRIVACY_VALUES = ['total', 'normal', 'none'] as const-export type SessionReplayPrivacy =- (typeof SESSION_REPLAY_PRIVACY_VALUES)[number]+export type SessionReplayPrivacy = (typeof SESSION_REPLAY_PRIVACY_VALUES)[number]export interface SessionReplayOptions {privacy?: SessionReplayPrivacy@@ -279,16 +278,16 @@ export interface PageViewsOptions {heartbeatOnBackground?: boolean/**- * Set to `true` to enable hash-based routing.- * For example if you have pages like /#/path or want to track pages like /path#hash+ * Set to `true` to enable hash-based routing, or provide an array of hash values to include.+ * For example, use `true` for pages like /#/path, or `['pricing', 'features']` to include only those hashes.*/- hash?: boolean+ hash?: boolean | readonly string[]/**- * Set to `true` to enable search-based routing.- * For example if you have pages like /path?search+ * Set to `true` to enable search-based routing, or provide an array of query parameter names to include.+ * For example, use `true` for /path?search, or `['search', 'page']` to ignore all other parameters.*/- search?: boolean+ search?: boolean | readonly string[]/*** Callback to edit / prevent sending pageviews.@@ -353,14 +352,7 @@ const SESSION_REPLAY_CHUNK_RETRY_DELAYS_MS = [2_000, 5_000, 15_000]// rejects every re-seed too. Cap the attempts rather than re-uploading a// multi-megabyte snapshot on a loop for the rest of the session.const SESSION_REPLAY_MAX_SNAPSHOT_RESEEDS = 3-const SESSION_REPLAY_ACTIVITY_EVENTS = [- 'click',- 'keydown',- 'mousedown',- 'mousemove',- 'scroll',- 'touchstart',-] as const+const SESSION_REPLAY_ACTIVITY_EVENTS = ['click', 'keydown', 'mousedown', 'mousemove', 'scroll', 'touchstart'] as const// Default cache duration: 5 minutesconst DEFAULT_CACHE_DURATION = 5 * 60 * 1000@@ -393,7 +385,10 @@ export class Lib {// The last profile ID sent to the identify API (to avoid duplicate requests)private lastIdentifySent: string | null = null- constructor(private projectID: string, private options?: LibOptions) {+ constructor(+ private projectID: string,+ private options?: LibOptions,+ ) {this.trackPathChange = this.trackPathChange.bind(this)this.heartbeat = this.heartbeat.bind(this)this.captureError = this.captureError.bind(this)@@ -971,9 +966,7 @@ export class Lib {}}- async startSessionReplay(- options: SessionReplayOptions = {},- ): Promise<SessionReplayActions> {+ async startSessionReplay(options: SessionReplayOptions = {}): Promise<SessionReplayActions> {if (this.sessionReplayActions) {return this.sessionReplayActions}@@ -994,9 +987,7 @@ export class Lib {}}- private async initialiseSessionReplay(- options: SessionReplayOptions,- ): Promise<SessionReplayActions> {+ private async initialiseSessionReplay(options: SessionReplayOptions): Promise<SessionReplayActions> {if (this.sessionReplayActions) {return this.sessionReplayActions}@@ -1040,30 +1031,19 @@ export class Lib {? options.flushIntervalMs: DEFAULT_SESSION_REPLAY_FLUSH_INTERVALconst maxEventsPerChunk =- typeof options.maxEventsPerChunk === 'number' &&- options.maxEventsPerChunk > 0+ typeof options.maxEventsPerChunk === 'number' && options.maxEventsPerChunk > 0? Math.floor(options.maxEventsPerChunk): DEFAULT_SESSION_REPLAY_MAX_EVENTSconst maxBytesPerChunkCandidate =- typeof options.maxBytesPerChunk === 'number'- ? Math.floor(options.maxBytesPerChunk)- : Number.NaN+ typeof options.maxBytesPerChunk === 'number' ? Math.floor(options.maxBytesPerChunk) : Number.NaNconst maxBytesPerChunk =- maxBytesPerChunkCandidate >= 1- ? maxBytesPerChunkCandidate- : DEFAULT_SESSION_REPLAY_MAX_CHUNK_BYTES+ maxBytesPerChunkCandidate >= 1 ? maxBytesPerChunkCandidate : DEFAULT_SESSION_REPLAY_MAX_CHUNK_BYTESconst maxBytesPerEventCandidate =- typeof options.maxBytesPerEvent === 'number'- ? Math.floor(options.maxBytesPerEvent)- : Number.NaN+ typeof options.maxBytesPerEvent === 'number' ? Math.floor(options.maxBytesPerEvent) : Number.NaNconst maxBytesPerEvent =- maxBytesPerEventCandidate >= 1- ? maxBytesPerEventCandidate- : DEFAULT_SESSION_REPLAY_MAX_EVENT_BYTES+ maxBytesPerEventCandidate >= 1 ? maxBytesPerEventCandidate : DEFAULT_SESSION_REPLAY_MAX_EVENT_BYTESconst idleTimeoutMs =- typeof options.idleTimeoutMs === 'number' && options.idleTimeoutMs > 0- ? options.idleTimeoutMs- : null+ typeof options.idleTimeoutMs === 'number' && options.idleTimeoutMs > 0 ? options.idleTimeoutMs : nulllet chunkIndex = started.nextChunkIndexlet snapshotReseeds = 0@@ -1085,13 +1065,7 @@ export class Lib {flushing = flushing.catch(() => undefined).then(async () => {- const delivered = await this.sendSessionReplayChunk(- replayId,- privacy,- currentChunkIndex,- chunk,- useBeacon,- )+ const delivered = await this.sendSessionReplayChunk(replayId, privacy, currentChunkIndex, chunk, useBeacon)// Losing a full snapshot makes every later event unrenderable, so// re-seed the stream instead of recording into the void.@@ -1132,19 +1106,13 @@ export class Lib {return}- if (- events.length &&- eventsByteLength + eventByteLength > maxBytesPerChunk- ) {+ if (events.length && eventsByteLength + eventByteLength > maxBytesPerChunk) {void flush()}events.push(event)eventsByteLength += eventByteLength- if (- events.length >= maxEventsPerChunk ||- eventsByteLength >= maxBytesPerChunk- ) {+ if (events.length >= maxEventsPerChunk || eventsByteLength >= maxBytesPerChunk) {void flush()}},@@ -1193,10 +1161,7 @@ export class Lib {window.addEventListener('pagehide', flushOnPageExit)document.addEventListener('visibilitychange', flushOnHidden)- maxDurationTimer = setTimeout(- () => void stopSessionReplay(),- maxDurationMs,- )+ maxDurationTimer = setTimeout(() => void stopSessionReplay(), maxDurationMs)if (idleTimeoutMs) {SESSION_REPLAY_ACTIVITY_EVENTS.forEach((eventName) => {@@ -1232,9 +1197,7 @@ export class Lib {}private getSessionReplayPrivacy(privacy: unknown): SessionReplayPrivacy {- return SESSION_REPLAY_PRIVACY_VALUES.includes(- privacy as SessionReplayPrivacy,- )+ return SESSION_REPLAY_PRIVACY_VALUES.includes(privacy as SessionReplayPrivacy)? (privacy as SessionReplayPrivacy): DEFAULT_SESSION_REPLAY_PRIVACY}@@ -1349,11 +1312,7 @@ export class Lib {private getSessionReplayUrl(): string {const replayOption = this.getSessionReplayPreloadOption()- if (- replayOption &&- typeof replayOption === 'object' &&- replayOption.rrwebUrl- ) {+ if (replayOption && typeof replayOption === 'object' && replayOption.rrwebUrl) {return replayOption.rrwebUrl}@@ -1373,10 +1332,7 @@ export class Lib {if (trackerScript?.src) {const { hostname, pathname } = new URL(trackerScript.src)- if (- hostname === 'swetrix.org' &&- /^\/swetrix(\.min)?\.js$/i.test(pathname)- ) {+ if (hostname === 'swetrix.org' && /^\/swetrix(\.min)?\.js$/i.test(pathname)) {return DEFAULT_RRWEB_URL}@@ -1466,8 +1422,7 @@ export class Lib {private async loadSessionReplayRecorder(): Promise<void> {const replayOption = this.getSessionReplayPreloadOption()- const hasCustomReplayUrl =- replayOption && typeof replayOption === 'object' && replayOption.rrwebUrl+ const hasCustomReplayUrl = replayOption && typeof replayOption === 'object' && replayOption.rrwebUrlif (hasCustomReplayUrl || this.getTrackerScript()) {await this.loadSessionReplayScript(this.getSessionReplayUrl())@@ -1516,12 +1471,8 @@ export class Lib {recordIframes: boolean,maskAllText?: boolean,): RrwebRecordOptions {- const hasUserSampling =- userOptions &&- Object.prototype.hasOwnProperty.call(userOptions, 'sampling')- const hasUserSlimDOMOptions =- userOptions &&- Object.prototype.hasOwnProperty.call(userOptions, 'slimDOMOptions')+ const hasUserSampling = userOptions && Object.prototype.hasOwnProperty.call(userOptions, 'sampling')+ const hasUserSlimDOMOptions = userOptions && Object.prototype.hasOwnProperty.call(userOptions, 'slimDOMOptions')const sampling =typeof userOptions?.sampling === 'object' && userOptions.sampling !== null? {@@ -1532,8 +1483,7 @@ export class Lib {? userOptions?.sampling: DEFAULT_SESSION_REPLAY_SAMPLINGconst slimDOMOptions =- typeof userOptions?.slimDOMOptions === 'object' &&- userOptions.slimDOMOptions !== null+ typeof userOptions?.slimDOMOptions === 'object' && userOptions.slimDOMOptions !== null? {...DEFAULT_SESSION_REPLAY_SLIM_DOM_OPTIONS,...(userOptions.slimDOMOptions as Record<string, unknown>),@@ -1553,20 +1503,14 @@ export class Lib {}const maskInputOptions =- typeof options.maskInputOptions === 'object' &&- options.maskInputOptions !== null+ typeof options.maskInputOptions === 'object' && options.maskInputOptions !== null? (options.maskInputOptions as Record<string, unknown>): {}const resolvedPrivacy = this.getSessionReplayPrivacy(privacy)const defaultBlockSelector = recordIframes ? undefined : 'iframe'- const resolvedMaskAllText =- typeof maskAllText === 'boolean'- ? maskAllText- : resolvedPrivacy === 'total'- const textMaskingOptions = resolvedMaskAllText- ? { maskTextSelector: '*' }- : {}+ const resolvedMaskAllText = typeof maskAllText === 'boolean' ? maskAllText : resolvedPrivacy === 'total'+ const textMaskingOptions = resolvedMaskAllText ? { maskTextSelector: '*' } : {}if (resolvedPrivacy === 'total') {return {@@ -1588,10 +1532,7 @@ export class Lib {...options,...textMaskingOptions,maskAllInputs: true,- blockSelector: this.mergeSelectors(- options.blockSelector,- defaultBlockSelector,- ),+ blockSelector: this.mergeSelectors(options.blockSelector, defaultBlockSelector),emit,}}@@ -1599,10 +1540,7 @@ export class Lib {return {...options,...textMaskingOptions,- blockSelector: this.mergeSelectors(- options.blockSelector,- defaultBlockSelector,- ),+ blockSelector: this.mergeSelectors(options.blockSelector, defaultBlockSelector),maskInputOptions: {...maskInputOptions,password: true,@@ -1611,10 +1549,7 @@ export class Lib {}}- private mergeSelectors(- existing: unknown,- required?: string,- ): string | undefined {+ private mergeSelectors(existing: unknown, required?: string): string | undefined {if (!required) {return typeof existing === 'string' ? existing : undefined}@@ -1670,10 +1605,7 @@ export class Lib {replayId: unknownnextChunkIndex: unknown}>- const resolvedReplayId =- typeof result.replayId === 'string' && result.replayId- ? result.replayId- : replayId+ const resolvedReplayId = typeof result.replayId === 'string' && result.replayId ? result.replayId : replayIdconst resolvedChunkIndex =typeof result.nextChunkIndex === 'number' &&Number.isFinite(result.nextChunkIndex) &&@@ -1716,23 +1648,16 @@ export class Lib {if (useBeacon && typeof navigator.sendBeacon === 'function') {// sendBeacon refuses payloads over its ~64 KB quota; fall through to// fetch when it does.- const sent = navigator.sendBeacon(- url,- new Blob([payload], { type: 'application/json' }),- )+ const sent = navigator.sendBeacon(url, new Blob([payload], { type: 'application/json' }))if (sent) return true}// On the beacon path the page is unloading, so there is no time to retry.- const attempts = useBeacon- ? 1- : SESSION_REPLAY_CHUNK_RETRY_DELAYS_MS.length + 1+ const attempts = useBeacon ? 1 : SESSION_REPLAY_CHUNK_RETRY_DELAYS_MS.length + 1for (let attempt = 0; attempt < attempts; attempt++) {if (attempt > 0) {- await new Promise((resolve) =>- setTimeout(resolve, SESSION_REPLAY_CHUNK_RETRY_DELAYS_MS[attempt - 1]),- )+ await new Promise((resolve) => setTimeout(resolve, SESSION_REPLAY_CHUNK_RETRY_DELAYS_MS[attempt - 1]))}try {@@ -1753,11 +1678,7 @@ export class Lib {// Client errors (except timeouts and rate limits) won't succeed on// retry.- if (- response.status < 500 &&- response.status !== 408 &&- response.status !== 429- ) {+ if (response.status < 500 && response.status !== 408 && response.status !== 429) {return false}} catch {}diff --git a/packages/tracker-js/src/utils.ts b/packages/tracker-js/src/utils.tsindex 2481da58a..27a71b0a9 100644--- a/packages/tracker-js/src/utils.ts+++ b/packages/tracker-js/src/utils.ts@@ -1,8 +1,10 @@interface IGetPath {- hash?: boolean- search?: boolean+ hash?: boolean | readonly string[]+ search?: boolean | readonly string[]}+type RouteTrackingOption = boolean | readonly string[] | undefined+const findInSearch = (exp: RegExp): string | undefined => {const res = location.search.match(exp)return (res && res[2]) || undefined@@ -80,6 +82,36 @@ export const getUTMTerm = () => findInSearch(utmTermRegex)export const getUTMContent = () => findInSearch(utmContentRegex)+const filterSearch = (search: string, option: RouteTrackingOption): string => {+ if (option === true) return search+ if (!Array.isArray(option) || !search) return ''++ const allowedParams = new Set(option)+ const params = search+ .slice(1)+ .split('&')+ .filter((param) => {+ const separatorIndex = param.indexOf('=')+ const rawName = separatorIndex === -1 ? param : param.slice(0, separatorIndex)++ try {+ return allowedParams.has(decodeURIComponent(rawName.replace(/\+/g, ' ')))+ } catch {+ return allowedParams.has(rawName)+ }+ })++ return params.length ? `?${params.join('&')}` : ''+}++const filterHash = (hash: string, option: RouteTrackingOption): string => {+ if (option === true) return hash+ if (!Array.isArray(option) || !hash) return ''++ const hashValue = hash.slice(1)+ return option.some((value) => value.replace(/^#/, '') === hashValue) ? hash : ''+}+/*** Function used to track the current page (path) of the application.* Will work in cases where the path looks like:@@ -90,8 +122,8 @@ export const getUTMContent = () => findInSearch(utmContentRegex)* - /path#hash?search** @param options - Options for the function.- * @param options.hash - Whether to trigger on hash change.- * @param options.search - Whether to trigger on search change.+ * @param options.hash - Whether to include hashes, or an allowlist of hash values to include.+ * @param options.search - Whether to include query parameters, or an allowlist of parameter names to include.* @returns The path of the current page.*/export const getPath = (options: IGetPath): string => {@@ -100,13 +132,13 @@ export const getPath = (options: IGetPath): string => {if (options.hash) {const hashIndex = location.hash.indexOf('?')const hashString = hashIndex > -1 ? location.hash.substring(0, hashIndex) : location.hash- result += hashString+ result += filterHash(hashString, options.hash)}if (options.search) {const hashIndex = location.hash.indexOf('?')const searchString = location.search || (hashIndex > -1 ? location.hash.substring(hashIndex) : '')- result += searchString+ result += filterSearch(searchString, options.search)}return resultdiff --git a/packages/tracker-js/tests/utils.test.ts b/packages/tracker-js/tests/utils.test.tsindex 45fec655e..d0fb677dd 100644--- a/packages/tracker-js/tests/utils.test.ts+++ b/packages/tracker-js/tests/utils.test.ts@@ -119,6 +119,29 @@ describe('Utility Functions', () => {expect(utils.getPath({ hash: true, search: true })).toBe('/test-page#section1?param=value')})+ test('getPath should include only allowlisted query parameters', () => {+ setLocation({+ pathname: '/products',+ search: '?category=analytics&noise=123&category=privacy&empty=&encoded%5Fname=value',+ })++ expect(utils.getPath({ search: ['category', 'empty', 'encoded_name'] })).toBe(+ '/products?category=analytics&category=privacy&empty=&encoded%5Fname=value',+ )+ expect(utils.getPath({ search: ['missing'] })).toBe('/products')+ expect(utils.getPath({ search: [] })).toBe('/products')+ })++ test('getPath should include only allowlisted hash values', () => {+ setLocation({ pathname: '/docs', hash: '#installation' })+ expect(utils.getPath({ hash: ['installation', 'configuration'] })).toBe('/docs#installation')+ expect(utils.getPath({ hash: ['#installation'] })).toBe('/docs#installation')+ expect(utils.getPath({ hash: ['configuration'] })).toBe('/docs')++ setLocation({ pathname: '/', hash: '#/dashboard?tab=overview&noise=123' })+ expect(utils.getPath({ hash: ['/dashboard'], search: ['tab'] })).toBe('/#/dashboard?tab=overview')+ })+test('getUTM* functions should extract UTM parameters', () => {setLocation({pathname: '/landing',