@teploy/observe-browser 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +151 -2
- package/dist/breadcrumbs.d.ts +79 -0
- package/dist/breadcrumbs.d.ts.map +1 -0
- package/dist/breadcrumbs.js +363 -0
- package/dist/breadcrumbs.js.map +1 -0
- package/dist/flags.d.ts +79 -0
- package/dist/flags.d.ts.map +1 -0
- package/dist/flags.js +185 -0
- package/dist/flags.js.map +1 -0
- package/dist/index.d.ts +297 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +981 -0
- package/dist/index.js.map +1 -0
- package/package.json +44 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,981 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @teploy/observe-browser — Observe's browser SDK.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { init } from "@teploy/observe-browser";
|
|
6
|
+
*
|
|
7
|
+
* init({
|
|
8
|
+
* endpoint: "https://observe.example.com",
|
|
9
|
+
* siteId: "my-site",
|
|
10
|
+
* // Ingestion requires a site-scoped API key (create one under
|
|
11
|
+
* // Settings > API keys; browser keys are public by design and can only
|
|
12
|
+
* // append telemetry to their own site).
|
|
13
|
+
* apiKey: "pk_site_scoped_ingest_key",
|
|
14
|
+
* });
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* For frameworks that can't use script tags (SPA routes, CSP, etc.) this
|
|
18
|
+
* module takes the place of the `<script src="/observe.js">` snippet. It
|
|
19
|
+
* sends the same payloads to the same ingestion endpoints.
|
|
20
|
+
*/
|
|
21
|
+
import { createRecorder } from "./breadcrumbs.js";
|
|
22
|
+
import { createFlagClient } from "./flags.js";
|
|
23
|
+
export { createFlagClient } from "./flags.js";
|
|
24
|
+
/** Wire protocol version this SDK speaks (F12/F19 idempotent batches). */
|
|
25
|
+
export const PROTOCOL_VERSION = 2;
|
|
26
|
+
function newStats(producerId) {
|
|
27
|
+
return {
|
|
28
|
+
deliveredBatches: 0,
|
|
29
|
+
deliveredEvents: 0,
|
|
30
|
+
retries: 0,
|
|
31
|
+
dropped: {},
|
|
32
|
+
undeliveredAtUnload: 0,
|
|
33
|
+
queued: 0,
|
|
34
|
+
producerId,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** O11: count a loss (never silent) — increments the visible counter and
|
|
38
|
+
* reports through onError so an unset hook cannot hide the drop either. */
|
|
39
|
+
function countDrop(target, reason, events, detail) {
|
|
40
|
+
target.stats.dropped[reason] = (target.stats.dropped[reason] ?? 0) + events;
|
|
41
|
+
reportError(target, new Error(`observe: lost ${events} event(s) (${reason})${detail ? ` — ${detail}` : ""}`));
|
|
42
|
+
}
|
|
43
|
+
let client = null;
|
|
44
|
+
function makeId() {
|
|
45
|
+
const arr = new Uint8Array(16);
|
|
46
|
+
(globalThis.crypto ?? globalThis.msCrypto).getRandomValues(arr);
|
|
47
|
+
return Array.from(arr, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
48
|
+
}
|
|
49
|
+
// Server-side caps the SDK must respect (audit F32): the events batch
|
|
50
|
+
// endpoint rejects >100 events per request, and a keepalive body plus any
|
|
51
|
+
// other in-flight keepalive traffic must stay under the browser's 64 KiB
|
|
52
|
+
// budget — 48 KiB is a conservative per-request allowance.
|
|
53
|
+
const MAX_EVENTS_PER_REQUEST = 100;
|
|
54
|
+
const MAX_KEEPALIVE_BYTES = 48 * 1024;
|
|
55
|
+
// AUD-026 (round 2): batches are packed by ENCODED BYTES as well as event
|
|
56
|
+
// count — a count-only cap let a batch of large events exceed the server's
|
|
57
|
+
// 2 MiB body limit (or the keepalive budget) and be rejected whole. 1 MiB
|
|
58
|
+
// leaves room for envelope overhead under the route cap.
|
|
59
|
+
const MAX_REQUEST_BYTES = 1024 * 1024;
|
|
60
|
+
// TO-033/TO-034: admission-time budgets. Every queued record carries its
|
|
61
|
+
// serialized bytes, and the queued+pending total is capped in BOTH count
|
|
62
|
+
// and bytes — during retry backoff or a hanging request the buffer can no
|
|
63
|
+
// longer grow without limit (the old MAX_BUFFERED_ON_ERROR only ran after
|
|
64
|
+
// a send had already failed).
|
|
65
|
+
const MAX_QUEUED_EVENTS = 200;
|
|
66
|
+
const MAX_QUEUED_BYTES = 8 * 1024 * 1024;
|
|
67
|
+
// TO-035: a conservative per-event admission cap under the server's 64 KiB
|
|
68
|
+
// stored-event limit, so a record that can never be accepted is reported
|
|
69
|
+
// at admission instead of poisoning every request that packs it.
|
|
70
|
+
const MAX_EVENT_BYTES = 60 * 1024;
|
|
71
|
+
// Retained requests on a failed send (audit F32): keep the batch for the next
|
|
72
|
+
// flush instead of silently erasing it, but bound the retention so a long
|
|
73
|
+
// outage cannot grow memory without limit. Beyond the cap, the OLDEST
|
|
74
|
+
// pending requests are dropped and reported (they carry the oldest data).
|
|
75
|
+
const MAX_PENDING_REQUESTS = 200;
|
|
76
|
+
// F32 retry policy: the backoff doubles per attempt up to this ceiling.
|
|
77
|
+
const MAX_RETRY_DELAY_MS = 60000;
|
|
78
|
+
// TO-034: every flush-network request carries a deadline; a hanging fetch
|
|
79
|
+
// must not pin the single flush owner forever while the buffer grows. The
|
|
80
|
+
// default is 10 s; init({ requestTimeoutMs }) overrides (O11, clamped).
|
|
81
|
+
const FETCH_DEADLINE_MS = 10000;
|
|
82
|
+
const textEncoder = new TextEncoder();
|
|
83
|
+
// F41 URL contract: what leaves the browser is origin+path only. Campaign
|
|
84
|
+
// attribution rides the explicit utm_* fields extracted from the
|
|
85
|
+
// allowlisted query params — the raw query string never leaves the page.
|
|
86
|
+
const UTM_KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];
|
|
87
|
+
function pageUrl() {
|
|
88
|
+
if (typeof location === "undefined")
|
|
89
|
+
return "";
|
|
90
|
+
return location.origin + location.pathname;
|
|
91
|
+
}
|
|
92
|
+
function campaignFields() {
|
|
93
|
+
const out = {};
|
|
94
|
+
if (typeof location === "undefined" || !location.search)
|
|
95
|
+
return out;
|
|
96
|
+
try {
|
|
97
|
+
const params = new URLSearchParams(location.search);
|
|
98
|
+
for (const key of UTM_KEYS) {
|
|
99
|
+
const v = params.get(key);
|
|
100
|
+
if (v)
|
|
101
|
+
out[key] = v.slice(0, 256);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
/* a malformed search string carries no attribution */
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/** Serialize the v2 batch envelope around already-serialized events.
|
|
110
|
+
* The producer id is ALWAYS the owning client's (TO-036): the old global
|
|
111
|
+
* fallback let an old client's in-flight flush adopt a replacement
|
|
112
|
+
* client's producer identity after re-init. */
|
|
113
|
+
function batchEnvelopeJSON(producerId, batchId, events) {
|
|
114
|
+
return `{"v":${PROTOCOL_VERSION},"producer_id":${JSON.stringify(producerId)},"batch_id":${JSON.stringify(batchId)},"events":[${events.join(",")}]}`;
|
|
115
|
+
}
|
|
116
|
+
/** Freeze buffer entries into request-legal envelopes by count and encoded
|
|
117
|
+
* bytes (AUD-026/TO-032). Every emitted request is complete and immutable;
|
|
118
|
+
* entries that cannot fit any envelope are reported and dropped (they were
|
|
119
|
+
* already rejected at admission, so this is a belt-and-braces re-check). */
|
|
120
|
+
function packEventRequests(producerId, entries, onDrop) {
|
|
121
|
+
const out = [];
|
|
122
|
+
let batch = [];
|
|
123
|
+
let bytes = 0;
|
|
124
|
+
const flushBatch = () => {
|
|
125
|
+
if (!batch.length)
|
|
126
|
+
return;
|
|
127
|
+
const batchId = makeId();
|
|
128
|
+
const body = batchEnvelopeJSON(producerId, batchId, batch);
|
|
129
|
+
out.push({
|
|
130
|
+
producerId,
|
|
131
|
+
batchId,
|
|
132
|
+
body,
|
|
133
|
+
bytes: textEncoder.encode(body).byteLength,
|
|
134
|
+
eventCount: batch.length,
|
|
135
|
+
});
|
|
136
|
+
batch = [];
|
|
137
|
+
bytes = 0;
|
|
138
|
+
};
|
|
139
|
+
for (const raw of entries) {
|
|
140
|
+
const rawBytes = textEncoder.encode(raw).byteLength;
|
|
141
|
+
const solo = textEncoder.encode(batchEnvelopeJSON(producerId, "probe", [raw])).byteLength;
|
|
142
|
+
if (solo > MAX_REQUEST_BYTES) {
|
|
143
|
+
onDrop(`dropped an event exceeding the request byte budget (${solo} > ${MAX_REQUEST_BYTES})`);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const envelopeOverhead = solo - rawBytes;
|
|
147
|
+
if (batch.length >= MAX_EVENTS_PER_REQUEST ||
|
|
148
|
+
(batch.length > 0 && bytes + rawBytes + envelopeOverhead > MAX_REQUEST_BYTES)) {
|
|
149
|
+
flushBatch();
|
|
150
|
+
}
|
|
151
|
+
bytes += rawBytes;
|
|
152
|
+
batch.push(raw);
|
|
153
|
+
}
|
|
154
|
+
flushBatch();
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
/** fetch with a hard deadline (TO-034) and redirect refusal (TO-037: a
|
|
158
|
+
* redirect would forward the X-API-Key credential to another origin). */
|
|
159
|
+
async function fetchWithDeadline(url, init, deadlineMs = FETCH_DEADLINE_MS, consume) {
|
|
160
|
+
const controller = new AbortController();
|
|
161
|
+
let timer;
|
|
162
|
+
try {
|
|
163
|
+
return await Promise.race([
|
|
164
|
+
fetch(url, { ...init, redirect: "error", signal: controller.signal }).then(res => consume ? consume(res) : res),
|
|
165
|
+
new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new Error("observe: request deadline reached")); }, deadlineMs); }),
|
|
166
|
+
]);
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
if (timer !== undefined)
|
|
170
|
+
clearTimeout(timer);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function queuedEvents(target) {
|
|
174
|
+
return target.buffer.length + target.pending.reduce((n, r) => n + r.eventCount, 0) + (target.activeRequest?.eventCount ?? 0);
|
|
175
|
+
}
|
|
176
|
+
function safeUrl(value) {
|
|
177
|
+
try {
|
|
178
|
+
const url = new URL(value);
|
|
179
|
+
return /^https?:$/.test(url.protocol) ? url.origin + url.pathname : "";
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return "";
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Send one pre-serialized JSON body. STRICT (AUD-021/TO-037): rejects on
|
|
187
|
+
* any transport failure (non-2xx, network error, redirect) and carries a
|
|
188
|
+
* request deadline so a hanging fetch cannot pin the flush owner (TO-034).
|
|
189
|
+
* The flush owner consumes rejections to drive retention; the
|
|
190
|
+
* fire-and-forget public boundaries (captureException, log, unload sends)
|
|
191
|
+
* report them instead. `keepalive` is only used for small final sends
|
|
192
|
+
* while the page is unloading.
|
|
193
|
+
*/
|
|
194
|
+
function sendRawJSON(target, path, raw, unloading = false) {
|
|
195
|
+
const url = target.opts.endpoint.replace(/\/+$/, "") + path;
|
|
196
|
+
const headers = { "Content-Type": "application/json" };
|
|
197
|
+
if (target.opts.apiKey)
|
|
198
|
+
headers["X-API-Key"] = target.opts.apiKey;
|
|
199
|
+
const bytes = textEncoder.encode(raw).byteLength;
|
|
200
|
+
return fetchWithDeadline(url, {
|
|
201
|
+
method: "POST",
|
|
202
|
+
headers,
|
|
203
|
+
body: raw,
|
|
204
|
+
credentials: "omit",
|
|
205
|
+
keepalive: unloading && bytes <= MAX_KEEPALIVE_BYTES,
|
|
206
|
+
}, target.opts.requestTimeoutMs).then((res) => {
|
|
207
|
+
if (!res.ok)
|
|
208
|
+
throw new Error(`observe: ingest returned ${res.status}`);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
function sendJSON(target, path, payload, unloading = false) {
|
|
212
|
+
let raw;
|
|
213
|
+
try {
|
|
214
|
+
raw = JSON.stringify(payload);
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
return Promise.reject(err instanceof Error ? err : new Error("observe: payload not serializable"));
|
|
218
|
+
}
|
|
219
|
+
return sendRawJSON(target, path, raw, unloading).catch((err) => {
|
|
220
|
+
reportError(target, err instanceof Error ? err : new Error(String(err)));
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* TO-035: read and validate the events-batch acknowledgment. HTTP success
|
|
225
|
+
* alone is not acceptance — the server reports per-event rejections in
|
|
226
|
+
* `rejected`; those surface through onError (the rejected events are gone
|
|
227
|
+
* server-side; retrying would only duplicate the accepted neighbors).
|
|
228
|
+
*/
|
|
229
|
+
async function readEventBatchAck(res) {
|
|
230
|
+
if (!res.ok)
|
|
231
|
+
throw new Error(`observe: ingest returned ${res.status}`);
|
|
232
|
+
let value;
|
|
233
|
+
if (res.body) {
|
|
234
|
+
const reader = res.body.getReader();
|
|
235
|
+
const decoder = new TextDecoder();
|
|
236
|
+
let text = "", bytes = 0;
|
|
237
|
+
try {
|
|
238
|
+
while (true) {
|
|
239
|
+
const chunk = await reader.read();
|
|
240
|
+
if (chunk.done)
|
|
241
|
+
break;
|
|
242
|
+
bytes += chunk.value.byteLength;
|
|
243
|
+
if (bytes > 64 * 1024)
|
|
244
|
+
throw new Error("observe: oversized batch acknowledgment");
|
|
245
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
246
|
+
}
|
|
247
|
+
text += decoder.decode();
|
|
248
|
+
try {
|
|
249
|
+
value = JSON.parse(text);
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
value = null;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
void reader.cancel().catch(() => { });
|
|
257
|
+
reader.releaseLock();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
// Response doubles and bodyless older transports still expose json().
|
|
262
|
+
value = await res.json().catch(() => null);
|
|
263
|
+
}
|
|
264
|
+
if (!value || typeof value !== "object" || value.ok !== true) {
|
|
265
|
+
throw new Error("observe: invalid batch acknowledgment");
|
|
266
|
+
}
|
|
267
|
+
return value;
|
|
268
|
+
}
|
|
269
|
+
/** Route a transport failure to the configured hook without throwing into
|
|
270
|
+
* application code (audit F32's drop signal). */
|
|
271
|
+
function reportError(target, err) {
|
|
272
|
+
try {
|
|
273
|
+
target.opts.onError?.(err);
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
/* an onError hook that throws must not break the SDK */
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/** Route a scheduled retry to the visibility hook (audit F32). */
|
|
280
|
+
function reportRetry(target, info) {
|
|
281
|
+
try {
|
|
282
|
+
target.opts.onRetry?.(info);
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
/* an onRetry hook that throws must not break the SDK */
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
/** O11: the honest unload accounting. At pagehide the still-queued events
|
|
289
|
+
* are the worst-case loss; record the snapshot visibly (onError + stats)
|
|
290
|
+
* before the best-effort keepalive flush, because the page may die before
|
|
291
|
+
* any delivery confirmation arrives. */
|
|
292
|
+
function recordUnloadSnapshot(target) {
|
|
293
|
+
const queued = queuedEvents(target);
|
|
294
|
+
if (queued > 0) {
|
|
295
|
+
target.stats.undeliveredAtUnload = queued;
|
|
296
|
+
reportError(target, new Error(`observe: page unloading with ${queued} undelivered event(s) — attempting keepalive flush; this count is the loss upper bound`));
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/** Initialize the SDK. Re-init disposes the previous client's timer and
|
|
300
|
+
* listeners and drains its queued work under the OLD configuration (audit
|
|
301
|
+
* F31); previously each init() leaked one interval plus three listeners
|
|
302
|
+
* and silently dropped everything the replaced client had buffered.
|
|
303
|
+
* Numeric options are clamped to finite sane ranges (TO-034). */
|
|
304
|
+
export function init(options) {
|
|
305
|
+
if (!options.endpoint)
|
|
306
|
+
throw new Error("@teploy/observe-browser: endpoint is required");
|
|
307
|
+
const clamp = (v, dflt, min, max) => {
|
|
308
|
+
const n = typeof v === "number" && Number.isFinite(v) ? v : dflt;
|
|
309
|
+
return Math.min(max, Math.max(min, n));
|
|
310
|
+
};
|
|
311
|
+
const previous = client;
|
|
312
|
+
if (previous) {
|
|
313
|
+
previous.dispose();
|
|
314
|
+
// Best-effort final drain of the old client's work to the old endpoint
|
|
315
|
+
// under the old key — never redirected to the new config (TO-036: the
|
|
316
|
+
// old client's requests keep ITS producer identity). Frozen pending
|
|
317
|
+
// requests resend their exact bytes (TO-032).
|
|
318
|
+
drainClient(previous);
|
|
319
|
+
}
|
|
320
|
+
const instance = {
|
|
321
|
+
opts: {
|
|
322
|
+
endpoint: options.endpoint,
|
|
323
|
+
// A key is bound to one site and a different site_id is refused with a
|
|
324
|
+
// 403, so with a key send none and let the key decide.
|
|
325
|
+
siteId: options.siteId ?? (options.apiKey ? "" : "default"),
|
|
326
|
+
apiKey: options.apiKey,
|
|
327
|
+
disableAutoPageview: options.disableAutoPageview ?? false,
|
|
328
|
+
batchSize: clamp(options.batchSize, 50, 1, MAX_EVENTS_PER_REQUEST),
|
|
329
|
+
flushIntervalMs: clamp(options.flushIntervalMs, 2000, 250, 3600000),
|
|
330
|
+
release: options.release,
|
|
331
|
+
environment: options.environment,
|
|
332
|
+
onError: options.onError,
|
|
333
|
+
onRetry: options.onRetry,
|
|
334
|
+
maxRetryAttempts: clamp(options.maxRetryAttempts, 5, 0, 50),
|
|
335
|
+
retryBackoffMs: clamp(options.retryBackoffMs, 1000, 1, 60000),
|
|
336
|
+
requestTimeoutMs: clamp(options.requestTimeoutMs, 10000, 250, 600000),
|
|
337
|
+
},
|
|
338
|
+
buffer: [],
|
|
339
|
+
queuedBytes: 0,
|
|
340
|
+
activeRequest: null,
|
|
341
|
+
pending: [],
|
|
342
|
+
timer: null,
|
|
343
|
+
userId: null,
|
|
344
|
+
sessionId: makeId(),
|
|
345
|
+
producerId: makeId(),
|
|
346
|
+
flushing: null,
|
|
347
|
+
retryCounts: new Map(),
|
|
348
|
+
retryAfter: 0,
|
|
349
|
+
stats: null,
|
|
350
|
+
dispose: () => { },
|
|
351
|
+
crumbs: null,
|
|
352
|
+
flagClient: null,
|
|
353
|
+
exposed: new Set(),
|
|
354
|
+
};
|
|
355
|
+
const bc = options.breadcrumbs;
|
|
356
|
+
const bcOpts = typeof bc === "object" && bc !== null ? bc : {};
|
|
357
|
+
instance.crumbs = createRecorder({ ...bcOpts, ignoreUrls: [...(bcOpts.ignoreUrls ?? []), options.endpoint.replace(/\/+$/, "")] }, (err) => reportError(instance, err));
|
|
358
|
+
instance.flagClient = createFlagClient({
|
|
359
|
+
endpoint: options.endpoint,
|
|
360
|
+
siteId: instance.opts.siteId,
|
|
361
|
+
apiKey: options.apiKey,
|
|
362
|
+
ttlMs: options.flags?.ttlMs,
|
|
363
|
+
timeoutMs: options.flags?.timeoutMs,
|
|
364
|
+
});
|
|
365
|
+
instance.stats = newStats(instance.producerId);
|
|
366
|
+
client = instance;
|
|
367
|
+
if (typeof window !== "undefined") {
|
|
368
|
+
// Listeners are bound to THIS client instance and removed on dispose
|
|
369
|
+
// via an AbortController (audit F31).
|
|
370
|
+
const controller = new AbortController();
|
|
371
|
+
instance.dispose = () => {
|
|
372
|
+
// The window global can vanish between init and dispose in tests and
|
|
373
|
+
// embedded runtimes — teardown must not throw there.
|
|
374
|
+
if (typeof window !== "undefined" && instance.timer !== null)
|
|
375
|
+
window.clearInterval(instance.timer);
|
|
376
|
+
instance.timer = null;
|
|
377
|
+
controller.abort();
|
|
378
|
+
instance.crumbs.uninstall();
|
|
379
|
+
};
|
|
380
|
+
// Auto-flush on buffer age.
|
|
381
|
+
instance.timer = window.setInterval(() => {
|
|
382
|
+
void flushClient(instance);
|
|
383
|
+
}, instance.opts.flushIntervalMs);
|
|
384
|
+
// Flush when the tab is hidden (mobile app-switch, close).
|
|
385
|
+
document.addEventListener("visibilitychange", () => {
|
|
386
|
+
if (document.visibilityState === "hidden")
|
|
387
|
+
void flushClient(instance, true);
|
|
388
|
+
}, { signal: controller.signal });
|
|
389
|
+
// O11: pagehide is the last moment sync work is guaranteed to run —
|
|
390
|
+
// snapshot the undelivered count (visible through onError + getStats)
|
|
391
|
+
// and fire the keepalive flush. Anything still queued after this is
|
|
392
|
+
// honestly reported as the unload loss, never swallowed.
|
|
393
|
+
window.addEventListener("pagehide", () => {
|
|
394
|
+
recordUnloadSnapshot(instance);
|
|
395
|
+
void flushClient(instance, true);
|
|
396
|
+
}, { signal: controller.signal });
|
|
397
|
+
// Autocapture: uncaught errors and promise rejections.
|
|
398
|
+
window.addEventListener("error", (e) => {
|
|
399
|
+
void captureExceptionFor(instance, e.error ?? new Error(e.message), { mechanism: "onerror" });
|
|
400
|
+
}, { signal: controller.signal });
|
|
401
|
+
window.addEventListener("unhandledrejection", (e) => {
|
|
402
|
+
const reason = e.reason;
|
|
403
|
+
void captureExceptionFor(instance, reason instanceof Error ? reason : new Error(String(reason)), {
|
|
404
|
+
mechanism: "onunhandledrejection",
|
|
405
|
+
});
|
|
406
|
+
}, { signal: controller.signal });
|
|
407
|
+
// Opt-in automatic breadcrumbs (installed last so the SDK's own
|
|
408
|
+
// listeners above are unaffected).
|
|
409
|
+
if (bc)
|
|
410
|
+
instance.crumbs.install();
|
|
411
|
+
if (!instance.opts.disableAutoPageview) {
|
|
412
|
+
pageview();
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Record a pageview for the current URL.
|
|
418
|
+
*
|
|
419
|
+
* `pathname` is only carried as a property: the server derives the stored
|
|
420
|
+
* pathname from `url`, so an explicit one is an annotation, not a field.
|
|
421
|
+
*
|
|
422
|
+
* F41: url is origin+path; the allowlisted utm_* campaign params ride as
|
|
423
|
+
* explicit fields. The full query string and fragment never leave the
|
|
424
|
+
* browser.
|
|
425
|
+
*/
|
|
426
|
+
export function pageview(pathname) {
|
|
427
|
+
if (!client)
|
|
428
|
+
return;
|
|
429
|
+
const props = {
|
|
430
|
+
url: pageUrl(),
|
|
431
|
+
referrer: typeof document !== "undefined" ? safeUrl(document.referrer) : "",
|
|
432
|
+
title: typeof document !== "undefined" ? document.title : "",
|
|
433
|
+
...campaignFields(),
|
|
434
|
+
};
|
|
435
|
+
if (pathname)
|
|
436
|
+
props.pathname = pathname;
|
|
437
|
+
track("pageview", props);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Top-level payload keys the ingest endpoint actually reads. Anything else a
|
|
441
|
+
* caller passes to track() is a custom property and must be nested under
|
|
442
|
+
* `properties` — the server stores no other top-level field.
|
|
443
|
+
*/
|
|
444
|
+
const RESERVED_FIELDS = new Set([
|
|
445
|
+
"site_id",
|
|
446
|
+
"event_type",
|
|
447
|
+
"event_id",
|
|
448
|
+
"url",
|
|
449
|
+
"referrer",
|
|
450
|
+
"title",
|
|
451
|
+
"language",
|
|
452
|
+
"screen",
|
|
453
|
+
"distinct_id",
|
|
454
|
+
"release",
|
|
455
|
+
// F41 explicit campaign fields.
|
|
456
|
+
"utm_source",
|
|
457
|
+
"utm_medium",
|
|
458
|
+
"utm_campaign",
|
|
459
|
+
"utm_term",
|
|
460
|
+
"utm_content",
|
|
461
|
+
]);
|
|
462
|
+
/** Server-side cap on custom properties per event. Exceeding it is a 400. */
|
|
463
|
+
const MAX_PROPERTIES = 50;
|
|
464
|
+
/**
|
|
465
|
+
* Record a custom event. Includes distinct_id when identify() has been called.
|
|
466
|
+
*
|
|
467
|
+
* Custom props are nested under `properties`; the handful of keys the server
|
|
468
|
+
* reads as real fields (url, referrer, title, language, screen, distinct_id,
|
|
469
|
+
* release) stay at the top level. Props beyond the server's 50-property cap
|
|
470
|
+
* are dropped rather than letting the whole event be rejected.
|
|
471
|
+
*/
|
|
472
|
+
export function track(eventType, props = {}) {
|
|
473
|
+
const target = client;
|
|
474
|
+
if (!target)
|
|
475
|
+
return;
|
|
476
|
+
const payload = {};
|
|
477
|
+
const properties = {};
|
|
478
|
+
for (const key of Object.keys(props)) {
|
|
479
|
+
// SDK-owned identity fields are assigned LAST (below) so a caller
|
|
480
|
+
// cannot override site/event/id routing through props (TO-033).
|
|
481
|
+
if (key === "site_id" || key === "event_type" || key === "event_id")
|
|
482
|
+
continue;
|
|
483
|
+
if (RESERVED_FIELDS.has(key)) {
|
|
484
|
+
payload[key] = props[key];
|
|
485
|
+
}
|
|
486
|
+
else if (Object.keys(properties).length < MAX_PROPERTIES) {
|
|
487
|
+
properties[key] = props[key];
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (Object.keys(properties).length > 0)
|
|
491
|
+
payload.properties = properties;
|
|
492
|
+
if (target.userId)
|
|
493
|
+
payload.distinct_id = target.userId;
|
|
494
|
+
if (target.opts.release)
|
|
495
|
+
payload.release = target.opts.release;
|
|
496
|
+
payload.site_id = target.opts.siteId;
|
|
497
|
+
payload.event_type = eventType;
|
|
498
|
+
payload.event_id = makeId();
|
|
499
|
+
// TO-033: snapshot the record at admission. The queue owns immutable
|
|
500
|
+
// bytes — caller mutations after track() (nested objects, arrays) can no
|
|
501
|
+
// longer change the eventual body, and an unserializable record (BigInt,
|
|
502
|
+
// circular) is isolated and reported here instead of poisoning the flush.
|
|
503
|
+
let raw;
|
|
504
|
+
try {
|
|
505
|
+
raw = JSON.stringify(payload);
|
|
506
|
+
}
|
|
507
|
+
catch (err) {
|
|
508
|
+
countDrop(target, "admission_unserializable", 1, err instanceof Error ? err.message : String(err));
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
const bytes = textEncoder.encode(raw).byteLength;
|
|
512
|
+
if (bytes > MAX_EVENT_BYTES) {
|
|
513
|
+
countDrop(target, "admission_oversize", 1, `${bytes} > ${MAX_EVENT_BYTES}`);
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
// TO-034: admission-time count+byte budget across queued and pending —
|
|
517
|
+
// during retry backoff or a hanging request the buffer can no longer
|
|
518
|
+
// grow without limit. Overflow drops the NEWEST record (the oldest data
|
|
519
|
+
// is closest to delivery) and says so.
|
|
520
|
+
if (queuedEvents(target) >= MAX_QUEUED_EVENTS || target.queuedBytes + bytes + 256 > MAX_QUEUED_BYTES) {
|
|
521
|
+
countDrop(target, "queue_full", 1, "drop-newest overflow policy");
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
target.buffer.push(raw);
|
|
525
|
+
target.queuedBytes += bytes + 256;
|
|
526
|
+
if (target.buffer.length >= target.opts.batchSize)
|
|
527
|
+
flush();
|
|
528
|
+
}
|
|
529
|
+
/** Trait keys that duplicate the raw identity (audit F33). The ID travels
|
|
530
|
+
* only in the top-level distinct_id field the server hashes; these keys
|
|
531
|
+
* used to copy it verbatim into stored event properties. */
|
|
532
|
+
const FORBIDDEN_ID_TRAITS = new Set(["user_id", "distinct_id", "email"]);
|
|
533
|
+
/**
|
|
534
|
+
* Associate subsequent events with a user id (and optional traits).
|
|
535
|
+
*
|
|
536
|
+
* Stores the userId locally and emits a one-shot `$identify` event so the
|
|
537
|
+
* server can record the identification in the events stream. Traits ride
|
|
538
|
+
* as event properties minus any identity-shaped key. Every subsequent
|
|
539
|
+
* track()/captureException() call includes `distinct_id` in the payload —
|
|
540
|
+
* the server hashes it with the per-site `session_salt` before storage,
|
|
541
|
+
* matching the existing session-id privacy pattern.
|
|
542
|
+
*/
|
|
543
|
+
export function identify(userId, traits) {
|
|
544
|
+
if (!client || !userId)
|
|
545
|
+
return;
|
|
546
|
+
client.userId = userId;
|
|
547
|
+
const safe = {};
|
|
548
|
+
if (traits) {
|
|
549
|
+
for (const [key, value] of Object.entries(traits)) {
|
|
550
|
+
if (FORBIDDEN_ID_TRAITS.has(key) || RESERVED_FIELDS.has(key))
|
|
551
|
+
continue;
|
|
552
|
+
if (Object.keys(safe).length < MAX_PROPERTIES)
|
|
553
|
+
safe[key] = value;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
track("$identify", safe);
|
|
557
|
+
}
|
|
558
|
+
/** Clear the current user — call on logout. */
|
|
559
|
+
export function reset() {
|
|
560
|
+
if (!client)
|
|
561
|
+
return;
|
|
562
|
+
client.userId = null;
|
|
563
|
+
client.sessionId = makeId();
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* The current client-generated session id, or null before init(). Lets a
|
|
567
|
+
* separately-loaded script (e.g. observe-replay.js, which tracks its own
|
|
568
|
+
* session id via setSessionId()) correlate its events with this session
|
|
569
|
+
* rather than defaulting to an empty session_id.
|
|
570
|
+
*/
|
|
571
|
+
export function getSessionId() {
|
|
572
|
+
return client ? client.sessionId : null;
|
|
573
|
+
}
|
|
574
|
+
/** Record a breadcrumb by hand. Works whether or not automatic capture is
|
|
575
|
+
* enabled; a no-op before init(). Never throws. */
|
|
576
|
+
export function addBreadcrumb(crumb) {
|
|
577
|
+
try {
|
|
578
|
+
client?.crumbs.add(crumb);
|
|
579
|
+
}
|
|
580
|
+
catch {
|
|
581
|
+
/* never throw into application code */
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
/** Drop all buffered breadcrumbs. */
|
|
585
|
+
export function clearBreadcrumbs() {
|
|
586
|
+
client?.crumbs.clear();
|
|
587
|
+
}
|
|
588
|
+
/** Submit a message (no exception object) as an issue event. Sends
|
|
589
|
+
* immediately; never rejects. Level defaults to "info". */
|
|
590
|
+
export function captureMessage(message, ctx) {
|
|
591
|
+
if (!client)
|
|
592
|
+
return Promise.resolve();
|
|
593
|
+
const target = client;
|
|
594
|
+
const payload = buildErrorPayload(target, "Message", String(message), ctx, { level: ctx?.level ?? "info", mechanism: ctx?.mechanism ?? "message" });
|
|
595
|
+
return sendJSON(target, "/api/v1/errors", payload).catch((sendErr) => {
|
|
596
|
+
reportError(target, sendErr instanceof Error ? sendErr : new Error(String(sendErr)));
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
/** Submit an error. Sends immediately — not buffered. Never rejects into
|
|
600
|
+
* application code (AUD-021: the strict transport's rejection is reported
|
|
601
|
+
* through onError instead). */
|
|
602
|
+
export function captureException(err, ctx) {
|
|
603
|
+
if (!client)
|
|
604
|
+
return Promise.resolve();
|
|
605
|
+
return captureExceptionFor(client, err, ctx);
|
|
606
|
+
}
|
|
607
|
+
function captureExceptionFor(target, err, ctx) {
|
|
608
|
+
const payload = buildErrorPayload(target, err.name || "Error", err.message || String(err), ctx, {
|
|
609
|
+
level: ctx?.level ?? "error",
|
|
610
|
+
mechanism: ctx?.mechanism ?? "manual",
|
|
611
|
+
stack: parseStack(err.stack),
|
|
612
|
+
});
|
|
613
|
+
// Fire-and-forget public boundary (AUD-021): report, don't reject.
|
|
614
|
+
return sendJSON(target, "/api/v1/errors", payload).catch((sendErr) => {
|
|
615
|
+
reportError(target, sendErr instanceof Error ? sendErr : new Error(String(sendErr)));
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
function buildErrorPayload(target, errorType, errorValue, ctx, o) {
|
|
619
|
+
const payload = {
|
|
620
|
+
site_id: target.opts.siteId,
|
|
621
|
+
event_id: makeId(),
|
|
622
|
+
error_type: errorType,
|
|
623
|
+
error_value: errorValue,
|
|
624
|
+
release_tag: ctx?.release ?? target.opts.release,
|
|
625
|
+
environment: ctx?.environment ?? target.opts.environment ?? "production",
|
|
626
|
+
mechanism: o.mechanism,
|
|
627
|
+
url: pageUrl(),
|
|
628
|
+
level: o.level,
|
|
629
|
+
stack_trace: o.stack,
|
|
630
|
+
};
|
|
631
|
+
// Breadcrumbs recorded so far ride along (snapshot: later crumbs do not
|
|
632
|
+
// mutate an in-flight payload).
|
|
633
|
+
const crumbs = target.crumbs.snapshot();
|
|
634
|
+
if (crumbs.length > 0)
|
|
635
|
+
payload.breadcrumbs = crumbs;
|
|
636
|
+
// Tags ride in the server-supported `extra` envelope (it has no
|
|
637
|
+
// top-level tags field).
|
|
638
|
+
if (ctx?.tags && Object.keys(ctx.tags).length > 0) {
|
|
639
|
+
payload.extra = { tags: { ...ctx.tags } };
|
|
640
|
+
}
|
|
641
|
+
// Callers tracing their own operations can pass the active trace context
|
|
642
|
+
// for exact trace<->error correlation in the trace detail view.
|
|
643
|
+
if (ctx?.traceId)
|
|
644
|
+
payload.trace_id = ctx.traceId;
|
|
645
|
+
if (ctx?.spanId)
|
|
646
|
+
payload.span_id = ctx.spanId;
|
|
647
|
+
// If observe-replay.js is on the page, attach the active replay id so the
|
|
648
|
+
// Errors UI can cross-jump to the session replay.
|
|
649
|
+
const replayId = activeReplayId();
|
|
650
|
+
if (replayId)
|
|
651
|
+
payload.replay_id = replayId;
|
|
652
|
+
if (target.userId)
|
|
653
|
+
payload.distinct_id = target.userId;
|
|
654
|
+
return payload;
|
|
655
|
+
}
|
|
656
|
+
/** Evaluate one feature flag against the server (POST /api/v1/flags/evaluate).
|
|
657
|
+
* Never rejects: on any failure it resolves to ctx.default (or disabled)
|
|
658
|
+
* with `source: "default"`. Results are cached for the TTL and identical
|
|
659
|
+
* in-flight calls are coalesced. `userId` defaults to the identify()d user.
|
|
660
|
+
* Exposure is NOT recorded unless you pass `exposure: true` (records one
|
|
661
|
+
* "flag_exposure" event per flag/user/variant) or call track() yourself
|
|
662
|
+
* where the variant is actually rendered. Resolves to the default before init(). */
|
|
663
|
+
export function evaluateFlag(key, ctx) {
|
|
664
|
+
const target = client;
|
|
665
|
+
if (!target)
|
|
666
|
+
return Promise.resolve(defaultOnly(key, ctx, "sdk not initialized"));
|
|
667
|
+
return target.flagClient.evaluateFlag(key, withUser(target, ctx)).then((r) => {
|
|
668
|
+
maybeExpose(target, r, ctx);
|
|
669
|
+
return r;
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
/** Evaluate several flags concurrently (duplicate keys collapse; at most 50
|
|
673
|
+
* per call). Same failure and exposure semantics as evaluateFlag. */
|
|
674
|
+
export function evaluateFlags(keys, ctx) {
|
|
675
|
+
const target = client;
|
|
676
|
+
if (!target) {
|
|
677
|
+
const out = {};
|
|
678
|
+
for (const k of Array.isArray(keys) ? keys : [])
|
|
679
|
+
out[k] = defaultOnly(k, ctx, "sdk not initialized");
|
|
680
|
+
return Promise.resolve(out);
|
|
681
|
+
}
|
|
682
|
+
return target.flagClient.evaluateFlags(keys, withUser(target, ctx)).then((rs) => {
|
|
683
|
+
for (const r of Object.values(rs))
|
|
684
|
+
maybeExpose(target, r, ctx);
|
|
685
|
+
return rs;
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
function withUser(target, ctx) {
|
|
689
|
+
return { ...ctx, userId: ctx?.userId ?? target.userId ?? "" };
|
|
690
|
+
}
|
|
691
|
+
function defaultOnly(key, ctx, error) {
|
|
692
|
+
return {
|
|
693
|
+
key,
|
|
694
|
+
enabled: ctx?.default?.enabled === true,
|
|
695
|
+
...(ctx?.default?.variant ? { variant: ctx.default.variant } : {}),
|
|
696
|
+
reason: "default",
|
|
697
|
+
source: "default",
|
|
698
|
+
error,
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
function maybeExpose(target, r, ctx) {
|
|
702
|
+
if (ctx?.exposure !== true || r.source === "default" || client !== target)
|
|
703
|
+
return;
|
|
704
|
+
const id = JSON.stringify([r.key, ctx.userId ?? target.userId ?? "", r.enabled, r.variant ?? ""]);
|
|
705
|
+
if (target.exposed.has(id))
|
|
706
|
+
return;
|
|
707
|
+
if (target.exposed.size >= 1000)
|
|
708
|
+
target.exposed.clear();
|
|
709
|
+
target.exposed.add(id);
|
|
710
|
+
track("flag_exposure", { flag_key: r.key, enabled: r.enabled, ...(r.variant ? { variant: r.variant } : {}) });
|
|
711
|
+
}
|
|
712
|
+
function activeReplayId() {
|
|
713
|
+
if (typeof window === "undefined")
|
|
714
|
+
return null;
|
|
715
|
+
const r = window.observeReplay;
|
|
716
|
+
if (r && typeof r.getReplayId === "function") {
|
|
717
|
+
try {
|
|
718
|
+
const id = r.getReplayId();
|
|
719
|
+
return typeof id === "string" && id ? id : null;
|
|
720
|
+
}
|
|
721
|
+
catch {
|
|
722
|
+
return null;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
return null;
|
|
726
|
+
}
|
|
727
|
+
/** Submit a log entry. Fire-and-forget: failures are reported through
|
|
728
|
+
* onError, never rejected into application code (AUD-021). */
|
|
729
|
+
export function log(entry) {
|
|
730
|
+
const target = client;
|
|
731
|
+
if (!target)
|
|
732
|
+
return Promise.resolve();
|
|
733
|
+
return sendJSON(target, "/api/v1/logs", { site_id: target.opts.siteId, ...entry })
|
|
734
|
+
.catch((err) => {
|
|
735
|
+
reportError(target, err instanceof Error ? err : new Error(String(err)));
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
/** Split events into server-legal chunks by count and encoded bytes
|
|
739
|
+
* (AUD-026). */
|
|
740
|
+
/** Release the queue reservation of a delivered/abandoned request (TO-034). */
|
|
741
|
+
function releaseRequest(target, req) {
|
|
742
|
+
target.queuedBytes -= req.bytes;
|
|
743
|
+
if (target.queuedBytes < 0)
|
|
744
|
+
target.queuedBytes = 0;
|
|
745
|
+
target.retryCounts.delete(req.batchId);
|
|
746
|
+
}
|
|
747
|
+
/** Drop the OLDEST pending requests over the retention bounds, reporting
|
|
748
|
+
* each. Called under the flush owner only. */
|
|
749
|
+
function trimPending(target) {
|
|
750
|
+
let droppedRequests = 0;
|
|
751
|
+
let droppedEvents = 0;
|
|
752
|
+
while (target.pending.length > MAX_PENDING_REQUESTS || target.queuedBytes > MAX_QUEUED_BYTES) {
|
|
753
|
+
const oldest = target.pending.shift();
|
|
754
|
+
if (!oldest)
|
|
755
|
+
break;
|
|
756
|
+
releaseRequest(target, oldest);
|
|
757
|
+
droppedRequests++;
|
|
758
|
+
droppedEvents += oldest.eventCount;
|
|
759
|
+
}
|
|
760
|
+
if (droppedRequests > 0) {
|
|
761
|
+
countDrop(target, "retention_cap", droppedEvents, `${droppedRequests} oldest pending request(s), drop-oldest policy`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
/** Send one frozen request and consume its acknowledgment. Returns the
|
|
765
|
+
* ack on acceptance (including partial rejections, which are counted and
|
|
766
|
+
* reported but NOT retried — the rejected events are gone server-side and
|
|
767
|
+
* the accepted neighbors must not be resent). */
|
|
768
|
+
async function deliverRequest(target, req, unloading) {
|
|
769
|
+
const ack = await fetchWithDeadline(target.opts.endpoint.replace(/\/+$/, "") + "/api/v1/events/batch", requestInitFor(target, req.body, unloading), target.opts.requestTimeoutMs, readEventBatchAck);
|
|
770
|
+
target.stats.deliveredBatches++;
|
|
771
|
+
const rejected = ack.rejected ?? 0;
|
|
772
|
+
target.stats.deliveredEvents += Math.max(req.eventCount - rejected, 0);
|
|
773
|
+
if (rejected > 0) {
|
|
774
|
+
countDrop(target, "server_rejected", rejected, `server accepted ${ack.accepted ?? req.eventCount - rejected} of ${req.eventCount}`);
|
|
775
|
+
}
|
|
776
|
+
return ack;
|
|
777
|
+
}
|
|
778
|
+
/** Build the fetch init for a frozen body. */
|
|
779
|
+
function requestInitFor(target, body, unloading) {
|
|
780
|
+
const headers = { "Content-Type": "application/json" };
|
|
781
|
+
if (target.opts.apiKey)
|
|
782
|
+
headers["X-API-Key"] = target.opts.apiKey;
|
|
783
|
+
return {
|
|
784
|
+
method: "POST",
|
|
785
|
+
headers,
|
|
786
|
+
body,
|
|
787
|
+
credentials: "omit",
|
|
788
|
+
keepalive: unloading && textEncoder.encode(body).byteLength <= MAX_KEEPALIVE_BYTES,
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
/** Best-effort final drain of a replaced client's work (TO-036): pending
|
|
792
|
+
* requests resend their exact bytes under their own producer identity;
|
|
793
|
+
* buffered records are frozen into fresh requests. Failures are counted
|
|
794
|
+
* as visible losses and reported, never retried (the replacement owns the
|
|
795
|
+
* timer from here on). */
|
|
796
|
+
function drainClient(target) {
|
|
797
|
+
if (target.flushing) {
|
|
798
|
+
void target.flushing.finally(() => drainClient(target));
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
const requests = [...target.pending];
|
|
802
|
+
target.pending = [];
|
|
803
|
+
if (target.buffer.length > 0) {
|
|
804
|
+
const entries = target.buffer.splice(0);
|
|
805
|
+
target.queuedBytes -= entries.reduce((n, raw) => n + textEncoder.encode(raw).byteLength + 256, 0);
|
|
806
|
+
const fresh = packEventRequests(target.producerId, entries, (why) => {
|
|
807
|
+
countDrop(target, "pack_oversize", 1, `${why} on re-init`);
|
|
808
|
+
});
|
|
809
|
+
target.queuedBytes += fresh.reduce((n, req) => n + req.bytes, 0);
|
|
810
|
+
requests.push(...fresh);
|
|
811
|
+
}
|
|
812
|
+
for (const req of requests) {
|
|
813
|
+
deliverRequest(target, req, true)
|
|
814
|
+
.then(() => releaseRequest(target, req))
|
|
815
|
+
.catch((err) => {
|
|
816
|
+
releaseRequest(target, req);
|
|
817
|
+
countDrop(target, "reinit_drain_failed", req.eventCount, err instanceof Error ? err.message : String(err));
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
/** Flush a specific client's queue.
|
|
822
|
+
*
|
|
823
|
+
* AUD-022 (round 2): ONE flush owner per client.
|
|
824
|
+
*
|
|
825
|
+
* TO-032: delivery units are FROZEN request envelopes. A request keeps its
|
|
826
|
+
* identity and exact bytes across every retry — a failed batch is never
|
|
827
|
+
* merged back into the live buffer, so a retry can never reuse an
|
|
828
|
+
* already-acknowledged batch id for different content (the old repack
|
|
829
|
+
* lost the newly queued tail whenever the server recognized the id).
|
|
830
|
+
*
|
|
831
|
+
* F32 retry policy: a failed request is re-sent automatically with a
|
|
832
|
+
* doubling backoff (retryAfter gate below) until maxRetryAttempts, then
|
|
833
|
+
* dropped with an onError report. Retries keep their producer/batch ids
|
|
834
|
+
* (F12), so the server dedupes any redelivery. */
|
|
835
|
+
function flushClient(target, unloading = false) {
|
|
836
|
+
if (target.flushing)
|
|
837
|
+
return target.flushing;
|
|
838
|
+
// Backoff gate: during the retry sleep, wakeups (timer, visibility,
|
|
839
|
+
// explicit flush()) do not send. The unload path is exempt — it is a
|
|
840
|
+
// last-gasp best effort with nothing left to wait for.
|
|
841
|
+
if (!unloading && Date.now() < target.retryAfter)
|
|
842
|
+
return Promise.resolve();
|
|
843
|
+
const work = Promise.resolve().then(async () => {
|
|
844
|
+
for (let units = 0; units < 8; units++) {
|
|
845
|
+
// Freeze newly recorded records into requests first: retries of
|
|
846
|
+
// older requests keep FIFO order ahead of them.
|
|
847
|
+
if (target.buffer.length > 0) {
|
|
848
|
+
const entries = target.buffer.splice(0);
|
|
849
|
+
target.queuedBytes -= entries.reduce((n, raw) => n + textEncoder.encode(raw).byteLength + 256, 0);
|
|
850
|
+
if (target.queuedBytes < 0)
|
|
851
|
+
target.queuedBytes = 0;
|
|
852
|
+
const fresh = packEventRequests(target.producerId, entries, (why) => {
|
|
853
|
+
countDrop(target, "pack_oversize", 1, why);
|
|
854
|
+
});
|
|
855
|
+
target.queuedBytes += fresh.reduce((n, req) => n + req.bytes, 0);
|
|
856
|
+
target.pending.push(...fresh);
|
|
857
|
+
trimPending(target);
|
|
858
|
+
}
|
|
859
|
+
const req = target.pending.shift();
|
|
860
|
+
if (!req)
|
|
861
|
+
return;
|
|
862
|
+
target.activeRequest = req;
|
|
863
|
+
try {
|
|
864
|
+
await deliverRequest(target, req, unloading);
|
|
865
|
+
releaseRequest(target, req);
|
|
866
|
+
}
|
|
867
|
+
catch (err) {
|
|
868
|
+
const sendErr = err instanceof Error ? err : new Error(String(err));
|
|
869
|
+
const attempts = (target.retryCounts.get(req.batchId) ?? 0) + 1;
|
|
870
|
+
if (attempts > target.opts.maxRetryAttempts) {
|
|
871
|
+
// Retry budget exhausted: give up on THIS request only. Its
|
|
872
|
+
// reservation is released; later requests keep their turn.
|
|
873
|
+
releaseRequest(target, req);
|
|
874
|
+
countDrop(target, "retry_exhausted", req.eventCount, `${target.opts.maxRetryAttempts} attempts, last error: ${sendErr.message}`);
|
|
875
|
+
}
|
|
876
|
+
else {
|
|
877
|
+
target.retryCounts.set(req.batchId, attempts);
|
|
878
|
+
target.stats.retries++;
|
|
879
|
+
const delayMs = Math.min(target.opts.retryBackoffMs * 2 ** (attempts - 1), MAX_RETRY_DELAY_MS);
|
|
880
|
+
target.retryAfter = Date.now() + delayMs;
|
|
881
|
+
// Delivery failed: the frozen request keeps its bytes and its
|
|
882
|
+
// place at the head of the queue; the backoff gate above holds
|
|
883
|
+
// the next attempt until the retry moment.
|
|
884
|
+
target.pending.unshift(req);
|
|
885
|
+
trimPending(target);
|
|
886
|
+
reportRetry(target, { attempt: attempts, delayMs, batchSize: req.eventCount, error: sendErr });
|
|
887
|
+
}
|
|
888
|
+
target.activeRequest = null;
|
|
889
|
+
reportError(target, sendErr);
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
target.activeRequest = null;
|
|
893
|
+
if (unloading)
|
|
894
|
+
return; // one best-effort request per unload
|
|
895
|
+
}
|
|
896
|
+
});
|
|
897
|
+
const owned = work.finally(() => {
|
|
898
|
+
if (target.flushing === owned)
|
|
899
|
+
target.flushing = null;
|
|
900
|
+
});
|
|
901
|
+
target.flushing = owned;
|
|
902
|
+
return owned;
|
|
903
|
+
}
|
|
904
|
+
/** Force an immediate flush of buffered events. */
|
|
905
|
+
export function flush() {
|
|
906
|
+
if (client?.flushing)
|
|
907
|
+
return client.flushing;
|
|
908
|
+
if (!client || (client.buffer.length === 0 && client.pending.length === 0))
|
|
909
|
+
return Promise.resolve();
|
|
910
|
+
return flushClient(client);
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* O11 diagnostics: delivery and loss counters for the active client
|
|
914
|
+
* (null before init()). Every dropped event is counted here by reason AND
|
|
915
|
+
* reported through onError — the SDK never loses events silently.
|
|
916
|
+
* `queued` is live; the rest are monotone counters.
|
|
917
|
+
*/
|
|
918
|
+
export function getStats() {
|
|
919
|
+
if (!client)
|
|
920
|
+
return null;
|
|
921
|
+
const snapshot = {
|
|
922
|
+
deliveredBatches: client.stats.deliveredBatches,
|
|
923
|
+
deliveredEvents: client.stats.deliveredEvents,
|
|
924
|
+
retries: client.stats.retries,
|
|
925
|
+
dropped: { ...client.stats.dropped },
|
|
926
|
+
undeliveredAtUnload: client.stats.undeliveredAtUnload,
|
|
927
|
+
queued: queuedEvents(client),
|
|
928
|
+
producerId: client.producerId,
|
|
929
|
+
};
|
|
930
|
+
return snapshot;
|
|
931
|
+
}
|
|
932
|
+
/** Parse one stack frame line in V8 or SpiderMonkey syntax.
|
|
933
|
+
*
|
|
934
|
+
* Audit F30: the old regex's filename group excluded ':' entirely, so any
|
|
935
|
+
* http(s) URL, port number, or Windows drive path failed to match and the
|
|
936
|
+
* frame was dropped — normal web errors lost their stacks. The location is
|
|
937
|
+
* now matched as "everything up to the final :line:col suffix", which
|
|
938
|
+
* accepts URLs, ports, and file:/// and drive-letter paths.
|
|
939
|
+
*/
|
|
940
|
+
function parseFrame(line) {
|
|
941
|
+
line = line.trim();
|
|
942
|
+
let fn = "<anonymous>";
|
|
943
|
+
let location = line;
|
|
944
|
+
if (line.startsWith("at ")) {
|
|
945
|
+
location = line.slice(3);
|
|
946
|
+
const paren = location.lastIndexOf(" (");
|
|
947
|
+
if (paren >= 0 && location.endsWith(")")) {
|
|
948
|
+
fn = location.slice(0, paren);
|
|
949
|
+
location = location.slice(paren + 2, -1);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
else {
|
|
953
|
+
const at = line.indexOf("@");
|
|
954
|
+
if (at < 0)
|
|
955
|
+
return null;
|
|
956
|
+
fn = location.slice(0, at) || fn;
|
|
957
|
+
location = location.slice(at + 1);
|
|
958
|
+
}
|
|
959
|
+
const m = /^(.*):(\d+):(\d+)$/.exec(location);
|
|
960
|
+
if (!m || !m[1])
|
|
961
|
+
return null;
|
|
962
|
+
const lineno = Number(m[2]);
|
|
963
|
+
const colno = Number(m[3]);
|
|
964
|
+
if (!Number.isSafeInteger(lineno) || !Number.isSafeInteger(colno))
|
|
965
|
+
return null;
|
|
966
|
+
return { function: fn, filename: m[1], lineno, colno, in_app: !/node_modules|chrome-extension:/.test(m[1]) };
|
|
967
|
+
}
|
|
968
|
+
function parseStack(stack) {
|
|
969
|
+
if (!stack)
|
|
970
|
+
return undefined;
|
|
971
|
+
const frames = [];
|
|
972
|
+
for (const line of stack.split("\n").slice(0, 50)) {
|
|
973
|
+
const frame = parseFrame(line);
|
|
974
|
+
if (frame)
|
|
975
|
+
frames.push(frame);
|
|
976
|
+
}
|
|
977
|
+
return frames.length ? frames : undefined;
|
|
978
|
+
}
|
|
979
|
+
// Default export for convenience with older bundlers.
|
|
980
|
+
export default { init, pageview, track, identify, reset, captureException, captureMessage, addBreadcrumb, clearBreadcrumbs, evaluateFlag, evaluateFlags, log, flush, getStats };
|
|
981
|
+
//# sourceMappingURL=index.js.map
|