🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance tracking script documentation and functionality
Bill Yang07c1ecd0170b
diff --git a/docs/content/docs/script.mdx b/docs/content/docs/script.mdxindex 6569b8df9..428bdbc6c 100644--- a/docs/content/docs/script.mdx+++ b/docs/content/docs/script.mdx@@ -39,8 +39,8 @@ These are the attributes you can pass to the script tag.| Attribute | Type | Default | Description || :---------------- | :--------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `data-skip-patterns` | `string` | `[]` | A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards: `*` (matches within a segment) and `**` (matches across segments). |-| `data-mask-patterns` | `string` | `[]` | A JSON string array of URL path patterns to mask for privacy. Pageviews matching these patterns will be tracked, but the actual URL path will be replaced with the pattern itself in analytics data. Supports the same wildcards as `data-skip-patterns`. |+| `data-skip-patterns` | `string` | `[]` | A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards: `*` (matches within a segment) and `**` (matches across segments), plus regex patterns prefixed with `re:`. |+| `data-mask-patterns` | `string` | `[]` | A JSON string array of URL path patterns to mask for privacy. Pageviews matching these patterns will be tracked, but the actual URL path will be replaced with the pattern itself in analytics data. Supports the same wildcards and `re:` regex patterns as `data-skip-patterns`. || `data-debounce` | `string` | `"500"`| The delay (in milliseconds) before tracking a pageview after URL changes via the History API (`pushState`, `replaceState`). Set to `0` to disable debouncing. |### Session Replay Attributes@@ -73,12 +73,24 @@ Examples:- `/admin/**` matches both `/admin/dashboard` and `/admin/users/list`- `/blog/*/comments` matches `/blog/post-123/comments` but not `/blog/category/post/comments`+Regex patterns are also supported when prefixed with `re:`. The regex is used as-is, so add `^` and `$` if you want a full-path match.++Examples:+- `re:^/users/\\d+$` matches `/users/123` but not `/users/abc`+- `re:^/private/.*$` matches anything under `/private/`+Example usage:```htmldata-skip-patterns='["/admin/**", "/blog/drafts/*", "/preview/**"]'data-mask-patterns='["/users/*/settings", "/accounts/**", "/orders/*/details"]'```+Regex usage:+```html+data-skip-patterns='["re:^/private/.*$"]'+data-mask-patterns='["re:^/users/\\d+/settings$"]'+```+**Example with debugging overrides:**```htmldiff --git a/docs/content/docs/sdks/web.mdx b/docs/content/docs/sdks/web.mdxindex 20f475eb2..5f43948f0 100644--- a/docs/content/docs/sdks/web.mdx+++ b/docs/content/docs/sdks/web.mdx@@ -89,6 +89,9 @@ These settings are controlled through your Rybbit dashboard and cannot be set in| Track Web Vitals | Track Core Web Vitals performance metrics | `false` || Capture Errors | Enable automatic error tracking | `false` || Session Replay | Enable session replay recording | `false` |+| Track Button Clicks | Automatically track button click interactions | `false` |+| Track Copy | Automatically track copy events | `false` |+| Track Form Interactions| Automatically track form submissions and input changes | `false` |If fetching settings fails or times out, the SDK uses sensible defaults.@@ -343,19 +346,17 @@ await rybbit.init({#### Privacy Config Options-| Option | Type | Description |-| :------------------ | :-------------------- | :-------------------------------------------------------------- |-| `maskAllInputs` | `boolean` | Mask all input values (default: `true`) |-| `maskTextSelectors` | `string[]` | CSS selectors for elements whose text should be masked |-| `blockClass` | `string` | CSS class name to block elements from recording |-| `blockSelector` | `string` | CSS selector to block elements from recording |-| `ignoreClass` | `string` | CSS class name to ignore elements from recording |-| `ignoreSelector` | `string` | CSS selector to ignore elements from recording |-| `maskTextClass` | `string` | CSS class name to mask text content |-| `collectFonts` | `boolean` | Whether to collect font information |-| `slimDOMOptions` | `object \| boolean` | Options to reduce DOM snapshot size |-| `batchSize` | `number` | Number of events to batch before sending |-| `batchInterval` | `number` | Interval in milliseconds between batched sends |+| Option | Type | Description |+| :------------------ | :-------------------- | :--------------------------------------------------------------------- |+| `maskAllInputs` | `boolean` | Mask all input values (default: `true`) |+| `maskTextSelectors` | `string[]` | CSS selectors for elements whose text should be masked |+| `blockClass` | `string` | CSS class name to block elements from recording (default: `rr-block`) |+| `blockSelector` | `string` | CSS selector to block elements from recording |+| `ignoreClass` | `string` | CSS class name to ignore elements from recording (default: `rr-ignore`)|+| `ignoreSelector` | `string` | CSS selector to ignore elements from recording |+| `maskTextClass` | `string` | CSS class name to mask text content (default: `rr-mask`) |+| `collectFonts` | `boolean` | Whether to collect font information (default: `true`) |+| `slimDOMOptions` | `object \| boolean` | Options to reduce DOM snapshot size |## User Identification@@ -488,6 +489,24 @@ rybbit.onPageChange((newPath, previousPath) => {Callbacks are only triggered when the pathname actually changes. Multiple calls to the same path won't trigger callbacks repeatedly.</Callout>+## Opting Out++Users can opt out of all tracking by setting a flag in `localStorage` or on the `window` object. When opted out, all tracking calls are silently ignored.++```javascript+// Opt out via localStorage (persists across sessions)+localStorage.setItem("disable-rybbit", "true");++// Opt out via window flag (current session only)+window.__RYBBIT_OPTOUT__ = true;+```++To re-enable tracking, remove the localStorage item and reload the page:++```javascript+localStorage.removeItem("disable-rybbit");+```+## CleanupIn Single Page Applications or other dynamic environments, you may need to manually clean up the listeners that the SDK sets up.@@ -533,6 +552,17 @@ These options allow you to control which page paths are tracked and how they app- `*`: Matches any sequence of characters **except** the forward slash (`/`). Useful for matching single path segments.- `**`: Matches any sequence of characters **including** the forward slash (`/`). Useful for matching multiple path segments.+### Regex Patterns++For more advanced matching, you can use raw regular expressions by prefixing the pattern with `re:`:++```javascript+skipPatterns: [+ "re:^/users/\\d+/profile$", // Match numeric user IDs only+ "re:^/api/v[0-9]+/" // Match any API version prefix+]+```+### `skipPatterns`If a page's path matches any pattern in `skipPatterns`, the pageview for that path will **not** be sent.diff --git a/server/src/analytics-script/config.test.ts b/server/src/analytics-script/config.test.tsindex bed1bc448..f056188bc 100644--- a/server/src/analytics-script/config.test.ts+++ b/server/src/analytics-script/config.test.ts@@ -42,6 +42,7 @@ describe("parseScriptConfig", () => {const config = await parseScriptConfig(mockScriptTag);expect(config).toEqual({+ namespace: "rybbit",analyticsHost: "https://analytics.example.com",siteId: "123",debounceDuration: 500,@@ -52,6 +53,9 @@ describe("parseScriptConfig", () => {enableWebVitals: true, // webVitals from APItrackErrors: false, // trackErrors from APIenableSessionReplay: true, // sessionReplay from API+ trackButtonClicks: false,+ trackCopy: false,+ trackFormInteractions: false,skipPatterns: [],maskPatterns: [],sessionReplayBatchInterval: 5000,@@ -68,6 +72,7 @@ describe("parseScriptConfig", () => {sessionReplayCollectFonts: undefined,sessionReplaySampling: undefined,sessionReplaySlimDOMOptions: undefined,+ sessionReplaySampleRate: undefined,});expect(global.fetch).toHaveBeenCalledWith(@@ -92,6 +97,7 @@ describe("parseScriptConfig", () => {const config = await parseScriptConfig(mockScriptTag);expect(config).toEqual({+ namespace: "rybbit",analyticsHost: "https://analytics.example.com",siteId: "123",debounceDuration: 500,@@ -102,6 +108,9 @@ describe("parseScriptConfig", () => {enableWebVitals: false,trackErrors: false,enableSessionReplay: false,+ trackButtonClicks: false,+ trackCopy: false,+ trackFormInteractions: false,skipPatterns: [],maskPatterns: [],sessionReplayBatchInterval: 5000,@@ -117,6 +126,7 @@ describe("parseScriptConfig", () => {sessionReplayCollectFonts: undefined,sessionReplaySampling: undefined,sessionReplaySlimDOMOptions: undefined,+ sessionReplaySampleRate: undefined,});expect(consoleWarnSpy).toHaveBeenCalledWith(@@ -134,6 +144,7 @@ describe("parseScriptConfig", () => {const config = await parseScriptConfig(mockScriptTag);expect(config).toEqual({+ namespace: "rybbit",analyticsHost: "https://analytics.example.com",siteId: "123",debounceDuration: 500,@@ -144,6 +155,9 @@ describe("parseScriptConfig", () => {enableWebVitals: false,trackErrors: false,enableSessionReplay: false,+ trackButtonClicks: false,+ trackCopy: false,+ trackFormInteractions: false,skipPatterns: [],maskPatterns: [],sessionReplayBatchInterval: 5000,@@ -159,6 +173,7 @@ describe("parseScriptConfig", () => {sessionReplayCollectFonts: undefined,sessionReplaySampling: undefined,sessionReplaySlimDOMOptions: undefined,+ sessionReplaySampleRate: undefined,});expect(consoleWarnSpy).toHaveBeenCalledWith(diff --git a/server/src/analytics-script/tracking.test.ts b/server/src/analytics-script/tracking.test.tsindex 7448e6986..5705dfc68 100644--- a/server/src/analytics-script/tracking.test.ts+++ b/server/src/analytics-script/tracking.test.ts@@ -144,6 +144,19 @@ describe("Tracker", () => {expect(payload?.pathname).toBe("/user/*/profile");});+ it("should support regex skip and mask patterns", () => {+ config.skipPatterns = ["re:^/private/.*$"];+ config.maskPatterns = ["re:^/user/\\d+/profile$"];+ tracker = new Tracker(config);++ mockLocation.pathname = "/private/settings";+ expect(tracker.createBasePayload()).toBeNull();++ mockLocation.pathname = "/user/123/profile";+ const payload = tracker.createBasePayload();+ expect(payload?.pathname).toBe("re:^/user/\\d+/profile$");+ });+it("should exclude querystring when disabled", () => {config.trackQuerystring = false;tracker = new Tracker(config);diff --git a/server/src/analytics-script/utils.test.ts b/server/src/analytics-script/utils.test.tsindex 41dc2ce88..71fccc63a 100644--- a/server/src/analytics-script/utils.test.ts+++ b/server/src/analytics-script/utils.test.ts@@ -35,14 +35,21 @@ describe("utils", () => {expect(regex.test("/api/v1/users/admin/settings/config.json")).toBe(true);expect(regex.test("/api/v1/posts/123/data.json")).toBe(false);});++ it("should allow regex patterns with re: prefix", () => {+ const regex = patternToRegex("re:^/users/\\d+$");+ expect(regex.test("/users/123")).toBe(true);+ expect(regex.test("/users/abc")).toBe(false);+ });});describe("findMatchingPattern", () => {- const patterns = ["/api/*/users", "/admin/**", "*.json"];+ const patterns = ["/api/*/users", "/admin/**", "*.json", "re:^/users/\\d+$"];it("should find matching pattern", () => {expect(findMatchingPattern("/api/v1/users", patterns)).toBe("/api/*/users");expect(findMatchingPattern("/admin/settings/general", patterns)).toBe("/admin/**");+ expect(findMatchingPattern("/users/42", patterns)).toBe("re:^/users/\\d+$");});it("should return null for no match", () => {@@ -51,7 +58,7 @@ describe("utils", () => {it("should handle invalid patterns gracefully", () => {const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});- const invalidPatterns = ["[invalid"];+ const invalidPatterns = ["[invalid", "re:(unclosed"];expect(findMatchingPattern("/test", invalidPatterns)).toBe(null);consoleSpy.mockRestore();});diff --git a/server/src/analytics-script/utils.ts b/server/src/analytics-script/utils.tsindex 2fbc0ef17..ccca6c4a4 100644--- a/server/src/analytics-script/utils.ts+++ b/server/src/analytics-script/utils.ts@@ -2,6 +2,15 @@* Convert wildcard pattern to regex*/export function patternToRegex(pattern: string): RegExp {+ const REGEX_PREFIX = "re:";+ if (pattern.startsWith(REGEX_PREFIX)) {+ const rawRegex = pattern.slice(REGEX_PREFIX.length);+ if (!rawRegex) {+ throw new Error("Empty regex pattern");+ }+ return new RegExp(rawRegex);+ }+const DOUBLE_WILDCARD_TOKEN = "__DOUBLE_ASTERISK_TOKEN__";const SINGLE_WILDCARD_TOKEN = "__SINGLE_ASTERISK_TOKEN__";