@eventra_dev/eventra-sdk 2.0.14 → 2.1.0
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/README.md +69 -17
- package/dist/index.cjs +176 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +46 -3
- package/dist/index.d.ts +46 -3
- package/dist/index.mjs +176 -18
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
<a href="https://www.npmjs.com/package/@eventra_dev/eventra-sdk"><img alt="npm version" src="https://img.shields.io/npm/v/@eventra_dev/eventra-sdk.svg?style=flat-square&color=blue"></a>
|
|
9
9
|
<a href="https://www.npmjs.com/package/@eventra_dev/eventra-sdk"><img alt="npm downloads" src="https://img.shields.io/npm/dm/@eventra_dev/eventra-sdk.svg?style=flat-square&color=blue"></a>
|
|
10
10
|
<a href="https://github.com/and-1991/eventra-sdk/actions/workflows/test.yml"><img alt="tests" src="https://img.shields.io/github/actions/workflow/status/and-1991/eventra-sdk/test.yml?branch=main&label=tests&style=flat-square&logo=vitest&logoColor=white"></a>
|
|
11
|
-
<img alt="tests passing" src="https://img.shields.io/badge/tests-
|
|
11
|
+
<img alt="tests passing" src="https://img.shields.io/badge/tests-358%20passing-brightgreen?style=flat-square&logo=vitest&logoColor=white">
|
|
12
12
|
<img alt="test suites" src="https://img.shields.io/badge/suites-22-brightgreen?style=flat-square">
|
|
13
13
|
<img alt="coverage" src="https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square&logo=vitest&logoColor=white">
|
|
14
14
|
<img alt="node" src="https://img.shields.io/node/v/@eventra_dev/eventra-sdk?style=flat-square&color=darkgreen&logo=node.js&logoColor=white">
|
|
@@ -85,6 +85,48 @@ The SDK automatically handles:
|
|
|
85
85
|
|
|
86
86
|
---
|
|
87
87
|
|
|
88
|
+
## Identify users
|
|
89
|
+
|
|
90
|
+
Unique users, the Users page and per-user numbers in the dashboard (Top users, users on Declining) need to know whose event it is. Without a `userId` the events still count as uses (dead, new and declining features work as before), but nothing can be counted per user.
|
|
91
|
+
|
|
92
|
+
Already pass `userId` to every `track()`? Nothing to change: it still works and can be mixed with the methods below.
|
|
93
|
+
|
|
94
|
+
**Browser and React Native:** call `identify()` once after sign-in (and when the page loads with a signed-in user), and `reset()` in your sign-out handler. Every following `track()` gets that user:
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
tracker.identify(user.id);
|
|
98
|
+
tracker.track("export.clicked"); // sent with userId = user.id
|
|
99
|
+
|
|
100
|
+
// in your sign-out handler (not while auth is still loading)
|
|
101
|
+
tracker.reset();
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
- The user is kept in `localStorage` (with `persistQueue: false` in memory only, and a user stored earlier is removed), so the first events after a reload are not sent without it.
|
|
105
|
+
- `identify()` and `reset()` reach every open tab of the site. `reset()` also removes a user stored by an earlier visit.
|
|
106
|
+
- The stored user belongs to your API key: another Eventra project on the same site (a third-party widget, say) never sees it or resets it.
|
|
107
|
+
- `getUserId()` returns the current user.
|
|
108
|
+
- In React Native `identify()` works in memory. In Next.js and other SSR apps, call it in client code (an effect), not while rendering on the server.
|
|
109
|
+
|
|
110
|
+
**Everywhere else** (Node, serverless, edge, Deno, Cloudflare Workers) one instance may serve many users at once, so `identify()` is ignored there with one warning. Use `withUser()` for each request instead:
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
// in a request handler (Express, Nest, a serverless function); req.user is set by your auth middleware
|
|
114
|
+
app.post("/invoices", (req: Request & { user?: { id: string } }, res) => {
|
|
115
|
+
tracker.withUser(req.user?.id).track("invoice.created", { properties: { plan: "pro" } }); // undefined: no user
|
|
116
|
+
res.sendStatus(201);
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
`withUser()` returns a light object over the same queue, so making one per request is cheap. It works in every runtime. `withUser(undefined)`, `withUser(null)` or an invalid id give events without a user, never the user of `identify()`. Call it where you track (or keep it in a typed variable): the Eventra CLI finds `tracker.withUser(id).track("x")` and `const t = tracker.withUser(id); t.track("x")`, but not a scope stored on an untyped object such as `req.tracker`.
|
|
121
|
+
|
|
122
|
+
**Which user an event gets:** the `userId` passed to `track()` first (`null` sends the event without a user; an empty or blank one counts as not given), then the user of `withUser()`, then the one of `identify()`. The user is fixed when `track()` is called, so an event tracked just before `reset()` keeps its user.
|
|
123
|
+
|
|
124
|
+
Pass your own internal id (or a hash of it), never an email or a phone number. `identify()` and `withUser()` refuse text that names nobody (`"undefined"`, `"null"`, blanks), which is what `String(user?.id)` gives for a missing user.
|
|
125
|
+
|
|
126
|
+
The SDK warns once when none of the first 50 events has a user id: in a browser bundle that is not built for production, and on a server only when `NODE_ENV` is `development` (Lambda and many containers set none in production). Test runs (`NODE_ENV=test`) never warn. `identifyHint: false` turns it off for an app without signed-in users.
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
88
130
|
## Runtime Behavior
|
|
89
131
|
|
|
90
132
|
Eventra SDK adapts automatically:
|
|
@@ -95,7 +137,7 @@ Eventra SDK adapts automatically:
|
|
|
95
137
|
| Node.js | batching + retry |
|
|
96
138
|
| Serverless (AWS Lambda only) | immediate flush + retry |
|
|
97
139
|
| Edge | batching + retry |
|
|
98
|
-
| Anything else (e.g. Cloudflare Workers) | not distinctly detected
|
|
140
|
+
| Anything else (e.g. Cloudflare Workers) | not distinctly detected - falls back to the same batching + retry path as Node.js |
|
|
99
141
|
|
|
100
142
|
No config needed.
|
|
101
143
|
|
|
@@ -122,7 +164,7 @@ Minimal:
|
|
|
122
164
|
tracker.track("app.loaded");
|
|
123
165
|
```
|
|
124
166
|
|
|
125
|
-
Event names lose NUL, line breaks and half-surrogates (the server removes them too), are trimmed, cut to 64 characters and trimmed again, `userId` is cut to 120 (API limits); a cut never leaves half of an emoji, so the name is the one the CLI catalog holds. A numeric `userId` is written out as text, and `null` or an object means no user id. `properties` are copied when you call `track()`, so changing the object afterwards does not change the event. `track()` never throws: an empty name, or properties that exceed the depth/size limits, are dropped silently and reported via `onEventsDropped` instead. A properties object with more than 50,000 values in all is refused as soon as its keys are listed, without walking it (listing the keys of a huge object is the only cost left: about 0.35 s for a million).
|
|
167
|
+
Event names lose NUL, line breaks and half-surrogates (the server removes them too), are trimmed, cut to 64 characters and trimmed again, `userId` is cut to 120 (API limits); a cut never leaves half of an emoji, so the name is the one the CLI catalog holds. A numeric `userId` is written out as text, and `null` or an object means no user id (`null` also overrides a user set by `identify()` or `withUser()`). `properties` are copied when you call `track()`, so changing the object afterwards does not change the event. `track()` never throws: an empty name, or properties that exceed the depth/size limits, are dropped silently and reported via `onEventsDropped` instead. A properties object with more than 50,000 values in all is refused as soon as its keys are listed, without walking it (listing the keys of a huge object is the only cost left: about 0.35 s for a million).
|
|
126
168
|
|
|
127
169
|
---
|
|
128
170
|
|
|
@@ -223,7 +265,7 @@ const tracker = new Eventra({
|
|
|
223
265
|
});
|
|
224
266
|
```
|
|
225
267
|
|
|
226
|
-
**Privacy note:** persistence stores the pending queue
|
|
268
|
+
**Privacy note:** persistence stores the pending queue - including any `userId`/`properties` you pass to `track()` - as plaintext JSON in `localStorage` so it survives reloads. If that's a concern (e.g. properties may carry PII on a shared/public device), disable it:
|
|
227
269
|
|
|
228
270
|
```ts
|
|
229
271
|
const tracker = new Eventra({
|
|
@@ -252,12 +294,18 @@ const tracker = new Eventra({
|
|
|
252
294
|
});
|
|
253
295
|
|
|
254
296
|
tracker.track("invoice.created");
|
|
297
|
+
|
|
298
|
+
// one process serves many users: bind the user per call or request
|
|
299
|
+
export function onInvoiceCreated(userId: string) {
|
|
300
|
+
tracker.withUser(userId).track("invoice.created");
|
|
301
|
+
}
|
|
255
302
|
```
|
|
256
303
|
|
|
257
304
|
- batching
|
|
258
305
|
- retry
|
|
259
306
|
- auto flush (interval)
|
|
260
307
|
- graceful shutdown support
|
|
308
|
+
- `identify()` is ignored here, use `withUser()` (see [Identify users](#identify-users))
|
|
261
309
|
|
|
262
310
|
---
|
|
263
311
|
|
|
@@ -339,9 +387,10 @@ const tracker = new Eventra({
|
|
|
339
387
|
| exitOnSignal | Node only, default `true`: on `SIGINT`/`SIGTERM` the SDK flushes (bounded by `shutdownTimeoutMs`) and then, when no other listener for the signal exists, re-raises it so the process ends as it would without the SDK; when your app has its own listener the SDK only flushes. `false` only flushes and never re-raises. See [Shutdown](#shutdown) |
|
|
340
388
|
| shutdownTimeoutMs | Total time `shutdown()` may spend flushing (default: 10000). It gives up after this, so a dead or rate-limited server cannot hold a `SIGTERM` shutdown past your grace period |
|
|
341
389
|
| diagnostics | Report delivery problems (counts only) with the next successful batch, default `true`; `false` sends nothing extra. See [Delivery diagnostics](#delivery-diagnostics) |
|
|
342
|
-
| persistQueue | Persist the queue to `localStorage` in the browser (browser only, default: `true`)
|
|
390
|
+
| persistQueue | Persist the queue to `localStorage` in the browser (browser only, default: `true`) - `false` keeps it in-memory only, avoiding writing `userId`/`properties` to disk (the user of `identify()` is then kept in memory too) |
|
|
391
|
+
| identifyHint | Warn once when none of the first 50 events has a user id (default: `true`): in a browser bundle not built for production, on a server only with `NODE_ENV=development`, never in test runs. `false` for an app without signed-in users. See [Identify users](#identify-users) |
|
|
343
392
|
|
|
344
|
-
An option with an invalid value (for example `maxBatchSize: 0` or `NaN`, an empty `endpoint`) is ignored with one console warning and the default is used. Callbacks such as `onEventsDropped` and `onDeliveryFailed` can throw or reject without affecting the SDK. Draining a large queue (hundreds of thousands of events) takes time in proportion to its size. Some values are refused at once instead: an `apiKey` with characters a header cannot carry, a `fetchImpl` that is not a function. `endpoint` that is not a URL, an unknown `multiTabMode`, a `diagnostics` that is not `true` or `false`, a fractional `maxBatchSize` or `maxQueueSize`, a `maxBatchSize` above 500 (500 is used), and a `maxRetries` above 20 are reported with a warning and replaced. A `userId` that is `NaN` or infinite is no user id.
|
|
393
|
+
An option with an invalid value (for example `maxBatchSize: 0` or `NaN`, an empty `endpoint`) is ignored with one console warning and the default is used. Callbacks such as `onEventsDropped` and `onDeliveryFailed` can throw or reject without affecting the SDK. Draining a large queue (hundreds of thousands of events) takes time in proportion to its size. Some values are refused at once instead: an `apiKey` with characters a header cannot carry, a `fetchImpl` that is not a function. `endpoint` that is not a URL, an unknown `multiTabMode`, a `diagnostics` or `identifyHint` that is not `true` or `false`, a fractional `maxBatchSize` or `maxQueueSize`, a `maxBatchSize` above 500 (500 is used), and a `maxRetries` above 20 are reported with a warning and replaced. A `userId` that is `NaN` or infinite is no user id.
|
|
345
394
|
|
|
346
395
|
---
|
|
347
396
|
|
|
@@ -357,7 +406,7 @@ await tracker.flush();
|
|
|
357
406
|
|
|
358
407
|
## Shutdown
|
|
359
408
|
|
|
360
|
-
Graceful shutdown
|
|
409
|
+
Graceful shutdown - flush first, then cleanup:
|
|
361
410
|
|
|
362
411
|
```ts
|
|
363
412
|
await tracker.shutdown();
|
|
@@ -449,11 +498,11 @@ Eventra SDK includes:
|
|
|
449
498
|
- Circuit breaker with half-open recovery: one probe request, cooldown doubles after each failed probe (5 s up to 60 s)
|
|
450
499
|
- Queue-based delivery (all runtimes)
|
|
451
500
|
- Safe dequeue (events removed only after successful ingest)
|
|
452
|
-
- Queue persistence (browser) with merge + cross-tab sync
|
|
501
|
+
- Queue persistence (browser) with merge + cross-tab sync - opt out via `persistQueue: false` if `localStorage` isn't acceptable for your data
|
|
453
502
|
- Multi-tab leader election with re-election
|
|
454
503
|
- `fetch` + `keepalive` on tab close (with `x-api-key`, size-checked)
|
|
455
504
|
- `pagehide` + `visibilitychange` flush hooks
|
|
456
|
-
- Property validation at `track()` (depth + size)
|
|
505
|
+
- Property validation at `track()` (depth + size) - fails soft via `onEventsDropped`, `track()` never throws
|
|
457
506
|
- Payload byte limits per batch
|
|
458
507
|
- Permanent error handling via `onDeliveryFailed` (401, 422, etc.)
|
|
459
508
|
- Automatic requeue on network errors and 429 / 5xx
|
|
@@ -465,18 +514,21 @@ Eventra SDK includes:
|
|
|
465
514
|
|
|
466
515
|
**100% statement/branch/function/line coverage** (v8 provider, `pnpm test:coverage`).
|
|
467
516
|
|
|
468
|
-
|
|
517
|
+
**Mutation testing** (`pnpm test:mutation`, Stryker over all of `src/client.ts` and `src/diagnostics.ts`, about 30 minutes): 84.6% of mutants killed (2026-11-16), the build breaks below 80%. `tests/accuracy.test.ts` pins what decides whether an event reaches the server once and under its catalog name: name and user id cleaning and cutting, idempotency keys in every runtime, UTF-8 payload size, which saved events are read back, Retry-After, the size and depth limits of properties, what each server answer does to a batch, keepalive, and events shared between tabs. Mutants that cannot change behaviour are marked in the code with `// Stryker disable` and the reason.
|
|
518
|
+
|
|
519
|
+
358 vitest tests across 26 files (plus 7 Playwright tests in a real browser) cover the entire delivery pipeline:
|
|
469
520
|
|
|
470
|
-
- `track()` validation
|
|
471
|
-
-
|
|
472
|
-
-
|
|
521
|
+
- `track()` validation - name length, userId truncation, properties depth/size, idempotency keys
|
|
522
|
+
- Users - `identify()`, `reset()` and `withUser()`, which user wins, keeping the user across reloads and tabs and per API key, ignoring `identify()` outside a browser and React Native, ids that name nobody, the development hint
|
|
523
|
+
- Batching - auto-flush at `maxBatchSize`, periodic flush via timer, queue overflow drop
|
|
524
|
+
- Retry & backoff - 429, 5xx, network errors, no-retry on 4xx, fetch timeout/abort
|
|
473
525
|
- Circuit breaker - opens after 5 consecutive failed batches (each one after its retries), cools down, resets on success
|
|
474
|
-
- Payload guards
|
|
526
|
+
- Payload guards - multi-batch splitting, oversize event dropped via `onDeliveryFailed(413)`
|
|
475
527
|
- Shutdown & destroy - flush ordering, timer teardown, idempotent shutdown, the `shutdownTimeoutMs` budget, signal handling (re-raise only when nobody else listens, PID 1, `exitOnSignal: false`)
|
|
476
528
|
- Persisted queue - coalesced writes, 14-day maximum age, delivered-key filtering, cross-tab merge
|
|
477
|
-
- Runtime detection
|
|
529
|
+
- Runtime detection - Node, Edge (`EdgeRuntime`), Serverless (AWS Lambda), unknown fallback, Node process exit handling
|
|
478
530
|
- Browser mode - persistence (with its size cap), leader election (including multi-tab lease races), BroadcastChannel sync, `fetch` keepalive, `pagehide` while a request is in flight, `pageshow` after a back/forward cache restore, a `window` that is not a browser
|
|
479
|
-
- Storage edge cases
|
|
531
|
+
- Storage edge cases - corrupted/blocked localStorage, quota exceeded, queue trimming
|
|
480
532
|
- Internal fallbacks - `crypto.getRandomValues` (and a random id when there is no Web Crypto at all, as on Node 18), `Buffer`/string-length byte counting
|
|
481
533
|
- Regressions: `flush()` waiting for a flush already in flight, properties copied at `track()`, a corrupt stored queue
|
|
482
534
|
|
|
@@ -513,7 +565,7 @@ pnpm --filter @eventra_dev/eventra-sdk test:coverage
|
|
|
513
565
|
}
|
|
514
566
|
```
|
|
515
567
|
|
|
516
|
-
`idempotencyKey` is generated once per event and stays identical across every retry attempt of that event
|
|
568
|
+
`idempotencyKey` is generated once per event and stays identical across every retry attempt of that event - delivery is **at-least-once, not exactly-once**. A retried batch resends the same events with the same keys, and under a slow network a request can be fully received and processed by the ingestion endpoint even after the SDK's own fetch timed out client-side and moved on to a retry - the backend seeing the same `idempotencyKey` more than once is expected, not a sign of a bug, and should be deduplicated on that key rather than on request count.
|
|
517
569
|
|
|
518
570
|
Limits enforced by the SDK at `track()` time:
|
|
519
571
|
|
package/dist/index.cjs
CHANGED
|
@@ -193,11 +193,12 @@ var Diagnostics = class {
|
|
|
193
193
|
// src/client.ts
|
|
194
194
|
var SDK_NAME = "@eventra_dev/eventra-sdk";
|
|
195
195
|
var DEFAULT_ENDPOINT = "https://api.eventra.dev/api/v1/ingest/batch";
|
|
196
|
-
var SDK_VERSION = "2.0
|
|
196
|
+
var SDK_VERSION = "2.1.0";
|
|
197
197
|
var LEADER_KEY = "__eventra_leader__";
|
|
198
198
|
var LEADER_TTL_MS = 4e3;
|
|
199
199
|
var QUEUE_KEY = "__eventra_q__";
|
|
200
200
|
var DIAGNOSTICS_KEY = "__eventra_d__";
|
|
201
|
+
var USER_KEY_PREFIX = "__eventra_u__";
|
|
201
202
|
var CHANNEL_NAME = "eventra-sdk";
|
|
202
203
|
var MAX_EVENT_NAME = 64;
|
|
203
204
|
var MAX_USER_ID = 120;
|
|
@@ -218,6 +219,7 @@ var KEEPALIVE_MAX_BYTES = 6e4;
|
|
|
218
219
|
var DELIVERED_KEYS_MAX = 1e4;
|
|
219
220
|
var LIVE_TAB_GRACE_MS = 15e3;
|
|
220
221
|
var LIVE_TAB_KEYS_MAX = 1e4;
|
|
222
|
+
var IDENTIFY_HINT_AFTER = 50;
|
|
221
223
|
var activeInstances = 0;
|
|
222
224
|
function detectRuntime() {
|
|
223
225
|
const g = globalThis;
|
|
@@ -284,10 +286,11 @@ function isUrl(value) {
|
|
|
284
286
|
return false;
|
|
285
287
|
}
|
|
286
288
|
}
|
|
289
|
+
function warn(message) {
|
|
290
|
+
if (typeof console !== "undefined") console.warn(message);
|
|
291
|
+
}
|
|
287
292
|
function warnOption(name, value, fallback) {
|
|
288
|
-
|
|
289
|
-
console.warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
|
|
290
|
-
}
|
|
293
|
+
warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
|
|
291
294
|
}
|
|
292
295
|
function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
|
|
293
296
|
if (value === void 0) return fallback;
|
|
@@ -341,6 +344,39 @@ function normalizeUserId(value, max) {
|
|
|
341
344
|
if (typeof value !== "string") return void 0;
|
|
342
345
|
return cut(value, max);
|
|
343
346
|
}
|
|
347
|
+
function identifiedUserId(value) {
|
|
348
|
+
const id = normalizeUserId(value, MAX_USER_ID);
|
|
349
|
+
if (id === void 0) return void 0;
|
|
350
|
+
const trimmed = id.trim();
|
|
351
|
+
return trimmed && trimmed !== "undefined" && trimmed !== "null" ? id : void 0;
|
|
352
|
+
}
|
|
353
|
+
function keyHash(value) {
|
|
354
|
+
let hash = 2166136261;
|
|
355
|
+
for (let i = 0; i < value.length; i++) {
|
|
356
|
+
hash ^= value.charCodeAt(i);
|
|
357
|
+
hash = Math.imul(hash, 16777619);
|
|
358
|
+
}
|
|
359
|
+
return (hash >>> 0).toString(16);
|
|
360
|
+
}
|
|
361
|
+
function isReactNative() {
|
|
362
|
+
try {
|
|
363
|
+
return globalThis.navigator?.product === "ReactNative";
|
|
364
|
+
} catch {
|
|
365
|
+
return false;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
function nodeEnv() {
|
|
369
|
+
try {
|
|
370
|
+
return process.env.NODE_ENV;
|
|
371
|
+
} catch {
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
function isDevelopment(server) {
|
|
376
|
+
const env = nodeEnv();
|
|
377
|
+
if (env === null || env === "test") return false;
|
|
378
|
+
return server ? env === "development" : env !== "production";
|
|
379
|
+
}
|
|
344
380
|
function stripUnsafeForName(value) {
|
|
345
381
|
let out = "";
|
|
346
382
|
for (let i = 0; i < value.length; i++) {
|
|
@@ -385,7 +421,9 @@ function utf8ByteLength(value) {
|
|
|
385
421
|
function isStoredEvent(e) {
|
|
386
422
|
if (e === null || typeof e !== "object") return false;
|
|
387
423
|
const ev = e;
|
|
388
|
-
return typeof ev.idempotencyKey === "string" && ev.idempotencyKey.length > 0 && ev.idempotencyKey.length <= 100 &&
|
|
424
|
+
return typeof ev.idempotencyKey === "string" && ev.idempotencyKey.length > 0 && ev.idempotencyKey.length <= 100 && // Stryker disable next-line ConditionalExpression: equivalent, a name that is not a string has no length and fails the next check
|
|
425
|
+
typeof ev.name === "string" && ev.name.length > 0 && ev.name.length <= MAX_EVENT_NAME && typeof ev.timestamp === "string" && // Stryker disable next-line ConditionalExpression: equivalent, a user id that is not a string has no length to pass the check
|
|
426
|
+
(ev.userId === void 0 || typeof ev.userId === "string" && ev.userId.length <= MAX_USER_ID) && (ev.properties === void 0 || ev.properties !== null && typeof ev.properties === "object" && !Array.isArray(ev.properties));
|
|
389
427
|
}
|
|
390
428
|
function mergeQueues(...queues) {
|
|
391
429
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -419,8 +457,12 @@ function persistedQueueJson(queue) {
|
|
|
419
457
|
}
|
|
420
458
|
var MAX_PROPERTIES_NODES = 5e4;
|
|
421
459
|
function validateProperties(properties) {
|
|
422
|
-
if (
|
|
423
|
-
|
|
460
|
+
if (
|
|
461
|
+
// Stryker disable next-line all: equivalent, track() passes `properties ?? {}`, and any other non-object fails the toString check below
|
|
462
|
+
properties === null || // Stryker disable next-line all: equivalent, see the line above
|
|
463
|
+
typeof properties !== "object" || Array.isArray(properties) || // a Date, a Map, a Set, a RegExp: objects, but not a bag of named values
|
|
464
|
+
Object.prototype.toString.call(properties) !== "[object Object]"
|
|
465
|
+
) {
|
|
424
466
|
throw new Error("Eventra: properties must be an object");
|
|
425
467
|
}
|
|
426
468
|
const topKeys = Object.keys(properties);
|
|
@@ -528,11 +570,6 @@ var Storage = class {
|
|
|
528
570
|
} catch {
|
|
529
571
|
}
|
|
530
572
|
}
|
|
531
|
-
// Not currently called anywhere in the client — kept for API symmetry with
|
|
532
|
-
// get()/set() on this internal class. No real call site exists to exercise
|
|
533
|
-
// it, and Storage isn't part of the public surface, so a direct call here
|
|
534
|
-
// would only be a reflection-hack test, not real usage.
|
|
535
|
-
/* v8 ignore start */
|
|
536
573
|
remove(key) {
|
|
537
574
|
if (!this.enabled) return;
|
|
538
575
|
try {
|
|
@@ -540,7 +577,6 @@ var Storage = class {
|
|
|
540
577
|
} catch {
|
|
541
578
|
}
|
|
542
579
|
}
|
|
543
|
-
/* v8 ignore stop */
|
|
544
580
|
};
|
|
545
581
|
function storageAvailable() {
|
|
546
582
|
try {
|
|
@@ -701,6 +737,16 @@ var Eventra = class {
|
|
|
701
737
|
// the page is being left (`pagehide`)
|
|
702
738
|
this.leaving = false;
|
|
703
739
|
this.exitHandlers = [];
|
|
740
|
+
this.warnedServerIdentify = false;
|
|
741
|
+
this.warnedInvalidIdentify = false;
|
|
742
|
+
this.warnedInvalidUser = false;
|
|
743
|
+
// one user for the whole instance is safe only where the instance serves one person: a browser tab, a React
|
|
744
|
+
// Native app. Everything else (Node, edge, Lambda, Deno, Cloudflare Workers) may serve many requests at once.
|
|
745
|
+
this.singleUser = false;
|
|
746
|
+
this.userKey = USER_KEY_PREFIX;
|
|
747
|
+
// identifyHint: events without a user id so far, and whether the check is over
|
|
748
|
+
this.eventsWithoutUser = 0;
|
|
749
|
+
this.identifyHintDone = false;
|
|
704
750
|
if (!options || typeof options !== "object" || typeof options.apiKey !== "string" || !options.apiKey) {
|
|
705
751
|
throw new Error('Eventra: apiKey required - new Eventra({ apiKey: "..." })');
|
|
706
752
|
}
|
|
@@ -733,6 +779,10 @@ var Eventra = class {
|
|
|
733
779
|
if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") {
|
|
734
780
|
warnOption("diagnostics", options.diagnostics, "true");
|
|
735
781
|
}
|
|
782
|
+
if (options.identifyHint !== void 0 && typeof options.identifyHint !== "boolean") {
|
|
783
|
+
warnOption("identifyHint", options.identifyHint, "true");
|
|
784
|
+
}
|
|
785
|
+
this.identifyHintDone = options.identifyHint === false;
|
|
736
786
|
for (const name of ["maxBatchSize", "maxQueueSize"]) {
|
|
737
787
|
const value = options[name];
|
|
738
788
|
if (typeof value === "number" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {
|
|
@@ -740,6 +790,8 @@ var Eventra = class {
|
|
|
740
790
|
}
|
|
741
791
|
}
|
|
742
792
|
this.runtime = detectRuntime();
|
|
793
|
+
this.singleUser = this.runtime === "browser" || isReactNative();
|
|
794
|
+
this.userKey = `${USER_KEY_PREFIX}${keyHash(options.apiKey)}`;
|
|
743
795
|
warnIfInsecureEndpoint(this.endpoint);
|
|
744
796
|
this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
|
|
745
797
|
if (!this.fetch) {
|
|
@@ -771,7 +823,10 @@ var Eventra = class {
|
|
|
771
823
|
};
|
|
772
824
|
if (this.runtime === "browser") {
|
|
773
825
|
if (this.persistQueue) {
|
|
826
|
+
this.userId = this.loadStoredUser();
|
|
774
827
|
this.loadAndMergeQueue();
|
|
828
|
+
} else {
|
|
829
|
+
this.storage.remove(this.userKey);
|
|
775
830
|
}
|
|
776
831
|
this.setupQueueSync();
|
|
777
832
|
}
|
|
@@ -809,14 +864,86 @@ var Eventra = class {
|
|
|
809
864
|
}
|
|
810
865
|
}
|
|
811
866
|
track(name, options) {
|
|
867
|
+
this.trackSafely(name, options, void 0);
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Sets the user of every following event that does not name its own, in a browser or a React Native app. In
|
|
871
|
+
* the browser the user is kept in localStorage (unless `persistQueue: false`) and shared with the other open
|
|
872
|
+
* tabs. Anywhere else (a server, an edge or serverless function, Deno, Cloudflare Workers) one instance may
|
|
873
|
+
* serve many users at once, so it is ignored with one warning: use `withUser()` there.
|
|
874
|
+
*/
|
|
875
|
+
identify(userId) {
|
|
876
|
+
if (this.destroyed) return;
|
|
877
|
+
if (!this.singleUser) {
|
|
878
|
+
if (!this.warnedServerIdentify) {
|
|
879
|
+
this.warnedServerIdentify = true;
|
|
880
|
+
warn(
|
|
881
|
+
"Eventra: identify() is ignored outside a browser, where one instance may serve many users - use withUser(userId).track(...) for each request (in Next.js and other SSR apps, call identify() in client code, e.g. useEffect)"
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
const id = identifiedUserId(userId);
|
|
887
|
+
if (id === void 0) {
|
|
888
|
+
if (!this.warnedInvalidIdentify) {
|
|
889
|
+
this.warnedInvalidIdentify = true;
|
|
890
|
+
warn("Eventra: identify() needs a user id (a non-empty string or a number) - to sign a user out, call reset()");
|
|
891
|
+
}
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
this.identifyHintDone = true;
|
|
895
|
+
if (id !== this.userId) this.setUser(id);
|
|
896
|
+
}
|
|
897
|
+
/** Forgets the user set by `identify()` (on sign-out), in every open tab and in localStorage. */
|
|
898
|
+
reset() {
|
|
899
|
+
if (this.destroyed || !this.singleUser) return;
|
|
900
|
+
this.setUser(void 0);
|
|
901
|
+
}
|
|
902
|
+
/** The user set by `identify()`, if any. */
|
|
903
|
+
getUserId() {
|
|
904
|
+
return this.userId;
|
|
905
|
+
}
|
|
906
|
+
/**
|
|
907
|
+
* A tracker whose events carry `userId`, for one request on a server (works in every runtime). It shares
|
|
908
|
+
* this instance's queue, so making one per request is cheap. `undefined`, `null` or an invalid id give events
|
|
909
|
+
* without a user (never the user of `identify()`), so `withUser(req.user?.id)` works for signed-out requests.
|
|
910
|
+
*/
|
|
911
|
+
withUser(userId) {
|
|
912
|
+
let id;
|
|
913
|
+
if (userId !== void 0 && userId !== null) {
|
|
914
|
+
id = identifiedUserId(userId);
|
|
915
|
+
if (id === void 0 && !this.warnedInvalidUser) {
|
|
916
|
+
this.warnedInvalidUser = true;
|
|
917
|
+
warn("Eventra: withUser() got an invalid user id (it needs a non-empty string or a number), its events are sent without one");
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
if (id !== void 0) this.identifyHintDone = true;
|
|
921
|
+
const scopeUser = id ?? null;
|
|
922
|
+
return {
|
|
923
|
+
track: (name, options) => this.trackSafely(name, options, scopeUser)
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
setUser(id) {
|
|
927
|
+
this.userId = id;
|
|
928
|
+
if (this.runtime !== "browser") return;
|
|
929
|
+
if (id === void 0) this.storage.remove(this.userKey);
|
|
930
|
+
else if (this.persistQueue) this.storage.set(this.userKey, id);
|
|
931
|
+
this.broadcast({ type: "user", key: this.userKey, userId: id ?? null });
|
|
932
|
+
}
|
|
933
|
+
loadStoredUser() {
|
|
934
|
+
const saved = this.storage.get(this.userKey);
|
|
935
|
+
return typeof saved === "string" ? identifiedUserId(saved) : void 0;
|
|
936
|
+
}
|
|
937
|
+
// scopeUserId: undefined outside a scope, null for a scope without a user
|
|
938
|
+
trackSafely(name, options, scopeUserId) {
|
|
812
939
|
try {
|
|
813
|
-
this.trackEvent(name, options);
|
|
940
|
+
this.trackEvent(name, options, scopeUserId);
|
|
814
941
|
} catch {
|
|
815
942
|
this.recordDiagnostic("invalid_event");
|
|
816
943
|
callSafely(this.options.onEventsDropped, 1);
|
|
817
944
|
}
|
|
818
945
|
}
|
|
819
|
-
trackEvent(name, options) {
|
|
946
|
+
trackEvent(name, options, scopeUserId) {
|
|
820
947
|
if (this.destroyed || this.shuttingDown) return;
|
|
821
948
|
const eventName = normalizeEventName(name);
|
|
822
949
|
if (eventName === null) {
|
|
@@ -837,14 +964,17 @@ var Eventra = class {
|
|
|
837
964
|
callSafely(this.options.onEventsDropped, 1);
|
|
838
965
|
return;
|
|
839
966
|
}
|
|
967
|
+
const given = options?.userId;
|
|
968
|
+
const ownUserId = typeof given === "string" && !given.trim() ? void 0 : given;
|
|
840
969
|
const event = {
|
|
841
970
|
idempotencyKey: uuidV4(),
|
|
842
971
|
name: eventName,
|
|
843
|
-
userId: normalizeUserId(
|
|
972
|
+
userId: ownUserId !== void 0 ? normalizeUserId(ownUserId, MAX_USER_ID) : scopeUserId !== void 0 ? scopeUserId ?? void 0 : this.userId,
|
|
844
973
|
properties,
|
|
845
974
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
846
975
|
};
|
|
847
976
|
this.queue.push(event);
|
|
977
|
+
if (!this.identifyHintDone) this.checkIdentifyHint(identifiedUserId(event.userId) !== void 0);
|
|
848
978
|
if (this.runtime === "browser") {
|
|
849
979
|
this.schedulePersist();
|
|
850
980
|
this.broadcast({ type: "queue-add", events: [event] });
|
|
@@ -1039,6 +1169,20 @@ var Eventra = class {
|
|
|
1039
1169
|
diagnostics: withReport && report ? report : void 0
|
|
1040
1170
|
};
|
|
1041
1171
|
}
|
|
1172
|
+
// one warning during development when an app sends events without ever saying whose they are
|
|
1173
|
+
checkIdentifyHint(hasUser) {
|
|
1174
|
+
if (hasUser) {
|
|
1175
|
+
this.identifyHintDone = true;
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
if (++this.eventsWithoutUser < IDENTIFY_HINT_AFTER) return;
|
|
1179
|
+
this.identifyHintDone = true;
|
|
1180
|
+
if (!isDevelopment(!this.singleUser)) return;
|
|
1181
|
+
const how = this.singleUser ? "call tracker.identify(userId) after sign-in" : "track through tracker.withUser(userId) in each request";
|
|
1182
|
+
warn(
|
|
1183
|
+
`Eventra: none of the first ${IDENTIFY_HINT_AFTER} events has a userId, so unique users cannot be counted - ${how} (identifyHint: false turns this off)`
|
|
1184
|
+
);
|
|
1185
|
+
}
|
|
1042
1186
|
dropPoisonEvent(event) {
|
|
1043
1187
|
this.recordDiagnostic("too_large");
|
|
1044
1188
|
this.removeDelivered([event]);
|
|
@@ -1074,8 +1218,13 @@ var Eventra = class {
|
|
|
1074
1218
|
this.dropPoisonEvents(events);
|
|
1075
1219
|
return false;
|
|
1076
1220
|
}
|
|
1077
|
-
const useKeepalive =
|
|
1078
|
-
|
|
1221
|
+
const useKeepalive = (
|
|
1222
|
+
// Stryker disable next-line all: equivalent, document exists exactly in the browser runtime
|
|
1223
|
+
this.runtime === "browser" && // Stryker disable next-line all: equivalent, see the line above
|
|
1224
|
+
typeof document !== "undefined" && (document.visibilityState === "hidden" || this.leaving) && // browsers refuse a keepalive body above 64 KiB (the whole request fails), whatever maxPayloadBytes allows
|
|
1225
|
+
// Stryker disable next-line EqualityOperator: a body of exactly the keepalive limit; not worth a 60,000-byte fixture
|
|
1226
|
+
payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES)
|
|
1227
|
+
);
|
|
1079
1228
|
const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
|
|
1080
1229
|
let strippedDiagnostics = false;
|
|
1081
1230
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
@@ -1103,7 +1252,9 @@ var Eventra = class {
|
|
|
1103
1252
|
discardBody(res);
|
|
1104
1253
|
if (res.status === 429 || res.status >= 500) {
|
|
1105
1254
|
throw new RetryableDeliveryError(
|
|
1255
|
+
// Stryker disable next-line StringLiteral: the message is never read
|
|
1106
1256
|
"retryable delivery error",
|
|
1257
|
+
// Stryker disable next-line OptionalChaining: equivalent with a real Response, which always has headers.get
|
|
1107
1258
|
parseRetryAfterMs(res.headers?.get?.("retry-after")),
|
|
1108
1259
|
res.status === 429 ? "rate_limited" : "server_error"
|
|
1109
1260
|
);
|
|
@@ -1279,6 +1430,12 @@ var Eventra = class {
|
|
|
1279
1430
|
if (this.channel) {
|
|
1280
1431
|
this.channel.onmessage = (e) => {
|
|
1281
1432
|
const data = e.data;
|
|
1433
|
+
if (data?.type === "user") {
|
|
1434
|
+
if (data.key !== this.userKey) return;
|
|
1435
|
+
if (data.userId === null) this.userId = void 0;
|
|
1436
|
+
else if (typeof data.userId === "string") this.userId = identifiedUserId(data.userId) ?? this.userId;
|
|
1437
|
+
return;
|
|
1438
|
+
}
|
|
1282
1439
|
if (data?.type === "delivered" && Array.isArray(data.keys)) {
|
|
1283
1440
|
const keys = new Set(data.keys);
|
|
1284
1441
|
this.rememberDelivered(keys);
|
|
@@ -1297,6 +1454,7 @@ var Eventra = class {
|
|
|
1297
1454
|
}
|
|
1298
1455
|
if (this.persistQueue && typeof window !== "undefined") {
|
|
1299
1456
|
this.offStorageQueue = listen(window, "storage", (e) => {
|
|
1457
|
+
if (e.key === this.userKey || e.key === null) this.userId = this.loadStoredUser();
|
|
1300
1458
|
if (e.key !== QUEUE_KEY) return;
|
|
1301
1459
|
this.loadAndMergeQueue();
|
|
1302
1460
|
});
|