@omaralex24/zenith-browser 0.0.0-stage → 0.1.4

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/dist/client.js ADDED
@@ -0,0 +1,1135 @@
1
+ import { attachFlightRecorder } from "./flight.js";
2
+ import { attachWebVitalsTracker, webVitalsProperties } from "./vitals.js";
3
+ import { redactObject, redactSensitiveString } from "./scrub.js";
4
+ import { generateUuidV7 } from "./uuidv7.js";
5
+ import { parseActiveSurveysPayload, surveyUrlMatches } from "./surveys.js";
6
+ export class MemoryStorage {
7
+ values = new Map();
8
+ getItem(key) {
9
+ return this.values.has(key) ? (this.values.get(key) ?? null) : null;
10
+ }
11
+ setItem(key, value) {
12
+ this.values.set(key, String(value));
13
+ }
14
+ removeItem(key) {
15
+ this.values.delete(key);
16
+ }
17
+ }
18
+ const DEFAULT_FLUSH_INTERVAL_MS = 5_000;
19
+ const DEFAULT_MAX_BATCH_SIZE = 50;
20
+ const DEFAULT_MAX_QUEUE_SIZE = 500;
21
+ const DEFAULT_FLAG_FETCH_TIMEOUT_MS = 3_000;
22
+ const DEFAULT_SURVEY_FETCH_TIMEOUT_MS = 3_000;
23
+ const SURVEY_COOLDOWN_DAY_MS = 24 * 60 * 60 * 1_000;
24
+ const DEFAULT_MAX_SESSION_FLIGHT_BYTES = 128 * 1024;
25
+ const MAX_FLIGHT_FLUSH_BATCH_BYTES = 28 * 1024;
26
+ const SESSION_INACTIVITY_MS = 30 * 60 * 1_000;
27
+ const SESSION_MAX_AGE_MS = 24 * 60 * 60 * 1_000;
28
+ const FLIGHT_KINDS = new Set([
29
+ "ui_action",
30
+ "navigation",
31
+ "network",
32
+ "console",
33
+ "exception",
34
+ "state",
35
+ ]);
36
+ const FLIGHT_LEVELS = new Set(["info", "warn", "error"]);
37
+ function byteLength(value) {
38
+ return new TextEncoder().encode(value).length;
39
+ }
40
+ function compact(input) {
41
+ for (const key of Object.keys(input)) {
42
+ if (input[key] === undefined)
43
+ delete input[key];
44
+ }
45
+ return input;
46
+ }
47
+ function fnv1a(input) {
48
+ let hash = 0x811c9dc5;
49
+ for (let i = 0; i < input.length; i += 1) {
50
+ hash ^= input.charCodeAt(i);
51
+ hash = Math.imul(hash, 0x01000193) >>> 0;
52
+ }
53
+ return hash.toString(16).padStart(8, "0");
54
+ }
55
+ function storedIdentifier(value) {
56
+ if (!value)
57
+ return undefined;
58
+ const trimmed = value.trim();
59
+ return trimmed.length > 0 && byteLength(trimmed) <= 256 ? trimmed : undefined;
60
+ }
61
+ function copyFeatureFlagPayloads(value) {
62
+ if (!value || typeof value !== "object" || Array.isArray(value))
63
+ return {};
64
+ const output = {};
65
+ for (const [key, payload] of Object.entries(value)) {
66
+ if (payload && typeof payload === "object" && !Array.isArray(payload))
67
+ output[key] = payload;
68
+ }
69
+ return output;
70
+ }
71
+ function browserWindow() {
72
+ try {
73
+ if (typeof window !== "undefined")
74
+ return window;
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ return undefined;
80
+ }
81
+ function safeStorage() {
82
+ try {
83
+ const storage = globalThis.localStorage;
84
+ if (storage) {
85
+ const probe = "__zenith_probe__";
86
+ storage.setItem(probe, "1");
87
+ storage.removeItem(probe);
88
+ return storage;
89
+ }
90
+ }
91
+ catch {
92
+ }
93
+ return new MemoryStorage();
94
+ }
95
+ function storageGet(storage, key) {
96
+ try {
97
+ return storage.getItem(key) ?? undefined;
98
+ }
99
+ catch {
100
+ return undefined;
101
+ }
102
+ }
103
+ function storageSet(storage, key, value) {
104
+ try {
105
+ storage.setItem(key, value);
106
+ }
107
+ catch {
108
+ }
109
+ }
110
+ function storageRemove(storage, key) {
111
+ try {
112
+ storage.removeItem(key);
113
+ }
114
+ catch {
115
+ }
116
+ }
117
+ function copyFeatureFlags(value) {
118
+ if (!value || typeof value !== "object" || Array.isArray(value))
119
+ return undefined;
120
+ const output = {};
121
+ for (const [key, flagValue] of Object.entries(value)) {
122
+ if (!key || byteLength(key) > 256)
123
+ continue;
124
+ if (typeof flagValue === "boolean" || typeof flagValue === "string") {
125
+ Object.defineProperty(output, key, {
126
+ value: flagValue,
127
+ enumerable: true,
128
+ configurable: true,
129
+ writable: true,
130
+ });
131
+ }
132
+ }
133
+ return output;
134
+ }
135
+ function featureFlagsEqual(left, right) {
136
+ const leftKeys = Object.keys(left);
137
+ const rightKeys = Object.keys(right);
138
+ if (leftKeys.length !== rightKeys.length)
139
+ return false;
140
+ return leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && left[key] === right[key]);
141
+ }
142
+ function currentUrl(win) {
143
+ try {
144
+ const href = win?.location?.href ?? globalThis.location?.href;
145
+ return href ? new URL(href) : undefined;
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ }
151
+ function normalizeRoutePath(value, win) {
152
+ if (!value)
153
+ return undefined;
154
+ try {
155
+ const base = currentUrl(win)?.href ?? "http://localhost/";
156
+ return redactSensitiveString(new URL(value, base).pathname || "/");
157
+ }
158
+ catch {
159
+ return redactSensitiveString(value.split(/[?#]/, 1)[0] || "/");
160
+ }
161
+ }
162
+ function currentPath(win) {
163
+ const url = currentUrl(win);
164
+ return url?.pathname || undefined;
165
+ }
166
+ function currentReferrer(win) {
167
+ try {
168
+ const referrer = win?.document?.referrer;
169
+ return referrer ? redactSensitiveString(referrer) : undefined;
170
+ }
171
+ catch {
172
+ return undefined;
173
+ }
174
+ }
175
+ function currentUtmSource(win) {
176
+ const url = currentUrl(win);
177
+ const value = url?.searchParams.get("utm_source")?.trim();
178
+ return value ? redactSensitiveString(value) : undefined;
179
+ }
180
+ function inferDeviceType(win) {
181
+ let agent = "";
182
+ try {
183
+ agent = (win?.navigator?.userAgent ?? globalThis.navigator?.userAgent ?? "").toLowerCase();
184
+ }
185
+ catch {
186
+ agent = "";
187
+ }
188
+ if (/ipad|tablet|kindle|playbook/.test(agent) || (agent.includes("android") && !agent.includes("mobile")))
189
+ return "tablet";
190
+ if (/mobi|iphone|ipod|android|blackberry|phone/.test(agent))
191
+ return "mobile";
192
+ return "desktop";
193
+ }
194
+ function resolveFetch(fetchImpl) {
195
+ if (fetchImpl)
196
+ return fetchImpl;
197
+ if (typeof globalThis.fetch !== "function") {
198
+ throw new Error("ZenithClient requires a fetch implementation in this runtime");
199
+ }
200
+ return globalThis.fetch.bind(globalThis);
201
+ }
202
+ function sleep(ms) {
203
+ return new Promise((resolve) => setTimeout(resolve, ms));
204
+ }
205
+ function asJsonObject(value, name) {
206
+ if (value === undefined)
207
+ return {};
208
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
209
+ throw new TypeError(`${name} must be a JSON object`);
210
+ }
211
+ return redactObject(value);
212
+ }
213
+ function validateIdentifier(value, name) {
214
+ const trimmed = value.trim();
215
+ if (!trimmed || byteLength(trimmed) > 256) {
216
+ throw new TypeError(`${name} must be a non-empty string up to 256 bytes`);
217
+ }
218
+ return trimmed;
219
+ }
220
+ function beaconBody(body) {
221
+ if (typeof Blob !== "undefined") {
222
+ return new Blob([body], { type: "text/plain;charset=UTF-8" });
223
+ }
224
+ return body;
225
+ }
226
+ function collectSeoProperties(win) {
227
+ try {
228
+ const doc = win?.document ?? (typeof document === "undefined" ? undefined : document);
229
+ if (!doc)
230
+ return {};
231
+ const title = typeof doc.title === "string" ? doc.title : "";
232
+ const query = (selector) => {
233
+ try {
234
+ return doc.querySelector(selector);
235
+ }
236
+ catch {
237
+ return null;
238
+ }
239
+ };
240
+ const count = (selector) => {
241
+ try {
242
+ return doc.querySelectorAll(selector).length;
243
+ }
244
+ catch {
245
+ return 0;
246
+ }
247
+ };
248
+ const content = (element) => {
249
+ try {
250
+ return element?.getAttribute("content")?.trim() ?? "";
251
+ }
252
+ catch {
253
+ return "";
254
+ }
255
+ };
256
+ const robots = content(query('meta[name="robots"]')).toLowerCase();
257
+ return compact({
258
+ $seo_title: title.slice(0, 160),
259
+ $seo_title_len: title.length,
260
+ $seo_desc_len: content(query('meta[name="description"]')).length,
261
+ $seo_h1_count: count("h1"),
262
+ $seo_has_canonical: Boolean(query('link[rel="canonical"]')),
263
+ $seo_has_og_image: Boolean(query('meta[property="og:image"]')),
264
+ $seo_noindex: robots.includes("noindex"),
265
+ });
266
+ }
267
+ catch {
268
+ return {};
269
+ }
270
+ }
271
+ export class ZenithClient {
272
+ host;
273
+ apiKey;
274
+ fetchImpl;
275
+ storage;
276
+ storagePrefix;
277
+ flushIntervalMs;
278
+ maxBatchSize;
279
+ maxQueueSize;
280
+ retryBaseDelayMs;
281
+ maxRetries;
282
+ now;
283
+ win;
284
+ flightRecorderEnabled;
285
+ webVitalsEnabled;
286
+ seoCapture;
287
+ release;
288
+ tracePropagationTargets;
289
+ ignoreUrls;
290
+ featureFlagsEnabled;
291
+ flagBootstrap;
292
+ flagFetchTimeoutMs;
293
+ maxSessionFlightBytes;
294
+ flags = {};
295
+ flagPayloads = {};
296
+ flagListeners = new Set();
297
+ flagExposureKeys = new Set();
298
+ flagStateVersion = 0;
299
+ activeFlagLoad;
300
+ pendingFlagLoadTimer;
301
+ events = [];
302
+ flightRecords = [];
303
+ flushChain = Promise.resolve();
304
+ flushTimer;
305
+ recorder;
306
+ vitalsTracker;
307
+ pagehideListener;
308
+ anonId;
309
+ userId;
310
+ orgId;
311
+ sessionId;
312
+ sessionStartedAtMs;
313
+ lastActivityAtMs;
314
+ sessionFlightBytes = 0;
315
+ shutdownPromise;
316
+ shuttingDown = false;
317
+ constructor(config) {
318
+ if (!config || typeof config !== "object")
319
+ throw new TypeError("ZenithClient config is required");
320
+ const host = config.host?.trim().replace(/\/+$/, "");
321
+ if (!host)
322
+ throw new TypeError("host must be a non-empty URL");
323
+ const apiKey = config.apiKey?.trim();
324
+ if (!apiKey)
325
+ throw new TypeError("apiKey must be a non-empty string");
326
+ this.host = host;
327
+ this.apiKey = apiKey;
328
+ this.fetchImpl = resolveFetch(config.fetchImpl);
329
+ this.storage = config.storage ?? safeStorage();
330
+ this.storagePrefix = `zenith.${fnv1a(host)}.${fnv1a(apiKey)}`;
331
+ this.flushIntervalMs = Math.max(1, config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS);
332
+ this.maxBatchSize = Math.max(1, Math.min(1_000, config.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE));
333
+ this.maxQueueSize = Math.max(1, config.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE);
334
+ this.retryBaseDelayMs = Math.max(0, config.retryBaseDelayMs ?? 100);
335
+ this.maxRetries = Math.max(0, config.maxRetries ?? 2);
336
+ this.now = config.now ?? (() => Date.now());
337
+ this.win = browserWindow();
338
+ this.flightRecorderEnabled = config.enableFlightRecorder ?? true;
339
+ this.webVitalsEnabled = config.enableWebVitals ?? this.flightRecorderEnabled;
340
+ this.seoCapture = config.seoCapture ?? true;
341
+ this.release = storedIdentifier(config.release);
342
+ this.tracePropagationTargets = config.tracePropagationTargets;
343
+ this.ignoreUrls = config.ignoreUrls;
344
+ this.featureFlagsEnabled = config.enableFeatureFlags ?? false;
345
+ const bootstrapInput = config.flagBootstrap;
346
+ this.flagBootstrap = copyFeatureFlags(bootstrapInput?.flags) ?? copyFeatureFlags(config.flagBootstrap) ?? {};
347
+ this.flagPayloads = copyFeatureFlagPayloads(bootstrapInput?.payloads);
348
+ this.flagFetchTimeoutMs = Math.max(1, config.flagFetchTimeoutMs ?? DEFAULT_FLAG_FETCH_TIMEOUT_MS);
349
+ this.maxSessionFlightBytes = Math.max(1, config.maxSessionFlightBytes ?? DEFAULT_MAX_SESSION_FLIGHT_BYTES);
350
+ this.anonId = this.readOrCreateAnonId();
351
+ this.userId = storedIdentifier(storageGet(this.storage, this.key("user_id")));
352
+ this.orgId = storedIdentifier(storageGet(this.storage, this.key("org_id")));
353
+ const session = this.readOrCreateSession();
354
+ this.sessionId = session.sessionId;
355
+ this.sessionStartedAtMs = session.startedAtMs;
356
+ this.lastActivityAtMs = session.lastActivityAtMs;
357
+ const initialCachedFlags = this.readCachedFlagState();
358
+ this.flags = {
359
+ ...this.flagBootstrap,
360
+ ...(initialCachedFlags?.flags ?? {}),
361
+ };
362
+ this.flagPayloads = {
363
+ ...this.flagPayloads,
364
+ ...(initialCachedFlags?.payloads ?? {}),
365
+ };
366
+ if (!config.deferBrowserInstrumentation) {
367
+ this.attachBrowserInstrumentation();
368
+ }
369
+ if (this.featureFlagsEnabled) {
370
+ this.triggerFlagsLoad();
371
+ }
372
+ }
373
+ capture(event, properties, options = {}) {
374
+ if (this.shuttingDown)
375
+ return;
376
+ const eventName = validateIdentifier(event, "event");
377
+ const now = this.now();
378
+ const sessionId = this.touchSession(now);
379
+ const timestampMs = options.timestamp_ms ?? (options.timestamp ? Date.parse(options.timestamp) : now);
380
+ const explicitProperties = asJsonObject(properties, "properties");
381
+ const mergedProperties = eventName === "$pageview" && this.seoCapture
382
+ ? { ...collectSeoProperties(this.win), ...explicitProperties }
383
+ : explicitProperties;
384
+ const wire = compact({
385
+ event_id: options.event_id ?? generateUuidV7(now),
386
+ event: eventName,
387
+ distinct_id: this.userId ?? this.anonId,
388
+ timestamp_ms: Number.isFinite(timestampMs) ? timestampMs : now,
389
+ org_id: options.org_id ?? this.orgId,
390
+ session_id: options.session_id ?? sessionId,
391
+ trace_id: options.trace_id,
392
+ url_path: normalizeRoutePath(options.url_path ?? currentPath(this.win), this.win),
393
+ referrer: options.referrer ?? currentReferrer(this.win),
394
+ utm_source: options.utm_source ?? currentUtmSource(this.win),
395
+ country: options.country,
396
+ device_type: options.device_type ?? inferDeviceType(this.win),
397
+ properties: mergedProperties,
398
+ release: this.release,
399
+ });
400
+ this.enqueueEvent(wire);
401
+ }
402
+ identify(userId, setProps, setOnceProps) {
403
+ const nextUserId = validateIdentifier(userId, "userId");
404
+ const anonymousDistinctId = this.anonId;
405
+ const transitioningFromAnonymous = this.userId === undefined;
406
+ this.userId = nextUserId;
407
+ storageSet(this.storage, this.key("user_id"), nextUserId);
408
+ const properties = {
409
+ $set: asJsonObject(setProps, "setProps"),
410
+ $set_once: asJsonObject(setOnceProps, "setOnceProps"),
411
+ };
412
+ if (transitioningFromAnonymous) {
413
+ properties.$anon_distinct_id = anonymousDistinctId;
414
+ }
415
+ this.refreshFlagsForIdentity(true);
416
+ this.capture("$identify", properties);
417
+ this.triggerFlagsLoad();
418
+ }
419
+ group(orgId, orgProps) {
420
+ const nextOrgId = validateIdentifier(orgId, "orgId");
421
+ this.orgId = nextOrgId;
422
+ storageSet(this.storage, this.key("org_id"), nextOrgId);
423
+ this.refreshFlagsForIdentity(true);
424
+ this.capture("$group_identify", {
425
+ $group_set: asJsonObject(orgProps, "orgProps"),
426
+ }, { org_id: nextOrgId });
427
+ this.triggerFlagsLoad();
428
+ }
429
+ reset() {
430
+ const previousFlagsKey = this.flagStorageKey();
431
+ const previousPayloadsKey = this.flagPayloadStorageKey();
432
+ this.anonId = generateUuidV7(this.now());
433
+ this.userId = undefined;
434
+ this.orgId = undefined;
435
+ storageSet(this.storage, this.key("anon_id"), this.anonId);
436
+ storageRemove(this.storage, this.key("user_id"));
437
+ storageRemove(this.storage, this.key("org_id"));
438
+ storageRemove(this.storage, previousFlagsKey);
439
+ storageRemove(this.storage, previousPayloadsKey);
440
+ this.flagExposureKeys.clear();
441
+ this.sessionFlightBytes = 0;
442
+ this.rotateSession(this.now());
443
+ this.refreshFlagsForIdentity(false);
444
+ }
445
+ recordFlight(partial) {
446
+ if (this.shuttingDown)
447
+ return;
448
+ if (!partial || !FLIGHT_KINDS.has(partial.kind)) {
449
+ throw new TypeError("flight record kind must be one of ui_action, navigation, network, console, exception, state");
450
+ }
451
+ if (partial.level !== undefined && !FLIGHT_LEVELS.has(partial.level)) {
452
+ throw new TypeError("flight record level must be info, warn, or error");
453
+ }
454
+ const now = this.now();
455
+ const sessionId = this.touchSession(now);
456
+ const payload = asJsonObject(partial.payload, "flight payload");
457
+ const summary = redactSensitiveString(partial.summary ?? `${partial.kind} event`).slice(0, 240);
458
+ const record = compact({
459
+ event_id: partial.event_id ?? generateUuidV7(now),
460
+ session_id: partial.session_id ?? sessionId,
461
+ distinct_id: partial.distinct_id ?? this.userId ?? this.anonId,
462
+ timestamp_ms: partial.timestamp_ms ?? now,
463
+ kind: partial.kind,
464
+ level: partial.level ?? "info",
465
+ route: normalizeRoutePath(partial.route ?? currentPath(this.win), this.win),
466
+ target: partial.target ? redactSensitiveString(partial.target).slice(0, 240) : undefined,
467
+ method: partial.method?.toUpperCase(),
468
+ status_code: Number.isFinite(partial.status_code) ? Math.trunc(partial.status_code) : undefined,
469
+ duration_ms: Number.isFinite(partial.duration_ms) ? Math.max(0, Math.trunc(partial.duration_ms)) : undefined,
470
+ trace_id: partial.trace_id,
471
+ summary,
472
+ payload: this.orgId && payload.org_id === undefined ? { ...payload, org_id: this.orgId } : payload,
473
+ release: partial.release ?? this.release,
474
+ });
475
+ const estimatedBytes = byteLength(JSON.stringify(record));
476
+ if (this.sessionFlightBytes + estimatedBytes > this.maxSessionFlightBytes) {
477
+ // The session budget is cumulative. It is intentionally not replenished by the periodic
478
+ // flush; only session rotation or reset() starts a new budget.
479
+ return;
480
+ }
481
+ this.sessionFlightBytes += estimatedBytes;
482
+ this.enqueueFlight(record);
483
+ }
484
+ loadFlags() {
485
+ const version = this.flagStateVersion;
486
+ if (this.activeFlagLoad?.version === version) {
487
+ return this.activeFlagLoad.promise;
488
+ }
489
+ let promise;
490
+ promise = this.performLoadFlags(version).finally(() => {
491
+ if (this.activeFlagLoad?.promise === promise) {
492
+ this.activeFlagLoad = undefined;
493
+ }
494
+ });
495
+ this.activeFlagLoad = { version, promise };
496
+ return promise;
497
+ }
498
+ getFeatureFlag(key, defaultValue) {
499
+ const fallback = defaultValue ?? false;
500
+ if (typeof key !== "string")
501
+ return fallback;
502
+ const flagKey = key.trim();
503
+ if (!flagKey || byteLength(flagKey) > 256)
504
+ return fallback;
505
+ if (!Object.prototype.hasOwnProperty.call(this.flags, flagKey))
506
+ return fallback;
507
+ const value = this.flags[flagKey];
508
+ this.emitFeatureFlagExposure(flagKey, value);
509
+ return value;
510
+ }
511
+ isFeatureEnabled(key, defaultValue = false) {
512
+ const value = this.getFeatureFlag(key, defaultValue);
513
+ if (typeof value === "boolean")
514
+ return value;
515
+ if (typeof value === "string")
516
+ return value.length > 0;
517
+ return defaultValue;
518
+ }
519
+ getAllFlags() {
520
+ return { ...this.flags };
521
+ }
522
+ getFeatureFlagPayload(key) {
523
+ const payload = this.flagPayloads[key];
524
+ return payload ? { ...payload } : undefined;
525
+ }
526
+ onFlagsChange(listener) {
527
+ if (typeof listener !== "function") {
528
+ throw new TypeError("feature flags listener must be a function");
529
+ }
530
+ this.flagListeners.add(listener);
531
+ let active = true;
532
+ return () => {
533
+ if (!active)
534
+ return;
535
+ active = false;
536
+ this.flagListeners.delete(listener);
537
+ };
538
+ }
539
+ async getActiveSurveys(options = {}) {
540
+ const timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_SURVEY_FETCH_TIMEOUT_MS);
541
+ const controller = typeof AbortController === "undefined" ? undefined : new AbortController();
542
+ let timeout;
543
+ const timeoutPromise = new Promise((_resolve, reject) => {
544
+ timeout = setTimeout(() => {
545
+ try {
546
+ controller?.abort();
547
+ }
548
+ catch {
549
+ }
550
+ reject(new Error("active surveys request timed out"));
551
+ }, timeoutMs);
552
+ });
553
+ try {
554
+ const payload = await Promise.race([
555
+ this.requestActiveSurveys(controller?.signal),
556
+ timeoutPromise,
557
+ ]);
558
+ if (payload === undefined)
559
+ return [];
560
+ const path = normalizeRoutePath(options.currentPath ?? currentPath(this.win), this.win);
561
+ return parseActiveSurveysPayload(payload).filter((survey) => {
562
+ if (!surveyUrlMatches(survey.url_match, path))
563
+ return false;
564
+ if (survey.flag_key && (!this.featureFlagsEnabled || !this.isSurveyFlagEnabled(survey.flag_key)))
565
+ return false;
566
+ return !this.isSurveyInCooldown(survey);
567
+ });
568
+ }
569
+ catch {
570
+ return [];
571
+ }
572
+ finally {
573
+ if (timeout !== undefined)
574
+ clearTimeout(timeout);
575
+ }
576
+ }
577
+ async submitSurveyResponse(surveyId, response, options = {}) {
578
+ const timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_SURVEY_FETCH_TIMEOUT_MS);
579
+ const controller = typeof AbortController === "undefined" ? undefined : new AbortController();
580
+ let timeout;
581
+ try {
582
+ const id = typeof surveyId === "string" ? surveyId.trim() : "";
583
+ if (!id || byteLength(id) > 128)
584
+ return false;
585
+ const distinctId = this.userId ?? this.anonId;
586
+ const body = compact({
587
+ distinct_id: distinctId,
588
+ org_id: this.orgId,
589
+ url_path: normalizeRoutePath(currentPath(this.win), this.win),
590
+ rating: typeof response?.rating === "number" && Number.isFinite(response.rating) ? response.rating : undefined,
591
+ text: typeof response?.text === "string" ? redactSensitiveString(response.text) : undefined,
592
+ choice: typeof response?.choice === "string" ? response.choice : undefined,
593
+ });
594
+ const timeoutPromise = new Promise((_resolve, reject) => {
595
+ timeout = setTimeout(() => {
596
+ try {
597
+ controller?.abort();
598
+ }
599
+ catch {
600
+ }
601
+ reject(new Error("survey response request timed out"));
602
+ }, timeoutMs);
603
+ });
604
+ const result = await Promise.race([
605
+ this.fetchImpl(`${this.host}/surveys/${encodeURIComponent(id)}/respond`, {
606
+ method: "POST",
607
+ headers: {
608
+ Accept: "application/json",
609
+ "Content-Type": "application/json",
610
+ "X-Zenith-Key": this.apiKey,
611
+ },
612
+ body: JSON.stringify(body),
613
+ credentials: "omit",
614
+ signal: controller?.signal,
615
+ }),
616
+ timeoutPromise,
617
+ ]);
618
+ const status = typeof result?.status === "number" ? result.status : 0;
619
+ if (status < 200 || status >= 300)
620
+ return false;
621
+ storageSet(this.storage, this.surveyCooldownStorageKey(id), String(this.now()));
622
+ return true;
623
+ }
624
+ catch {
625
+ return false;
626
+ }
627
+ finally {
628
+ if (timeout !== undefined)
629
+ clearTimeout(timeout);
630
+ }
631
+ }
632
+ flush() {
633
+ const run = this.flushChain.then(() => this.flushOnce());
634
+ this.flushChain = run.catch(() => undefined);
635
+ return run.catch(() => undefined);
636
+ }
637
+ async shutdown() {
638
+ if (this.pendingFlagLoadTimer) {
639
+ clearTimeout(this.pendingFlagLoadTimer);
640
+ this.pendingFlagLoadTimer = undefined;
641
+ }
642
+ if (this.shutdownPromise)
643
+ return this.shutdownPromise;
644
+ // Flush the final LCP/INP/CLS measurements before the shutdown gate can suppress them.
645
+ this.vitalsTracker?.flush();
646
+ this.shuttingDown = true;
647
+ this.shutdownPromise = (async () => {
648
+ if (this.flushTimer)
649
+ clearInterval(this.flushTimer);
650
+ this.flushTimer = undefined;
651
+ if (this.win && this.pagehideListener) {
652
+ this.win.removeEventListener("pagehide", this.pagehideListener);
653
+ }
654
+ this.pagehideListener = undefined;
655
+ this.recorder?.detach();
656
+ this.recorder = undefined;
657
+ this.vitalsTracker?.detach();
658
+ this.vitalsTracker = undefined;
659
+ await this.flush();
660
+ })();
661
+ return this.shutdownPromise;
662
+ }
663
+ restart() {
664
+ if (this.shuttingDown) {
665
+ this.shuttingDown = false;
666
+ this.shutdownPromise = undefined;
667
+ }
668
+ this.attachBrowserInstrumentation();
669
+ if (this.events.length > 0 || this.flightRecords.length > 0)
670
+ this.ensureFlushTimer();
671
+ }
672
+ get identity() {
673
+ return compact({
674
+ anonId: this.anonId,
675
+ userId: this.userId,
676
+ orgId: this.orgId,
677
+ sessionId: this.sessionId,
678
+ });
679
+ }
680
+ get queuedEventCount() {
681
+ return this.events.length;
682
+ }
683
+ get queuedFlightRecordCount() {
684
+ return this.flightRecords.length;
685
+ }
686
+ attachBrowserInstrumentation() {
687
+ if (this.flightRecorderEnabled && this.win && !this.recorder) {
688
+ try {
689
+ this.recorder = attachFlightRecorder({
690
+ window: this.win,
691
+ tracePropagationTargets: this.tracePropagationTargets,
692
+ ignoreUrls: [
693
+ `${this.host}/capture`,
694
+ `${this.host}/batch`,
695
+ `${this.host}/flight`,
696
+ `${this.host}/decide`,
697
+ `${this.host}/surveys`,
698
+ `${this.host}/ai/spans`,
699
+ ...(this.ignoreUrls ?? []),
700
+ ],
701
+ onRecord: (record) => this.recordFlight(record),
702
+ });
703
+ }
704
+ catch {
705
+ this.recorder = undefined;
706
+ }
707
+ }
708
+ if (this.webVitalsEnabled && this.win && !this.vitalsTracker) {
709
+ try {
710
+ this.vitalsTracker = attachWebVitalsTracker({
711
+ window: this.win,
712
+ onSend: (sample) => this.capture("$web_vitals", webVitalsProperties(sample, currentPath(this.win), this.release)),
713
+ });
714
+ }
715
+ catch {
716
+ this.vitalsTracker = undefined;
717
+ }
718
+ }
719
+ if (this.win && typeof this.win.addEventListener === "function" && !this.pagehideListener) {
720
+ this.pagehideListener = () => this.flushOnPagehide();
721
+ this.win.addEventListener("pagehide", this.pagehideListener);
722
+ }
723
+ }
724
+ key(name) {
725
+ return `${this.storagePrefix}.${name}`;
726
+ }
727
+ flagStorageKey(distinctId = this.userId ?? this.anonId, orgId = this.orgId) {
728
+ return `zenith_flags_${this.host}_${distinctId}_${orgId ?? ""}`;
729
+ }
730
+ flagPayloadStorageKey(distinctId = this.userId ?? this.anonId, orgId = this.orgId) {
731
+ return `${this.flagStorageKey(distinctId, orgId)}_payloads`;
732
+ }
733
+ readCachedFlagState(distinctId = this.userId ?? this.anonId, orgId = this.orgId) {
734
+ const raw = storageGet(this.storage, this.flagStorageKey(distinctId, orgId));
735
+ if (!raw)
736
+ return undefined;
737
+ try {
738
+ const parsed = JSON.parse(raw);
739
+ const direct = copyFeatureFlags(parsed);
740
+ const nested = copyFeatureFlags(parsed?.flags);
741
+ const flags = nested ?? direct;
742
+ if (!flags)
743
+ return undefined;
744
+ let payloads = copyFeatureFlagPayloads(parsed?.payloads);
745
+ const rawPayloads = storageGet(this.storage, this.flagPayloadStorageKey(distinctId, orgId));
746
+ if (rawPayloads) {
747
+ try {
748
+ payloads = copyFeatureFlagPayloads(JSON.parse(rawPayloads));
749
+ }
750
+ catch { }
751
+ }
752
+ return { flags, payloads };
753
+ }
754
+ catch {
755
+ return undefined;
756
+ }
757
+ }
758
+ refreshFlagsForIdentity(preserveExisting) {
759
+ this.flagStateVersion += 1;
760
+ const cached = this.readCachedFlagState() ?? { flags: {}, payloads: {} };
761
+ const next = preserveExisting
762
+ ? {
763
+ ...this.flags,
764
+ ...cached.flags,
765
+ }
766
+ : {
767
+ ...cached.flags,
768
+ };
769
+ const nextPayloads = preserveExisting
770
+ ? { ...this.flagPayloads, ...cached.payloads }
771
+ : { ...cached.payloads };
772
+ for (const key of Object.keys(nextPayloads)) {
773
+ if (!(key in next))
774
+ delete nextPayloads[key];
775
+ }
776
+ const changed = !featureFlagsEqual(this.flags, next);
777
+ this.flags = next;
778
+ this.flagPayloads = nextPayloads;
779
+ if (changed)
780
+ this.notifyFlagsChanged();
781
+ }
782
+ triggerFlagsLoad() {
783
+ if (!this.featureFlagsEnabled)
784
+ return;
785
+ // Page boot often performs init + identify + group synchronously. Coalesce those version
786
+ // changes into one trailing-edge /decide request instead of firing three redundant requests.
787
+ if (this.pendingFlagLoadTimer)
788
+ clearTimeout(this.pendingFlagLoadTimer);
789
+ this.pendingFlagLoadTimer = setTimeout(() => {
790
+ this.pendingFlagLoadTimer = undefined;
791
+ void this.loadFlags().catch(() => undefined);
792
+ }, 50);
793
+ const maybeUnref = this.pendingFlagLoadTimer;
794
+ if (typeof maybeUnref.unref === "function")
795
+ maybeUnref.unref();
796
+ }
797
+ notifyFlagsChanged() {
798
+ for (const listener of [...this.flagListeners]) {
799
+ try {
800
+ listener(this.getAllFlags());
801
+ }
802
+ catch {
803
+ }
804
+ }
805
+ }
806
+ emitFeatureFlagExposure(key, value) {
807
+ const sessionId = this.touchSession(this.now());
808
+ const exposureKey = JSON.stringify([sessionId, key, typeof value, String(value)]);
809
+ if (this.flagExposureKeys.has(exposureKey))
810
+ return;
811
+ this.flagExposureKeys.add(exposureKey);
812
+ this.capture("$feature_flag_called", {
813
+ $feature_flag: key,
814
+ $feature_flag_response: value,
815
+ }, { session_id: sessionId });
816
+ }
817
+ recordFeatureFlagsUpdated() {
818
+ if (!this.flightRecorderEnabled)
819
+ return;
820
+ try {
821
+ this.recordFlight({
822
+ kind: "state",
823
+ summary: "feature_flags_updated",
824
+ payload: {
825
+ flags: this.getAllFlags(),
826
+ },
827
+ });
828
+ }
829
+ catch {
830
+ }
831
+ }
832
+ async performLoadFlags(version) {
833
+ const distinctId = this.userId ?? this.anonId;
834
+ const orgId = this.orgId;
835
+ const currentFlags = () => this.getAllFlags();
836
+ const controller = typeof AbortController === "undefined" ? undefined : new AbortController();
837
+ let timeout;
838
+ const timeoutPromise = new Promise((_resolve, reject) => {
839
+ timeout = setTimeout(() => {
840
+ try {
841
+ controller?.abort();
842
+ }
843
+ catch {
844
+ }
845
+ reject(new Error("feature flag request timed out"));
846
+ }, this.flagFetchTimeoutMs);
847
+ });
848
+ try {
849
+ const parsed = await Promise.race([
850
+ this.requestFeatureFlags(distinctId, orgId, controller?.signal),
851
+ timeoutPromise,
852
+ ]);
853
+ if (!parsed)
854
+ return currentFlags();
855
+ if (version !== this.flagStateVersion ||
856
+ distinctId !== (this.userId ?? this.anonId) ||
857
+ orgId !== this.orgId) {
858
+ return currentFlags();
859
+ }
860
+ this.flags = parsed.flags;
861
+ this.flagPayloads = parsed.payloads;
862
+ storageSet(this.storage, this.flagStorageKey(distinctId, orgId), JSON.stringify(parsed.flags));
863
+ storageSet(this.storage, this.flagPayloadStorageKey(distinctId, orgId), JSON.stringify(parsed.payloads));
864
+ this.notifyFlagsChanged();
865
+ this.recordFeatureFlagsUpdated();
866
+ return this.getAllFlags();
867
+ }
868
+ catch {
869
+ return currentFlags();
870
+ }
871
+ finally {
872
+ if (timeout !== undefined)
873
+ clearTimeout(timeout);
874
+ }
875
+ }
876
+ async requestFeatureFlags(distinctId, orgId, signal) {
877
+ const response = await this.fetchImpl(`${this.host}/decide`, {
878
+ method: "POST",
879
+ headers: {
880
+ Accept: "application/json",
881
+ "Content-Type": "application/json",
882
+ "X-Zenith-Key": this.apiKey,
883
+ },
884
+ body: JSON.stringify({
885
+ distinct_id: distinctId,
886
+ org_id: orgId,
887
+ send_exposure: false,
888
+ }),
889
+ credentials: "omit",
890
+ signal,
891
+ });
892
+ const status = typeof response?.status === "number" ? response.status : 0;
893
+ if (status < 200 || status >= 300)
894
+ return undefined;
895
+ let payload;
896
+ try {
897
+ payload = await response.json();
898
+ }
899
+ catch {
900
+ return undefined;
901
+ }
902
+ const rawFlags = payload?.flags;
903
+ const flags = copyFeatureFlags(rawFlags);
904
+ if (!flags)
905
+ return undefined;
906
+ return {
907
+ flags,
908
+ payloads: copyFeatureFlagPayloads(payload?.payloads),
909
+ };
910
+ }
911
+ async requestActiveSurveys(signal) {
912
+ const response = await this.fetchImpl(`${this.host}/surveys`, {
913
+ method: "GET",
914
+ headers: {
915
+ Accept: "application/json",
916
+ "X-Zenith-Key": this.apiKey,
917
+ },
918
+ credentials: "omit",
919
+ signal,
920
+ });
921
+ const status = typeof response?.status === "number" ? response.status : 0;
922
+ if (status < 200 || status >= 300)
923
+ return undefined;
924
+ try {
925
+ return await response.json();
926
+ }
927
+ catch {
928
+ return undefined;
929
+ }
930
+ }
931
+ isSurveyFlagEnabled(flagKey) {
932
+ if (!Object.prototype.hasOwnProperty.call(this.flags, flagKey))
933
+ return false;
934
+ const value = this.flags[flagKey];
935
+ if (typeof value === "boolean")
936
+ return value;
937
+ return typeof value === "string" && value.length > 0;
938
+ }
939
+ surveyCooldownStorageKey(surveyId) {
940
+ const distinctId = this.userId ?? this.anonId;
941
+ return this.key(`survey_cooldown.${fnv1a(`${distinctId}\n${surveyId}`)}`);
942
+ }
943
+ isSurveyInCooldown(survey) {
944
+ if (survey.cooldown_days <= 0)
945
+ return false;
946
+ const raw = storageGet(this.storage, this.surveyCooldownStorageKey(survey.survey_id));
947
+ const answeredAtMs = Number(raw ?? "");
948
+ if (!Number.isFinite(answeredAtMs) || answeredAtMs < 0)
949
+ return false;
950
+ return this.now() - answeredAtMs < survey.cooldown_days * SURVEY_COOLDOWN_DAY_MS;
951
+ }
952
+ readOrCreateAnonId() {
953
+ const existing = storedIdentifier(storageGet(this.storage, this.key("anon_id")));
954
+ if (existing)
955
+ return existing;
956
+ const created = generateUuidV7(this.now());
957
+ storageSet(this.storage, this.key("anon_id"), created);
958
+ return created;
959
+ }
960
+ readOrCreateSession() {
961
+ const now = this.now();
962
+ const existingId = storedIdentifier(storageGet(this.storage, this.key("session_id")));
963
+ const startedAt = Number(storageGet(this.storage, this.key("session_started_at_ms")) ?? "");
964
+ const lastActivity = Number(storageGet(this.storage, this.key("session_last_activity_ms")) ?? "");
965
+ if (existingId &&
966
+ Number.isFinite(startedAt) &&
967
+ Number.isFinite(lastActivity) &&
968
+ now - lastActivity < SESSION_INACTIVITY_MS &&
969
+ now - startedAt < SESSION_MAX_AGE_MS) {
970
+ this.persistSession(existingId, startedAt, now);
971
+ return { sessionId: existingId, startedAtMs: startedAt, lastActivityAtMs: now };
972
+ }
973
+ const sessionId = generateUuidV7(now);
974
+ this.persistSession(sessionId, now, now);
975
+ return { sessionId, startedAtMs: now, lastActivityAtMs: now };
976
+ }
977
+ rotateSession(now) {
978
+ this.sessionFlightBytes = 0;
979
+ this.sessionId = generateUuidV7(now);
980
+ this.sessionStartedAtMs = now;
981
+ this.lastActivityAtMs = now;
982
+ this.persistSession(this.sessionId, now, now);
983
+ }
984
+ touchSession(now) {
985
+ if (now - this.lastActivityAtMs >= SESSION_INACTIVITY_MS ||
986
+ now - this.sessionStartedAtMs >= SESSION_MAX_AGE_MS) {
987
+ this.rotateSession(now);
988
+ return this.sessionId;
989
+ }
990
+ this.lastActivityAtMs = now;
991
+ this.persistSession(this.sessionId, this.sessionStartedAtMs, now);
992
+ return this.sessionId;
993
+ }
994
+ persistSession(sessionId, startedAtMs, lastActivityAtMs) {
995
+ storageSet(this.storage, this.key("session_id"), sessionId);
996
+ storageSet(this.storage, this.key("session_started_at_ms"), String(startedAtMs));
997
+ storageSet(this.storage, this.key("session_last_activity_ms"), String(lastActivityAtMs));
998
+ }
999
+ ensureFlushTimer() {
1000
+ if (this.flushTimer || this.shuttingDown)
1001
+ return;
1002
+ this.flushTimer = setInterval(() => {
1003
+ void this.flush();
1004
+ }, this.flushIntervalMs);
1005
+ const maybeUnref = this.flushTimer;
1006
+ if (typeof maybeUnref.unref === "function")
1007
+ maybeUnref.unref();
1008
+ }
1009
+ enqueueEvent(event) {
1010
+ this.ensureFlushTimer();
1011
+ if (this.events.length >= this.maxQueueSize)
1012
+ this.events.shift();
1013
+ this.events.push(event);
1014
+ if (this.events.length >= this.maxBatchSize)
1015
+ void this.flush();
1016
+ }
1017
+ enqueueFlight(record) {
1018
+ this.ensureFlushTimer();
1019
+ if (this.flightRecords.length >= this.maxQueueSize)
1020
+ this.flightRecords.shift();
1021
+ this.flightRecords.push(record);
1022
+ if (this.flightRecords.length >= this.maxBatchSize)
1023
+ void this.flush();
1024
+ }
1025
+ async flushOnce() {
1026
+ await Promise.all([this.flushEventQueue(), this.flushFlightQueue()]);
1027
+ }
1028
+ async flushEventQueue() {
1029
+ while (this.events.length > 0) {
1030
+ const batch = this.events.slice(0, this.maxBatchSize);
1031
+ try {
1032
+ await this.postWithRetry(`${this.host}/batch`, { batch });
1033
+ this.events.splice(0, batch.length);
1034
+ }
1035
+ catch {
1036
+ break;
1037
+ }
1038
+ }
1039
+ }
1040
+ async flushFlightQueue() {
1041
+ while (this.flightRecords.length > 0) {
1042
+ const records = [];
1043
+ let batchBytes = 0;
1044
+ for (const record of this.flightRecords) {
1045
+ if (records.length >= this.maxBatchSize)
1046
+ break;
1047
+ const recordBytes = byteLength(JSON.stringify(record));
1048
+ if (records.length > 0 && batchBytes + recordBytes > MAX_FLIGHT_FLUSH_BATCH_BYTES)
1049
+ break;
1050
+ records.push(record);
1051
+ batchBytes += recordBytes;
1052
+ }
1053
+ try {
1054
+ await this.postWithRetry(`${this.host}/flight`, { records });
1055
+ this.flightRecords.splice(0, records.length);
1056
+ }
1057
+ catch {
1058
+ break;
1059
+ }
1060
+ }
1061
+ }
1062
+ async postWithRetry(url, body) {
1063
+ let lastError;
1064
+ for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
1065
+ try {
1066
+ const response = await this.fetchImpl(url, {
1067
+ method: "POST",
1068
+ headers: {
1069
+ Authorization: `Bearer ${this.apiKey}`,
1070
+ "Content-Type": "application/json",
1071
+ },
1072
+ body: JSON.stringify(body),
1073
+ });
1074
+ const status = typeof response?.status === "number" ? response.status : 0;
1075
+ if (status >= 200 && status < 300)
1076
+ return;
1077
+ if (status >= 400 && status < 500 && status !== 429) {
1078
+ return;
1079
+ }
1080
+ lastError = new Error(`ingest failed with status ${status}`);
1081
+ }
1082
+ catch (error) {
1083
+ lastError = error;
1084
+ }
1085
+ if (attempt < this.maxRetries) {
1086
+ await sleep(this.retryBaseDelayMs * 2 ** attempt);
1087
+ }
1088
+ }
1089
+ throw lastError instanceof Error ? lastError : new Error("ingest request failed");
1090
+ }
1091
+ flushOnPagehide() {
1092
+ this.vitalsTracker?.flush();
1093
+ if (this.events.length === 0 && this.flightRecords.length === 0)
1094
+ return;
1095
+ const nav = this.win?.navigator ?? (typeof navigator === "undefined" ? undefined : navigator);
1096
+ const sendBeacon = nav?.sendBeacon?.bind(nav);
1097
+ const send = (url, body) => {
1098
+ const payload = JSON.stringify({ api_key: this.apiKey, ...body });
1099
+ if (sendBeacon) {
1100
+ try {
1101
+ if (sendBeacon(url, beaconBody(payload)))
1102
+ return true;
1103
+ }
1104
+ catch {
1105
+ }
1106
+ }
1107
+ try {
1108
+ void this.fetchImpl(url, {
1109
+ method: "POST",
1110
+ headers: { "Content-Type": "text/plain;charset=UTF-8" },
1111
+ body: payload,
1112
+ keepalive: true,
1113
+ credentials: "omit",
1114
+ }).catch(() => undefined);
1115
+ return true;
1116
+ }
1117
+ catch {
1118
+ return false;
1119
+ }
1120
+ };
1121
+ while (this.events.length > 0) {
1122
+ const batch = this.events.slice(0, this.maxBatchSize);
1123
+ if (!send(`${this.host}/batch`, { batch }))
1124
+ break;
1125
+ this.events.splice(0, batch.length);
1126
+ }
1127
+ while (this.flightRecords.length > 0) {
1128
+ const records = this.flightRecords.slice(0, this.maxBatchSize);
1129
+ if (!send(`${this.host}/flight`, { records }))
1130
+ break;
1131
+ this.flightRecords.splice(0, records.length);
1132
+ }
1133
+ }
1134
+ }
1135
+ //# sourceMappingURL=client.js.map