@lensx/tracking 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +18 -0
- package/README.md +197 -2
- package/dist/config.d.ts +56 -0
- package/dist/config.js +106 -0
- package/dist/events.d.ts +16 -0
- package/dist/events.js +45 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +270 -0
- package/dist/network.d.ts +27 -0
- package/dist/network.js +50 -0
- package/dist/react.d.ts +52 -0
- package/dist/react.js +116 -0
- package/dist/redact.d.ts +9 -0
- package/dist/redact.js +62 -0
- package/package.json +44 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 the @lensx/tracking authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
|
6
|
+
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
|
7
|
+
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
|
9
|
+
following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial
|
|
12
|
+
portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
|
15
|
+
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
16
|
+
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
17
|
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
|
18
|
+
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,198 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lensx/tracking
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Privacy-first session recording for web apps, on top of the [OpenReplay](https://openreplay.com) web tracker
|
|
4
|
+
(self-hosted or cloud). One package gives every project the same setup: a consent gate, mask-everything
|
|
5
|
+
privacy defaults, safe network capture, typed events and a link between frontend replays and backend errors.
|
|
6
|
+
|
|
7
|
+
Built and tested against **`@openreplay/tracker` 19.2.0** (pinned) and **OpenReplay server 1.28.0**.
|
|
8
|
+
Not an official OpenReplay package.
|
|
9
|
+
|
|
10
|
+
- **Consent first**: nothing is recorded until the visitor agrees; the answer is remembered.
|
|
11
|
+
- **Masked by default**: all page text and every input are masked; you unmask only public parts.
|
|
12
|
+
- **Safe network capture**: auth/payment requests dropped, secrets redacted, sensitive headers never stored.
|
|
13
|
+
- **Reliable uploads**: retries a failed start, flushes before navigation, keeps the user ID across reloads.
|
|
14
|
+
- **Backend correlation**: your API receives the session token header, so server errors link to the replay.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm i @lensx/tracking
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
React is an optional peer dependency (needed only for `@lensx/tracking/react`).
|
|
23
|
+
|
|
24
|
+
## Quick start: Next.js (App Router)
|
|
25
|
+
|
|
26
|
+
**1. Environment variables** (`.env.local`; a missing project key turns recording off):
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
NEXT_PUBLIC_OPENREPLAY_PROJECT_KEY=your-project-key
|
|
30
|
+
NEXT_PUBLIC_OPENREPLAY_INGEST_POINT=https://openreplay.example.com/ingest
|
|
31
|
+
NEXT_PUBLIC_API_URL=https://api.example.com
|
|
32
|
+
NEXT_PUBLIC_TRACKING_ENV=production # local | staging | production
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
**2. Provider** (a client component that wraps the app, e.g. in `app/layout.tsx`):
|
|
36
|
+
|
|
37
|
+
```tsx
|
|
38
|
+
'use client';
|
|
39
|
+
|
|
40
|
+
import { createTrackingConfig } from '@lensx/tracking';
|
|
41
|
+
import { ConsentBanner, TrackingProvider } from '@lensx/tracking/react';
|
|
42
|
+
|
|
43
|
+
// Next.js inlines NEXT_PUBLIC_* only when written out literally.
|
|
44
|
+
const trackingConfig = createTrackingConfig({
|
|
45
|
+
projectKey: process.env.NEXT_PUBLIC_OPENREPLAY_PROJECT_KEY,
|
|
46
|
+
ingestPoint: process.env.NEXT_PUBLIC_OPENREPLAY_INGEST_POINT,
|
|
47
|
+
apiUrl: process.env.NEXT_PUBLIC_API_URL,
|
|
48
|
+
env: process.env.NEXT_PUBLIC_TRACKING_ENV,
|
|
49
|
+
appVersion: process.env.NEXT_PUBLIC_APP_VERSION,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
export function Providers({ children }: { children: React.ReactNode }) {
|
|
53
|
+
return (
|
|
54
|
+
<TrackingProvider config={trackingConfig}>
|
|
55
|
+
{children}
|
|
56
|
+
<ConsentBanner />
|
|
57
|
+
</TrackingProvider>
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
**3. Unmask public parts** (everything else stays masked in replays):
|
|
63
|
+
|
|
64
|
+
```tsx
|
|
65
|
+
<header data-openreplay-unmask>…</header>
|
|
66
|
+
<footer data-openreplay-unmask>…</footer>
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
That is the whole integration.
|
|
70
|
+
|
|
71
|
+
## Quick start: Vite / other React apps
|
|
72
|
+
|
|
73
|
+
Same as Next.js, with your bundler's env access:
|
|
74
|
+
|
|
75
|
+
```tsx
|
|
76
|
+
const trackingConfig = createTrackingConfig({
|
|
77
|
+
projectKey: import.meta.env.VITE_OPENREPLAY_PROJECT_KEY,
|
|
78
|
+
ingestPoint: import.meta.env.VITE_OPENREPLAY_INGEST_POINT,
|
|
79
|
+
apiUrl: import.meta.env.VITE_API_URL,
|
|
80
|
+
env: import.meta.env.VITE_TRACKING_ENV,
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Without React
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
import { configureTracking, createTrackingConfig, setConsent } from '@lensx/tracking';
|
|
88
|
+
|
|
89
|
+
const config = createTrackingConfig({ projectKey, ingestPoint, apiUrl, env: 'production' });
|
|
90
|
+
if (config) configureTracking(config);
|
|
91
|
+
|
|
92
|
+
// from your own consent UI; nothing is recorded before this
|
|
93
|
+
await setConsent(true); // false stops recording
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Consent banner
|
|
97
|
+
|
|
98
|
+
`<ConsentBanner />` shows only while the visitor has not answered, and only when recording is configured.
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
<ConsentBanner text="We record visits to improve the site." allowLabel="OK" declineLabel="No" />
|
|
102
|
+
|
|
103
|
+
// your own styling
|
|
104
|
+
<ConsentBanner className="my-banner" />
|
|
105
|
+
|
|
106
|
+
// your own components
|
|
107
|
+
<ConsentBanner
|
|
108
|
+
render={({ accept, decline, text }) => (
|
|
109
|
+
<>
|
|
110
|
+
<p>{text}</p>
|
|
111
|
+
<Button variant="outline" onClick={decline}>No thanks</Button>
|
|
112
|
+
<Button onClick={accept}>Allow</Button>
|
|
113
|
+
</>
|
|
114
|
+
)}
|
|
115
|
+
/>
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Or build your own with `useTracking()`: `consent` (`unknown` | `granted` | `denied`), `accept()`, `decline()`,
|
|
119
|
+
`recording`, `enabled`.
|
|
120
|
+
|
|
121
|
+
## Users, events and errors
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
const t = useTracking(); // or import the functions directly
|
|
125
|
+
|
|
126
|
+
t.identify(user.id); // internal ID only, never email or phone
|
|
127
|
+
t.resetUser(); // on logout: ends the session, starts a fresh anonymous one
|
|
128
|
+
t.track('checkout_started', { items: 3 });
|
|
129
|
+
t.reportError(error, { orderId });
|
|
130
|
+
t.replayUrl(); // link to the current replay, e.g. for support tickets
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Call `identify()` as soon as the app knows the user, including on page load for a signed-in user, not
|
|
134
|
+
only after recording starts. Then the tracker's start request carries the ID, and a full page load right
|
|
135
|
+
after cannot lose it.
|
|
136
|
+
|
|
137
|
+
| Function | What it does |
|
|
138
|
+
| ---------------------------------- | ---------------------------------------------------------------------------- |
|
|
139
|
+
| `createTrackingConfig(setup)` | Config from plain values; `null` (off) without project key or ingest point. |
|
|
140
|
+
| `configureTracking(cfg)` | Validates config. Records nothing yet. |
|
|
141
|
+
| `setConsent(granted)` | `true` starts the tracker; `false` stops it. Resolves `true` when recording. |
|
|
142
|
+
| `identify(userId)` / `resetUser()` | Set the user; on logout end the session and start a fresh one. |
|
|
143
|
+
| `setMetadata(key, value)` | Keys from `METADATA_KEYS`; add each key in the OpenReplay project settings. |
|
|
144
|
+
| `track(event, payload?)` | Custom event; names from `ALLOWED_EVENTS` so funnels match across projects. |
|
|
145
|
+
| `trackIssue(name, payload?)` | Handled failure shown as an issue. |
|
|
146
|
+
| `reportError(error, metadata?)` | Caught error with stack trace. |
|
|
147
|
+
| `replayUrl()` / `sessionId()` | Link to the current replay; session ID for logs. |
|
|
148
|
+
| `flushBeforeNavigation()` | Sends pending data before a full page navigation (e.g. to a payment page). |
|
|
149
|
+
|
|
150
|
+
## Privacy defaults
|
|
151
|
+
|
|
152
|
+
- **All page text masked** except inside `data-openreplay-unmask`. Implemented as a sanitizer rule, not the
|
|
153
|
+
tracker's `privateMode`, which also wipes page URLs and titles and so breaks funnels, journeys and heatmaps.
|
|
154
|
+
- **Every input masked**, whatever its type. `data-openreplay-hidden` removes an element from replays
|
|
155
|
+
entirely; `data-openreplay-obscured` masks it even inside an unmasked area.
|
|
156
|
+
- **No request/response bodies** unless `capturePayload: true`. With it on, `/auth/` and `/payments/`
|
|
157
|
+
requests are dropped and other bodies are redacted (`password`, `token`, `otp`, `cardNumber`, `cvv`,
|
|
158
|
+
`iban`, `nationalId` …).
|
|
159
|
+
- **Headers** `Cookie`, `Set-Cookie`, `Authorization`, `X-API-Key` are never recorded.
|
|
160
|
+
- The session token header (`X-OpenReplay-SessionToken`) goes **only** to `apiUrl` origins. Allow it in your
|
|
161
|
+
API's CORS (`Access-Control-Allow-Headers`).
|
|
162
|
+
|
|
163
|
+
Test it: type known values into your forms, then check the uploads (or the replay) for them.
|
|
164
|
+
|
|
165
|
+
## Backend correlation
|
|
166
|
+
|
|
167
|
+
Your API receives `X-OpenReplay-SessionToken` on requests from recorded sessions. Tag server errors and
|
|
168
|
+
logs with it (e.g. Sentry tag `openReplaySession.id`) and enable the matching OpenReplay integration
|
|
169
|
+
(Sentry, Datadog, Elasticsearch, Dynatrace) to see backend errors inside the replay.
|
|
170
|
+
|
|
171
|
+
## Local development
|
|
172
|
+
|
|
173
|
+
With `env: 'local'`, styles are stored inside each replay (`inlineCss`), and plain `http://localhost` is
|
|
174
|
+
allowed. Any other env requires HTTPS.
|
|
175
|
+
|
|
176
|
+
## Known limits
|
|
177
|
+
|
|
178
|
+
- Chromium cancels uploads still in flight when a tab closes or a full page load starts; the last
|
|
179
|
+
~0.5 s of activity can be lost. Data is sent every 5 s, so this only affects the final moment.
|
|
180
|
+
- Event names are a fixed list (`ALLOWED_EVENTS`) in this version.
|
|
181
|
+
|
|
182
|
+
## Compatibility
|
|
183
|
+
|
|
184
|
+
| Package | Tracker | OpenReplay server |
|
|
185
|
+
| ------- | ------- | ----------------- |
|
|
186
|
+
| 0.2.x | 19.2.0 | 1.28.x |
|
|
187
|
+
|
|
188
|
+
## Develop (monorepo)
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
pnpm --filter @lensx/tracking test
|
|
192
|
+
pnpm --filter @lensx/tracking build
|
|
193
|
+
scripts/publish-tracking.sh <version>
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
## License
|
|
197
|
+
|
|
198
|
+
MIT
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Options } from '@openreplay/tracker';
|
|
2
|
+
export type TrackingEnv = 'local' | 'staging' | 'production';
|
|
3
|
+
export interface TrackingConfig {
|
|
4
|
+
projectKey: string;
|
|
5
|
+
/** OpenReplay ingest URL, e.g. `https://openreplay.example.com/ingest`. */
|
|
6
|
+
ingestPoint: string;
|
|
7
|
+
/** Our own API base URLs; only these get the `X-OpenReplay-SessionToken` header. */
|
|
8
|
+
apiBaseUrls: string[];
|
|
9
|
+
env: TrackingEnv;
|
|
10
|
+
/** App release, shown in OpenReplay as revID. */
|
|
11
|
+
appVersion?: string;
|
|
12
|
+
/** Record request/response bodies. Off by default; turn on per project after the sanitizer review. */
|
|
13
|
+
capturePayload?: boolean;
|
|
14
|
+
/** Paths dropped from network recordings. Default: `/auth/`, `/payments/`. */
|
|
15
|
+
droppedPaths?: string[];
|
|
16
|
+
/** Only for test apps served on plain `http://localhost`. Ignored unless `env` is `local`. */
|
|
17
|
+
allowInsecureLocalhost?: boolean;
|
|
18
|
+
/** Tracker console log level (0 off … 5 verbose). */
|
|
19
|
+
debugLevel?: 0 | 2 | 3 | 4 | 5;
|
|
20
|
+
/**
|
|
21
|
+
* How often to push recorded data to the server, in ms (default 5000, 0 = tracker default).
|
|
22
|
+
* The tracker's worker only sends every 30 s, and Chromium can kill the worker before its
|
|
23
|
+
* last send when a page closes or reloads, losing up to 30 s.
|
|
24
|
+
*/
|
|
25
|
+
flushIntervalMs?: number;
|
|
26
|
+
}
|
|
27
|
+
export declare const DEFAULT_FLUSH_INTERVAL_MS = 5000;
|
|
28
|
+
/** Plain values, usually straight from env vars (e.g. `process.env.NEXT_PUBLIC_OPENREPLAY_PROJECT_KEY`). */
|
|
29
|
+
export interface TrackingSetup {
|
|
30
|
+
projectKey?: string;
|
|
31
|
+
ingestPoint?: string;
|
|
32
|
+
/** Base URL of the app's own API; only it gets the session header that links backend errors. */
|
|
33
|
+
apiUrl?: string | string[];
|
|
34
|
+
/** `local`, `staging` or `production` (default `production`). */
|
|
35
|
+
env?: string;
|
|
36
|
+
appVersion?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Builds the config from plain setup values; `null` (recording off) when the project key or
|
|
40
|
+
* ingest point is missing, so an environment without them simply does not record.
|
|
41
|
+
* `local` also allows plain `http://localhost`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function createTrackingConfig(setup: TrackingSetup): TrackingConfig | null;
|
|
44
|
+
export declare const UNMASK_SELECTOR = "[data-openreplay-unmask]";
|
|
45
|
+
/**
|
|
46
|
+
* Mask-by-default rule for the tracker's `domSanitizer`. The tracker masks everything inside a
|
|
47
|
+
* masked element, so an element stays plain only when it is inside a safe region or holds one
|
|
48
|
+
* (a layout container around the menu); everything else is masked. Inputs are masked separately
|
|
49
|
+
* by `defaultInputMode`.
|
|
50
|
+
*/
|
|
51
|
+
export declare function maskAllTextExceptUnmasked(el: Pick<Element, 'closest' | 'querySelector'>): 0 | 1;
|
|
52
|
+
/**
|
|
53
|
+
* Builds tracker options from our config. Option names are checked against
|
|
54
|
+
* @openreplay/tracker 19.2.0 (dist/lib/index.d.ts in the package) by the `Partial<Options>` type.
|
|
55
|
+
*/
|
|
56
|
+
export declare function buildTrackerOptions(cfg: TrackingConfig): Partial<Options>;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { DEFAULT_DROPPED_PATHS, IGNORED_HEADERS, createNetworkSanitizer, createTokenUrlMatcher, } from './network.js';
|
|
2
|
+
export const DEFAULT_FLUSH_INTERVAL_MS = 5_000;
|
|
3
|
+
const ENVS = ['local', 'staging', 'production'];
|
|
4
|
+
/**
|
|
5
|
+
* Builds the config from plain setup values; `null` (recording off) when the project key or
|
|
6
|
+
* ingest point is missing, so an environment without them simply does not record.
|
|
7
|
+
* `local` also allows plain `http://localhost`.
|
|
8
|
+
*/
|
|
9
|
+
export function createTrackingConfig(setup) {
|
|
10
|
+
const projectKey = setup.projectKey?.trim();
|
|
11
|
+
const ingestPoint = setup.ingestPoint?.trim();
|
|
12
|
+
if (!projectKey || !ingestPoint)
|
|
13
|
+
return null;
|
|
14
|
+
const env = ENVS.includes(setup.env ?? '')
|
|
15
|
+
? setup.env
|
|
16
|
+
: 'production';
|
|
17
|
+
const apis = (Array.isArray(setup.apiUrl) ? setup.apiUrl : [setup.apiUrl])
|
|
18
|
+
.filter((u) => Boolean(u?.trim()))
|
|
19
|
+
.map((u) => new URL(u).origin);
|
|
20
|
+
return {
|
|
21
|
+
projectKey,
|
|
22
|
+
ingestPoint,
|
|
23
|
+
apiBaseUrls: apis,
|
|
24
|
+
env,
|
|
25
|
+
...(setup.appVersion ? { appVersion: setup.appVersion } : {}),
|
|
26
|
+
allowInsecureLocalhost: env === 'local',
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export const UNMASK_SELECTOR = '[data-openreplay-unmask]';
|
|
30
|
+
const PLAIN = 0; // tracker SanitizeLevel.Plain
|
|
31
|
+
const OBSCURED = 1; // tracker SanitizeLevel.Obscured (text replaced by stars)
|
|
32
|
+
/**
|
|
33
|
+
* Mask-by-default rule for the tracker's `domSanitizer`. The tracker masks everything inside a
|
|
34
|
+
* masked element, so an element stays plain only when it is inside a safe region or holds one
|
|
35
|
+
* (a layout container around the menu); everything else is masked. Inputs are masked separately
|
|
36
|
+
* by `defaultInputMode`.
|
|
37
|
+
*/
|
|
38
|
+
export function maskAllTextExceptUnmasked(el) {
|
|
39
|
+
if (el.closest(UNMASK_SELECTOR))
|
|
40
|
+
return PLAIN;
|
|
41
|
+
if (el.querySelector(UNMASK_SELECTOR))
|
|
42
|
+
return PLAIN;
|
|
43
|
+
return OBSCURED;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Builds tracker options from our config. Option names are checked against
|
|
47
|
+
* @openreplay/tracker 19.2.0 (dist/lib/index.d.ts in the package) by the `Partial<Options>` type.
|
|
48
|
+
*/
|
|
49
|
+
export function buildTrackerOptions(cfg) {
|
|
50
|
+
validate(cfg);
|
|
51
|
+
const local = cfg.env === 'local';
|
|
52
|
+
return {
|
|
53
|
+
projectKey: cfg.projectKey,
|
|
54
|
+
ingestPoint: cfg.ingestPoint,
|
|
55
|
+
...(cfg.appVersion ? { revID: cfg.appVersion } : {}),
|
|
56
|
+
// privacy defaults: mask all page text, then unmask the safe parts in the app with
|
|
57
|
+
// `data-openreplay-unmask` (menus, headings, public product text). The same approach as
|
|
58
|
+
// Sentry Replay and FullStory's private-by-default mode. Not the tracker's `privateMode`:
|
|
59
|
+
// that also wipes page URLs and titles, which breaks funnels, journeys and heatmaps.
|
|
60
|
+
domSanitizer: maskAllTextExceptUnmasked,
|
|
61
|
+
defaultInputMode: 1, // 0 plain, 1 obscured, 2 ignored; every input masked, whatever its type
|
|
62
|
+
obscureTextEmails: true,
|
|
63
|
+
obscureInputEmails: true,
|
|
64
|
+
obscureInputNumbers: true,
|
|
65
|
+
obscureInputDates: true,
|
|
66
|
+
// local development: the server cannot download CSS from a developer machine, so send it inside the replay
|
|
67
|
+
...(local ? { inlineCss: 3 } : {}),
|
|
68
|
+
...(local && cfg.allowInsecureLocalhost ? { __DISABLE_SECURE_MODE: true } : {}),
|
|
69
|
+
...(cfg.debugLevel ? { __debug__: cfg.debugLevel } : {}),
|
|
70
|
+
network: {
|
|
71
|
+
capturePayload: cfg.capturePayload ?? false,
|
|
72
|
+
failuresOnly: false,
|
|
73
|
+
captureInIframes: true,
|
|
74
|
+
ignoreHeaders: IGNORED_HEADERS,
|
|
75
|
+
sessionTokenHeader: true, // X-OpenReplay-SessionToken
|
|
76
|
+
tokenUrlMatcher: createTokenUrlMatcher(cfg.apiBaseUrls),
|
|
77
|
+
sanitizer: createNetworkSanitizer(cfg.droppedPaths ?? DEFAULT_DROPPED_PATHS),
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function validate(cfg) {
|
|
82
|
+
if (!cfg.projectKey)
|
|
83
|
+
throw new Error('@lensx/tracking: projectKey is required');
|
|
84
|
+
let ingest;
|
|
85
|
+
try {
|
|
86
|
+
ingest = new URL(cfg.ingestPoint);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
throw new Error(`@lensx/tracking: ingestPoint is not a URL: ${cfg.ingestPoint}`);
|
|
90
|
+
}
|
|
91
|
+
if (ingest.protocol !== 'https:') {
|
|
92
|
+
throw new Error('@lensx/tracking: ingestPoint must use https');
|
|
93
|
+
}
|
|
94
|
+
for (const base of cfg.apiBaseUrls) {
|
|
95
|
+
try {
|
|
96
|
+
new URL(base);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
throw new Error(`@lensx/tracking: apiBaseUrls entry must be an absolute URL: ${base}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (cfg.allowInsecureLocalhost && cfg.env !== 'local') {
|
|
103
|
+
throw new Error('@lensx/tracking: allowInsecureLocalhost is only allowed when env is local');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=config.js.map
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard event names. Funnels in OpenReplay match on exact strings, so projects that use the
|
|
3
|
+
* same names can compare funnels. Custom names are allowed too (see `isValidEventName`).
|
|
4
|
+
*/
|
|
5
|
+
export declare const ALLOWED_EVENTS: readonly ["login_succeeded", "login_failed", "logout", "signup_completed", "product_viewed", "cart_added", "cart_removed", "checkout_started", "checkout_completed", "payment_failed", "booking_started", "booking_completed", "booking_failed", "course_viewed", "course_enrolled", "lesson_started", "lesson_completed", "search_performed", "form_submitted", "contact_submitted", "newsletter_subscribed", "web_vital"];
|
|
6
|
+
/** One of the standard names. */
|
|
7
|
+
export type AllowedEvent = (typeof ALLOWED_EVENTS)[number];
|
|
8
|
+
/** A standard name (autocompleted) or a custom snake_case name. */
|
|
9
|
+
export type EventName = AllowedEvent | (string & {});
|
|
10
|
+
export declare function isAllowedEvent(name: string): name is AllowedEvent;
|
|
11
|
+
/** snake_case, starts with a letter, 2–64 characters: e.g. `booking_started`. */
|
|
12
|
+
export declare function isValidEventName(name: string): boolean;
|
|
13
|
+
/** Standard metadata keys. Each key must also be added in the OpenReplay project settings (max 10). */
|
|
14
|
+
export declare const METADATA_KEYS: readonly ["env", "plan", "tenant", "app_version"];
|
|
15
|
+
/** A standard key (autocompleted) or a custom one. */
|
|
16
|
+
export type MetadataKey = (typeof METADATA_KEYS)[number] | (string & {});
|
package/dist/events.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard event names. Funnels in OpenReplay match on exact strings, so projects that use the
|
|
3
|
+
* same names can compare funnels. Custom names are allowed too (see `isValidEventName`).
|
|
4
|
+
*/
|
|
5
|
+
export const ALLOWED_EVENTS = [
|
|
6
|
+
// auth
|
|
7
|
+
'login_succeeded',
|
|
8
|
+
'login_failed',
|
|
9
|
+
'logout',
|
|
10
|
+
'signup_completed',
|
|
11
|
+
// commerce
|
|
12
|
+
'product_viewed',
|
|
13
|
+
'cart_added',
|
|
14
|
+
'cart_removed',
|
|
15
|
+
'checkout_started',
|
|
16
|
+
'checkout_completed',
|
|
17
|
+
'payment_failed',
|
|
18
|
+
// bookings
|
|
19
|
+
'booking_started',
|
|
20
|
+
'booking_completed',
|
|
21
|
+
'booking_failed',
|
|
22
|
+
// learning
|
|
23
|
+
'course_viewed',
|
|
24
|
+
'course_enrolled',
|
|
25
|
+
'lesson_started',
|
|
26
|
+
'lesson_completed',
|
|
27
|
+
// generic
|
|
28
|
+
'search_performed',
|
|
29
|
+
'form_submitted',
|
|
30
|
+
'contact_submitted',
|
|
31
|
+
'newsletter_subscribed',
|
|
32
|
+
'web_vital',
|
|
33
|
+
];
|
|
34
|
+
const allowed = new Set(ALLOWED_EVENTS);
|
|
35
|
+
const EVENT_NAME = /^[a-z][a-z0-9_]{1,63}$/;
|
|
36
|
+
export function isAllowedEvent(name) {
|
|
37
|
+
return allowed.has(name);
|
|
38
|
+
}
|
|
39
|
+
/** snake_case, starts with a letter, 2–64 characters: e.g. `booking_started`. */
|
|
40
|
+
export function isValidEventName(name) {
|
|
41
|
+
return EVENT_NAME.test(name);
|
|
42
|
+
}
|
|
43
|
+
/** Standard metadata keys. Each key must also be added in the OpenReplay project settings (max 10). */
|
|
44
|
+
export const METADATA_KEYS = ['env', 'plan', 'tenant', 'app_version'];
|
|
45
|
+
//# sourceMappingURL=events.js.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type TrackingConfig } from './config.js';
|
|
2
|
+
import { type EventName, type MetadataKey } from './events.js';
|
|
3
|
+
export { buildTrackerOptions, createTrackingConfig, DEFAULT_FLUSH_INTERVAL_MS, type TrackingConfig, type TrackingSetup, type TrackingEnv, } from './config.js';
|
|
4
|
+
export { ALLOWED_EVENTS, METADATA_KEYS, isAllowedEvent, isValidEventName } from './events.js';
|
|
5
|
+
export type { AllowedEvent, EventName, MetadataKey } from './events.js';
|
|
6
|
+
export { redact, REDACTED, SENSITIVE_KEYS, isSensitiveKey } from './redact.js';
|
|
7
|
+
export { createNetworkSanitizer, createTokenUrlMatcher, IGNORED_HEADERS, DEFAULT_DROPPED_PATHS, type NetworkRecord, } from './network.js';
|
|
8
|
+
type Payload = Record<string, unknown>;
|
|
9
|
+
/**
|
|
10
|
+
* No forced flush this soon after start, so the first page snapshot goes out undisturbed.
|
|
11
|
+
* A flush asked for inside the window is postponed to its end, never dropped: dropping it
|
|
12
|
+
* would leave the actions right after a page reload unsent until the tab closes, and
|
|
13
|
+
* Chromium cancels uploads made at tab close.
|
|
14
|
+
*/
|
|
15
|
+
export declare const FLUSH_GRACE_AFTER_START_MS = 3000;
|
|
16
|
+
/** Call once at app start. Records nothing until `setConsent(true)`. */
|
|
17
|
+
export declare function configureTracking(config: TrackingConfig): void;
|
|
18
|
+
/**
|
|
19
|
+
* Consent gate. Nothing is recorded or buffered before the user accepts (the tracker's
|
|
20
|
+
* `coldStart()` is not used: it records before consent).
|
|
21
|
+
* Resolves to true when recording is running.
|
|
22
|
+
*/
|
|
23
|
+
export declare function setConsent(granted: boolean): Promise<boolean>;
|
|
24
|
+
/** Waits before each retry of a failed start (ms). */
|
|
25
|
+
export declare const START_RETRY_DELAYS_MS: readonly [1000, 3000, 7000];
|
|
26
|
+
/**
|
|
27
|
+
* Network and server (5xx) failures are worth retrying; configuration problems (no worker,
|
|
28
|
+
* 4xx, already started, canceled) are not. The tracker itself never retries a failed start,
|
|
29
|
+
* and a network blip during a page reload (e.g. Chromium's ERR_NETWORK_IO_SUSPENDED) would
|
|
30
|
+
* otherwise leave the whole page unrecorded.
|
|
31
|
+
*/
|
|
32
|
+
export declare function isRetryableStartFailure(reason: string): boolean;
|
|
33
|
+
export declare function hasConsent(): boolean;
|
|
34
|
+
/** Our internal user ID only, never an email or phone number. */
|
|
35
|
+
export declare function identify(userId: string): void;
|
|
36
|
+
/** On logout: end this session and start a fresh one so the next user is not merged in. */
|
|
37
|
+
export declare function resetUser(): Promise<void>;
|
|
38
|
+
/** The key must also exist in the OpenReplay project's metadata settings. */
|
|
39
|
+
export declare function setMetadata(key: MetadataKey, value: string): void;
|
|
40
|
+
/** A standard name from `ALLOWED_EVENTS`, or a custom snake_case name (e.g. `booking_started`). */
|
|
41
|
+
export declare function track(name: EventName, payload?: Payload): void;
|
|
42
|
+
/**
|
|
43
|
+
* Call before a full page load that the app starts itself (`window.location = …`, a form
|
|
44
|
+
* post, a redirect to a payment page). Chromium cancels the tracker worker's pending
|
|
45
|
+
* uploads when the page unloads, so the last 1–3 s are lost otherwise. Sends what is pending and waits up to `maxWaitMs`. Client-side routing
|
|
46
|
+
* (Next.js `router.push`, React Router) does not need this.
|
|
47
|
+
*/
|
|
48
|
+
export declare function flushBeforeNavigation(maxWaitMs?: number): Promise<void>;
|
|
49
|
+
export declare function trackIssue(name: string, payload?: Payload): void;
|
|
50
|
+
export declare function reportError(error: Error, metadata?: Payload): void;
|
|
51
|
+
export declare function replayUrl(withCurrentTime?: boolean): string | undefined;
|
|
52
|
+
export declare function sessionId(): string | undefined;
|
|
53
|
+
/** @internal Test helper: forget all state. */
|
|
54
|
+
export declare function __resetTrackingForTests(): void;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import Tracker from '@openreplay/tracker';
|
|
2
|
+
import { DEFAULT_FLUSH_INTERVAL_MS, buildTrackerOptions } from './config.js';
|
|
3
|
+
import { isValidEventName } from './events.js';
|
|
4
|
+
export { buildTrackerOptions, createTrackingConfig, DEFAULT_FLUSH_INTERVAL_MS, } from './config.js';
|
|
5
|
+
export { ALLOWED_EVENTS, METADATA_KEYS, isAllowedEvent, isValidEventName } from './events.js';
|
|
6
|
+
export { redact, REDACTED, SENSITIVE_KEYS, isSensitiveKey } from './redact.js';
|
|
7
|
+
export { createNetworkSanitizer, createTokenUrlMatcher, IGNORED_HEADERS, DEFAULT_DROPPED_PATHS, } from './network.js';
|
|
8
|
+
const state = {
|
|
9
|
+
cfg: null,
|
|
10
|
+
tracker: null,
|
|
11
|
+
consent: false,
|
|
12
|
+
userId: null,
|
|
13
|
+
metadata: {},
|
|
14
|
+
flushTimer: null,
|
|
15
|
+
starting: null,
|
|
16
|
+
pending: [],
|
|
17
|
+
activeSince: 0,
|
|
18
|
+
deferredFlush: null,
|
|
19
|
+
};
|
|
20
|
+
/** Enough for a burst of page-load events; later calls are dropped beyond this. */
|
|
21
|
+
const MAX_PENDING = 100;
|
|
22
|
+
/**
|
|
23
|
+
* No forced flush this soon after start, so the first page snapshot goes out undisturbed.
|
|
24
|
+
* A flush asked for inside the window is postponed to its end, never dropped: dropping it
|
|
25
|
+
* would leave the actions right after a page reload unsent until the tab closes, and
|
|
26
|
+
* Chromium cancels uploads made at tab close.
|
|
27
|
+
*/
|
|
28
|
+
export const FLUSH_GRACE_AFTER_START_MS = 3_000;
|
|
29
|
+
/** Flush now, or once at the end of the start window. */
|
|
30
|
+
function forceFlushWhenAllowed(t) {
|
|
31
|
+
if (!t.isActive())
|
|
32
|
+
return;
|
|
33
|
+
const wait = state.activeSince + FLUSH_GRACE_AFTER_START_MS - Date.now();
|
|
34
|
+
if (wait <= 0) {
|
|
35
|
+
t.forceFlushBatch();
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (state.deferredFlush)
|
|
39
|
+
return; // one is already planned
|
|
40
|
+
state.deferredFlush = setTimeout(() => {
|
|
41
|
+
state.deferredFlush = null;
|
|
42
|
+
if (state.tracker === t && t.isActive())
|
|
43
|
+
t.forceFlushBatch();
|
|
44
|
+
}, wait);
|
|
45
|
+
}
|
|
46
|
+
function clearDeferredFlush() {
|
|
47
|
+
if (state.deferredFlush)
|
|
48
|
+
clearTimeout(state.deferredFlush);
|
|
49
|
+
state.deferredFlush = null;
|
|
50
|
+
}
|
|
51
|
+
const isBrowser = () => typeof window !== 'undefined';
|
|
52
|
+
/**
|
|
53
|
+
* Push recorded data to the server now. Waits a moment first: the tracker hands new
|
|
54
|
+
* messages to its worker on the next frame, so an immediate flush would miss them.
|
|
55
|
+
*/
|
|
56
|
+
function flushSoon() {
|
|
57
|
+
setTimeout(() => {
|
|
58
|
+
if (state.tracker)
|
|
59
|
+
forceFlushWhenAllowed(state.tracker);
|
|
60
|
+
}, 150);
|
|
61
|
+
}
|
|
62
|
+
function startFlushTimer() {
|
|
63
|
+
stopFlushTimer();
|
|
64
|
+
const ms = state.cfg?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
|
|
65
|
+
if (ms <= 0)
|
|
66
|
+
return;
|
|
67
|
+
state.flushTimer = setInterval(() => {
|
|
68
|
+
if (state.tracker)
|
|
69
|
+
forceFlushWhenAllowed(state.tracker);
|
|
70
|
+
}, ms);
|
|
71
|
+
}
|
|
72
|
+
function stopFlushTimer() {
|
|
73
|
+
if (state.flushTimer)
|
|
74
|
+
clearInterval(state.flushTimer);
|
|
75
|
+
state.flushTimer = null;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Runs `fn` now when recording, or right after the tracker finishes starting. Calls made
|
|
79
|
+
* before consent are dropped on purpose: nothing is kept before the user accepts.
|
|
80
|
+
*/
|
|
81
|
+
function whenRecording(fn) {
|
|
82
|
+
const t = state.tracker;
|
|
83
|
+
if (!t || !state.consent)
|
|
84
|
+
return;
|
|
85
|
+
if (state.starting) {
|
|
86
|
+
if (state.pending.length < MAX_PENDING)
|
|
87
|
+
state.pending.push(fn);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
// Outside the start window the tracker decides: it keeps the user ID and metadata for the
|
|
91
|
+
// session even when not yet active (checking isActive() here would lose user IDs).
|
|
92
|
+
fn(t);
|
|
93
|
+
}
|
|
94
|
+
function drainPending(t) {
|
|
95
|
+
const calls = state.pending.splice(0);
|
|
96
|
+
for (const fn of calls) {
|
|
97
|
+
try {
|
|
98
|
+
fn(t);
|
|
99
|
+
}
|
|
100
|
+
catch (e) {
|
|
101
|
+
console.warn('[@lensx/tracking] queued call failed:', e);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (calls.length)
|
|
105
|
+
flushSoon();
|
|
106
|
+
}
|
|
107
|
+
/** Call once at app start. Records nothing until `setConsent(true)`. */
|
|
108
|
+
export function configureTracking(config) {
|
|
109
|
+
buildTrackerOptions(config); // validate early
|
|
110
|
+
state.cfg = config;
|
|
111
|
+
state.metadata.env = config.env;
|
|
112
|
+
if (config.appVersion)
|
|
113
|
+
state.metadata.app_version = config.appVersion;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Consent gate. Nothing is recorded or buffered before the user accepts (the tracker's
|
|
117
|
+
* `coldStart()` is not used: it records before consent).
|
|
118
|
+
* Resolves to true when recording is running.
|
|
119
|
+
*/
|
|
120
|
+
export async function setConsent(granted) {
|
|
121
|
+
state.consent = granted;
|
|
122
|
+
if (!isBrowser() || !state.cfg)
|
|
123
|
+
return false;
|
|
124
|
+
if (!granted) {
|
|
125
|
+
stopFlushTimer();
|
|
126
|
+
clearDeferredFlush();
|
|
127
|
+
state.pending.length = 0;
|
|
128
|
+
if (state.tracker?.isActive())
|
|
129
|
+
state.tracker.stop();
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
state.tracker ??= new Tracker(buildTrackerOptions(state.cfg));
|
|
133
|
+
if (state.tracker.isActive())
|
|
134
|
+
return true;
|
|
135
|
+
state.starting ??= startRecording(state.tracker, {
|
|
136
|
+
metadata: { ...state.metadata },
|
|
137
|
+
...(state.userId ? { userID: state.userId } : {}),
|
|
138
|
+
}).finally(() => {
|
|
139
|
+
state.starting = null;
|
|
140
|
+
});
|
|
141
|
+
return state.starting;
|
|
142
|
+
}
|
|
143
|
+
/** Waits before each retry of a failed start (ms). */
|
|
144
|
+
export const START_RETRY_DELAYS_MS = [1_000, 3_000, 7_000];
|
|
145
|
+
/**
|
|
146
|
+
* Network and server (5xx) failures are worth retrying; configuration problems (no worker,
|
|
147
|
+
* 4xx, already started, canceled) are not. The tracker itself never retries a failed start,
|
|
148
|
+
* and a network blip during a page reload (e.g. Chromium's ERR_NETWORK_IO_SUSPENDED) would
|
|
149
|
+
* otherwise leave the whole page unrecorded.
|
|
150
|
+
*/
|
|
151
|
+
export function isRetryableStartFailure(reason) {
|
|
152
|
+
if (/Server error: 5\d\d/.test(reason))
|
|
153
|
+
return true;
|
|
154
|
+
return /failed to fetch|networkerror|network error|load failed|network request failed|timeout|unknown error/i.test(reason);
|
|
155
|
+
}
|
|
156
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
157
|
+
async function startRecording(tracker, options) {
|
|
158
|
+
for (let attempt = 0;; attempt++) {
|
|
159
|
+
let reason;
|
|
160
|
+
try {
|
|
161
|
+
const result = await tracker.start(options);
|
|
162
|
+
if (result.success) {
|
|
163
|
+
if (!state.consent) {
|
|
164
|
+
// consent was withdrawn while the tracker was starting
|
|
165
|
+
state.pending.length = 0;
|
|
166
|
+
tracker.stop();
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
state.activeSince = Date.now();
|
|
170
|
+
startFlushTimer();
|
|
171
|
+
drainPending(tracker);
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
reason = result.reason;
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
reason = e instanceof Error ? e.message : String(e);
|
|
178
|
+
}
|
|
179
|
+
const delay = START_RETRY_DELAYS_MS[attempt];
|
|
180
|
+
if (delay === undefined || !isRetryableStartFailure(reason) || !state.consent) {
|
|
181
|
+
state.pending.length = 0;
|
|
182
|
+
console.warn('[@lensx/tracking] OpenReplay did not start:', reason);
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
console.warn(`[@lensx/tracking] OpenReplay start failed (${reason}); retrying in ${delay} ms`);
|
|
186
|
+
await sleep(delay);
|
|
187
|
+
// consent withdrawn, or the app replaced the tracker, while we waited
|
|
188
|
+
if (!state.consent || state.tracker !== tracker) {
|
|
189
|
+
state.pending.length = 0;
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
export function hasConsent() {
|
|
195
|
+
return state.consent;
|
|
196
|
+
}
|
|
197
|
+
/** Our internal user ID only, never an email or phone number. */
|
|
198
|
+
export function identify(userId) {
|
|
199
|
+
state.userId = userId;
|
|
200
|
+
whenRecording((t) => t.setUserID(userId));
|
|
201
|
+
flushSoon(); // a login is often followed by a full page load
|
|
202
|
+
}
|
|
203
|
+
/** On logout: end this session and start a fresh one so the next user is not merged in. */
|
|
204
|
+
export async function resetUser() {
|
|
205
|
+
state.userId = null;
|
|
206
|
+
const t = state.tracker;
|
|
207
|
+
if (!t || !state.consent)
|
|
208
|
+
return;
|
|
209
|
+
if (t.isActive())
|
|
210
|
+
t.stop();
|
|
211
|
+
state.starting = startRecording(t, { forceNew: true, metadata: { ...state.metadata } }).finally(() => {
|
|
212
|
+
state.starting = null;
|
|
213
|
+
});
|
|
214
|
+
await state.starting;
|
|
215
|
+
}
|
|
216
|
+
/** The key must also exist in the OpenReplay project's metadata settings. */
|
|
217
|
+
export function setMetadata(key, value) {
|
|
218
|
+
state.metadata[key] = value;
|
|
219
|
+
whenRecording((t) => t.setMetadata(key, value));
|
|
220
|
+
}
|
|
221
|
+
/** A standard name from `ALLOWED_EVENTS`, or a custom snake_case name (e.g. `booking_started`). */
|
|
222
|
+
export function track(name, payload) {
|
|
223
|
+
if (!isValidEventName(name)) {
|
|
224
|
+
console.warn(`[@lensx/tracking] event "${name}" ignored: use snake_case, e.g. booking_started`);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
whenRecording((t) => t.event(name, payload));
|
|
228
|
+
flushSoon(); // business events often come right before a redirect
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Call before a full page load that the app starts itself (`window.location = …`, a form
|
|
232
|
+
* post, a redirect to a payment page). Chromium cancels the tracker worker's pending
|
|
233
|
+
* uploads when the page unloads, so the last 1–3 s are lost otherwise. Sends what is pending and waits up to `maxWaitMs`. Client-side routing
|
|
234
|
+
* (Next.js `router.push`, React Router) does not need this.
|
|
235
|
+
*/
|
|
236
|
+
export async function flushBeforeNavigation(maxWaitMs = 1_000) {
|
|
237
|
+
const t = state.tracker;
|
|
238
|
+
if (!t?.isActive())
|
|
239
|
+
return;
|
|
240
|
+
// the tracker hands new messages to its worker on the next frame; wait for that first
|
|
241
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
242
|
+
forceFlushWhenAllowed(t);
|
|
243
|
+
await new Promise((r) => setTimeout(r, Math.max(0, maxWaitMs - 100)));
|
|
244
|
+
}
|
|
245
|
+
export function trackIssue(name, payload) {
|
|
246
|
+
whenRecording((t) => t.issue(name, payload));
|
|
247
|
+
}
|
|
248
|
+
export function reportError(error, metadata) {
|
|
249
|
+
whenRecording((t) => t.handleError(error, metadata));
|
|
250
|
+
}
|
|
251
|
+
export function replayUrl(withCurrentTime = false) {
|
|
252
|
+
return state.tracker?.getSessionURL({ withCurrentTime }) ?? undefined;
|
|
253
|
+
}
|
|
254
|
+
export function sessionId() {
|
|
255
|
+
return state.tracker?.getSessionID() ?? undefined;
|
|
256
|
+
}
|
|
257
|
+
/** @internal Test helper: forget all state. */
|
|
258
|
+
export function __resetTrackingForTests() {
|
|
259
|
+
state.cfg = null;
|
|
260
|
+
state.tracker = null;
|
|
261
|
+
state.consent = false;
|
|
262
|
+
state.userId = null;
|
|
263
|
+
state.metadata = {};
|
|
264
|
+
state.starting = null;
|
|
265
|
+
state.pending = [];
|
|
266
|
+
state.activeSince = 0;
|
|
267
|
+
clearDeferredFlush();
|
|
268
|
+
stopFlushTimer();
|
|
269
|
+
}
|
|
270
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Shape the tracker passes to `network.sanitizer` (tracker 19.2.0, RequestResponseData). */
|
|
2
|
+
export interface NetworkRecord {
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly method: string;
|
|
5
|
+
url: string;
|
|
6
|
+
request: {
|
|
7
|
+
body: string | null;
|
|
8
|
+
headers: Record<string, string>;
|
|
9
|
+
};
|
|
10
|
+
response: {
|
|
11
|
+
body: unknown;
|
|
12
|
+
headers: Record<string, string>;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Header names the tracker must not record. The tracker compares names with
|
|
17
|
+
* `Array.includes`, which is case-sensitive, so we list lowercase and canonical spellings.
|
|
18
|
+
*/
|
|
19
|
+
export declare const IGNORED_HEADERS: string[];
|
|
20
|
+
/** URL path parts whose requests are dropped from recordings entirely. */
|
|
21
|
+
export declare const DEFAULT_DROPPED_PATHS: string[];
|
|
22
|
+
export declare function createNetworkSanitizer(droppedPaths?: readonly string[]): (data: NetworkRecord) => NetworkRecord | null;
|
|
23
|
+
/**
|
|
24
|
+
* Matcher for `network.tokenUrlMatcher`: true only for our own API origins.
|
|
25
|
+
* Each base is normalized to end with `/` so `https://api.x.com.evil.io` does not match `https://api.x.com`.
|
|
26
|
+
*/
|
|
27
|
+
export declare function createTokenUrlMatcher(apiBaseUrls: readonly string[]): (url: string) => boolean;
|
package/dist/network.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { redact } from './redact.js';
|
|
2
|
+
/**
|
|
3
|
+
* Header names the tracker must not record. The tracker compares names with
|
|
4
|
+
* `Array.includes`, which is case-sensitive, so we list lowercase and canonical spellings.
|
|
5
|
+
*/
|
|
6
|
+
export const IGNORED_HEADERS = [
|
|
7
|
+
'cookie',
|
|
8
|
+
'Cookie',
|
|
9
|
+
'set-cookie',
|
|
10
|
+
'Set-Cookie',
|
|
11
|
+
'authorization',
|
|
12
|
+
'Authorization',
|
|
13
|
+
'x-api-key',
|
|
14
|
+
'X-Api-Key',
|
|
15
|
+
'X-API-Key',
|
|
16
|
+
'proxy-authorization',
|
|
17
|
+
'Proxy-Authorization',
|
|
18
|
+
];
|
|
19
|
+
/** URL path parts whose requests are dropped from recordings entirely. */
|
|
20
|
+
export const DEFAULT_DROPPED_PATHS = ['/auth/', '/payments/'];
|
|
21
|
+
export function createNetworkSanitizer(droppedPaths = DEFAULT_DROPPED_PATHS) {
|
|
22
|
+
return function sanitizeRequest(data) {
|
|
23
|
+
const path = pathOf(data.url);
|
|
24
|
+
if (droppedPaths.some((p) => path.includes(p) || path.endsWith(p.replace(/\/$/, '')))) {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
if (data.request.body != null)
|
|
28
|
+
data.request.body = redact(data.request.body);
|
|
29
|
+
if (data.response.body != null)
|
|
30
|
+
data.response.body = redact(data.response.body);
|
|
31
|
+
return data;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Matcher for `network.tokenUrlMatcher`: true only for our own API origins.
|
|
36
|
+
* Each base is normalized to end with `/` so `https://api.x.com.evil.io` does not match `https://api.x.com`.
|
|
37
|
+
*/
|
|
38
|
+
export function createTokenUrlMatcher(apiBaseUrls) {
|
|
39
|
+
const prefixes = apiBaseUrls.map((b) => (b.endsWith('/') ? b : `${b}/`));
|
|
40
|
+
return (url) => prefixes.some((p) => url.startsWith(p) || `${url}/` === p);
|
|
41
|
+
}
|
|
42
|
+
function pathOf(url) {
|
|
43
|
+
try {
|
|
44
|
+
return new URL(url, 'http://relative.invalid').pathname;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return url;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=network.js.map
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import { flushBeforeNavigation, identify, replayUrl, reportError, resetUser, setMetadata, track, trackIssue, type TrackingConfig } from './index.js';
|
|
3
|
+
export type ConsentState = 'unknown' | 'granted' | 'denied';
|
|
4
|
+
export interface TrackingContextValue {
|
|
5
|
+
/** `unknown` until the user answers; show the banner then. */
|
|
6
|
+
consent: ConsentState;
|
|
7
|
+
/** True while a session is being recorded. */
|
|
8
|
+
recording: boolean;
|
|
9
|
+
/** False when config is missing or invalid; tracking calls are then no-ops. */
|
|
10
|
+
enabled: boolean;
|
|
11
|
+
accept: () => Promise<void>;
|
|
12
|
+
decline: () => Promise<void>;
|
|
13
|
+
track: typeof track;
|
|
14
|
+
trackIssue: typeof trackIssue;
|
|
15
|
+
identify: typeof identify;
|
|
16
|
+
resetUser: typeof resetUser;
|
|
17
|
+
setMetadata: typeof setMetadata;
|
|
18
|
+
reportError: typeof reportError;
|
|
19
|
+
replayUrl: typeof replayUrl;
|
|
20
|
+
flushBeforeNavigation: typeof flushBeforeNavigation;
|
|
21
|
+
}
|
|
22
|
+
export declare const CONSENT_STORAGE_KEY = "lensx.tracking.consent";
|
|
23
|
+
export interface TrackingProviderProps {
|
|
24
|
+
/** `null` turns tracking off (e.g. no project key in this environment). */
|
|
25
|
+
config: TrackingConfig | null;
|
|
26
|
+
children: ReactNode;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Configures tracking once and owns the consent state. Recording starts only after
|
|
30
|
+
* `accept()` (or a stored "granted" from a previous visit).
|
|
31
|
+
*/
|
|
32
|
+
export declare function TrackingProvider({ config, children }: TrackingProviderProps): import("react").JSX.Element;
|
|
33
|
+
export declare function useTracking(): TrackingContextValue;
|
|
34
|
+
export interface ConsentBannerProps {
|
|
35
|
+
/** Message shown to the visitor. */
|
|
36
|
+
text?: string;
|
|
37
|
+
allowLabel?: string;
|
|
38
|
+
declineLabel?: string;
|
|
39
|
+
/** Class for the banner box; without it a minimal inline style is used. */
|
|
40
|
+
className?: string;
|
|
41
|
+
/** Full control over the look, e.g. with the app's own Button component. */
|
|
42
|
+
render?: (actions: {
|
|
43
|
+
accept: () => void;
|
|
44
|
+
decline: () => void;
|
|
45
|
+
text: string;
|
|
46
|
+
}) => ReactNode;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Asks before recording starts and remembers the answer on this device. Renders nothing when
|
|
50
|
+
* tracking is off or the visitor already answered. Readable in replays (`data-openreplay-unmask`).
|
|
51
|
+
*/
|
|
52
|
+
export declare function ConsentBanner({ text, allowLabel, declineLabel, className, render, }: ConsentBannerProps): import("react").JSX.Element | null;
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from 'react';
|
|
4
|
+
import { configureTracking, flushBeforeNavigation, identify, replayUrl, reportError, resetUser, setConsent, setMetadata, track, trackIssue, } from './index.js';
|
|
5
|
+
export const CONSENT_STORAGE_KEY = 'lensx.tracking.consent';
|
|
6
|
+
const TrackingContext = createContext(null);
|
|
7
|
+
function readStored() {
|
|
8
|
+
try {
|
|
9
|
+
const v = window.localStorage.getItem(CONSENT_STORAGE_KEY);
|
|
10
|
+
return v === 'granted' || v === 'denied' ? v : 'unknown';
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return 'unknown';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function store(v) {
|
|
17
|
+
try {
|
|
18
|
+
window.localStorage.setItem(CONSENT_STORAGE_KEY, v);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// storage blocked: consent lasts for this page only
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Configures tracking once and owns the consent state. Recording starts only after
|
|
26
|
+
* `accept()` (or a stored "granted" from a previous visit).
|
|
27
|
+
*/
|
|
28
|
+
export function TrackingProvider({ config, children }) {
|
|
29
|
+
const [consent, setConsentState] = useState('unknown');
|
|
30
|
+
const [recording, setRecording] = useState(false);
|
|
31
|
+
const [enabled, setEnabled] = useState(false);
|
|
32
|
+
const configured = useRef(false);
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
if (configured.current)
|
|
35
|
+
return; // React StrictMode runs effects twice in dev
|
|
36
|
+
configured.current = true;
|
|
37
|
+
let ok = false;
|
|
38
|
+
if (config) {
|
|
39
|
+
try {
|
|
40
|
+
configureTracking(config);
|
|
41
|
+
ok = true;
|
|
42
|
+
}
|
|
43
|
+
catch (e) {
|
|
44
|
+
console.warn('[@lensx/tracking] tracking disabled:', e.message);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
setEnabled(ok);
|
|
48
|
+
const stored = readStored();
|
|
49
|
+
setConsentState(stored);
|
|
50
|
+
if (ok && stored === 'granted')
|
|
51
|
+
void setConsent(true).then(setRecording);
|
|
52
|
+
}, [config]);
|
|
53
|
+
const accept = useCallback(async () => {
|
|
54
|
+
store('granted');
|
|
55
|
+
setConsentState('granted');
|
|
56
|
+
setRecording(enabled ? await setConsent(true) : false);
|
|
57
|
+
}, [enabled]);
|
|
58
|
+
const decline = useCallback(async () => {
|
|
59
|
+
store('denied');
|
|
60
|
+
setConsentState('denied');
|
|
61
|
+
await setConsent(false);
|
|
62
|
+
setRecording(false);
|
|
63
|
+
}, []);
|
|
64
|
+
const value = useMemo(() => ({
|
|
65
|
+
consent,
|
|
66
|
+
recording,
|
|
67
|
+
enabled,
|
|
68
|
+
accept,
|
|
69
|
+
decline,
|
|
70
|
+
track,
|
|
71
|
+
trackIssue,
|
|
72
|
+
identify,
|
|
73
|
+
resetUser,
|
|
74
|
+
setMetadata,
|
|
75
|
+
reportError,
|
|
76
|
+
replayUrl,
|
|
77
|
+
flushBeforeNavigation,
|
|
78
|
+
}), [consent, recording, enabled, accept, decline]);
|
|
79
|
+
return _jsx(TrackingContext.Provider, { value: value, children: children });
|
|
80
|
+
}
|
|
81
|
+
export function useTracking() {
|
|
82
|
+
const ctx = useContext(TrackingContext);
|
|
83
|
+
if (!ctx)
|
|
84
|
+
throw new Error('useTracking must be used inside <TrackingProvider>');
|
|
85
|
+
return ctx;
|
|
86
|
+
}
|
|
87
|
+
const DEFAULT_CONSENT_TEXT = 'We record visits anonymously to improve the site. What you type is never recorded.';
|
|
88
|
+
/**
|
|
89
|
+
* Asks before recording starts and remembers the answer on this device. Renders nothing when
|
|
90
|
+
* tracking is off or the visitor already answered. Readable in replays (`data-openreplay-unmask`).
|
|
91
|
+
*/
|
|
92
|
+
export function ConsentBanner({ text = DEFAULT_CONSENT_TEXT, allowLabel = 'Allow', declineLabel = 'No thanks', className, render, }) {
|
|
93
|
+
const t = useTracking();
|
|
94
|
+
if (!t.enabled || t.consent !== 'unknown')
|
|
95
|
+
return null;
|
|
96
|
+
const accept = () => void t.accept();
|
|
97
|
+
const decline = () => void t.decline();
|
|
98
|
+
return (_jsx("div", { role: "dialog", "aria-label": "Session recording consent", "data-openreplay-unmask": true, className: className, style: className ? undefined : BANNER_STYLE, children: render ? (render({ accept, decline, text })) : (_jsxs(_Fragment, { children: [_jsx("p", { style: { margin: 0, flex: 1 }, children: text }), _jsx("button", { type: "button", onClick: decline, "data-testid": "consent-decline", children: declineLabel }), _jsx("button", { type: "button", onClick: accept, "data-testid": "consent-accept", children: allowLabel })] })) }));
|
|
99
|
+
}
|
|
100
|
+
const BANNER_STYLE = {
|
|
101
|
+
position: 'fixed',
|
|
102
|
+
insetInline: 16,
|
|
103
|
+
bottom: 16,
|
|
104
|
+
zIndex: 50,
|
|
105
|
+
display: 'flex',
|
|
106
|
+
flexWrap: 'wrap',
|
|
107
|
+
gap: 8,
|
|
108
|
+
alignItems: 'center',
|
|
109
|
+
padding: 16,
|
|
110
|
+
background: '#fff',
|
|
111
|
+
color: '#111',
|
|
112
|
+
border: '1px solid #ddd',
|
|
113
|
+
borderRadius: 12,
|
|
114
|
+
boxShadow: '0 8px 24px rgba(0,0,0,.12)',
|
|
115
|
+
};
|
|
116
|
+
//# sourceMappingURL=react.js.map
|
package/dist/redact.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Keys whose values never leave the browser. Matched case-insensitively, ignoring `_` and `-`. */
|
|
2
|
+
export declare const SENSITIVE_KEYS: readonly ["password", "passwd", "pass", "secret", "token", "accesstoken", "refreshtoken", "idtoken", "apikey", "authorization", "otp", "pin", "cvv", "cvc", "cardnumber", "pan", "iban", "nationalid", "ssn", "passport"];
|
|
3
|
+
export declare const REDACTED = "[REDACTED]";
|
|
4
|
+
export declare function isSensitiveKey(key: string): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Returns a copy of `value` with sensitive keys replaced by `[REDACTED]`.
|
|
7
|
+
* Strings that hold JSON are parsed, redacted and re-serialized; other strings pass through.
|
|
8
|
+
*/
|
|
9
|
+
export declare function redact<T>(value: T): T;
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** Keys whose values never leave the browser. Matched case-insensitively, ignoring `_` and `-`. */
|
|
2
|
+
export const SENSITIVE_KEYS = [
|
|
3
|
+
'password',
|
|
4
|
+
'passwd',
|
|
5
|
+
'pass',
|
|
6
|
+
'secret',
|
|
7
|
+
'token',
|
|
8
|
+
'accesstoken',
|
|
9
|
+
'refreshtoken',
|
|
10
|
+
'idtoken',
|
|
11
|
+
'apikey',
|
|
12
|
+
'authorization',
|
|
13
|
+
'otp',
|
|
14
|
+
'pin',
|
|
15
|
+
'cvv',
|
|
16
|
+
'cvc',
|
|
17
|
+
'cardnumber',
|
|
18
|
+
'pan',
|
|
19
|
+
'iban',
|
|
20
|
+
'nationalid',
|
|
21
|
+
'ssn',
|
|
22
|
+
'passport',
|
|
23
|
+
];
|
|
24
|
+
export const REDACTED = '[REDACTED]';
|
|
25
|
+
const sensitive = new Set(SENSITIVE_KEYS);
|
|
26
|
+
const MAX_DEPTH = 20;
|
|
27
|
+
export function isSensitiveKey(key) {
|
|
28
|
+
return sensitive.has(key.toLowerCase().replace(/[_-]/g, ''));
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Returns a copy of `value` with sensitive keys replaced by `[REDACTED]`.
|
|
32
|
+
* Strings that hold JSON are parsed, redacted and re-serialized; other strings pass through.
|
|
33
|
+
*/
|
|
34
|
+
export function redact(value) {
|
|
35
|
+
if (typeof value === 'string') {
|
|
36
|
+
const trimmed = value.trim();
|
|
37
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
38
|
+
try {
|
|
39
|
+
return JSON.stringify(redactValue(JSON.parse(trimmed), 0));
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
return redactValue(value, 0);
|
|
48
|
+
}
|
|
49
|
+
function redactValue(value, depth) {
|
|
50
|
+
if (value === null || typeof value !== 'object')
|
|
51
|
+
return value;
|
|
52
|
+
if (depth >= MAX_DEPTH)
|
|
53
|
+
return REDACTED;
|
|
54
|
+
if (Array.isArray(value))
|
|
55
|
+
return value.map((v) => redactValue(v, depth + 1));
|
|
56
|
+
const out = {};
|
|
57
|
+
for (const [k, v] of Object.entries(value)) {
|
|
58
|
+
out[k] = isSensitiveKey(k) ? REDACTED : redactValue(v, depth + 1);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=redact.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensx/tracking",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Company wrapper around the OpenReplay web tracker: config, consent, privacy, events, backend correlation",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./react": {
|
|
14
|
+
"types": "./dist/react.d.ts",
|
|
15
|
+
"import": "./dist/react.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@openreplay/tracker": "19.2.0"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"react": ">=18"
|
|
26
|
+
},
|
|
27
|
+
"peerDependenciesMeta": {
|
|
28
|
+
"react": {
|
|
29
|
+
"optional": true
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"keywords": [
|
|
34
|
+
"openreplay",
|
|
35
|
+
"session-replay",
|
|
36
|
+
"consent",
|
|
37
|
+
"privacy",
|
|
38
|
+
"react",
|
|
39
|
+
"nextjs"
|
|
40
|
+
],
|
|
41
|
+
"sideEffects": false,
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public",
|
|
44
|
+
"registry": "https://registry.npmjs.org"
|
|
45
|
+
}
|
|
46
|
+
}
|