@adhub-so/adhub-nextjs-sdk 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1178 @@
1
+ "use client";
2
+
3
+ // src/index.ts
4
+ import { useEffect, useMemo, useSyncExternalStore } from "react";
5
+
6
+ // src/identity-cookie.ts
7
+ var COOKIE_PREFIX = "adhub_project_anonymous_id_";
8
+ function hashKey(input) {
9
+ let hash = 2166136261;
10
+ for (let index = 0; index < input.length; index += 1) {
11
+ hash ^= input.charCodeAt(index);
12
+ hash = Math.imul(hash, 16777619);
13
+ }
14
+ return (hash >>> 0).toString(36);
15
+ }
16
+ function validAnonymousId(value) {
17
+ return value !== null && value.length >= 8 && value.length <= 255 && !/\s/.test(value);
18
+ }
19
+ function getAdHubAnonymousIdCookieName(projectKey) {
20
+ return `${COOKIE_PREFIX}${hashKey(projectKey.trim())}`;
21
+ }
22
+ function readAdHubAnonymousIdFromCookie(cookieHeader, projectKey) {
23
+ if (!cookieHeader) return null;
24
+ const cookieName = getAdHubAnonymousIdCookieName(projectKey);
25
+ for (const part of cookieHeader.split(";")) {
26
+ const [rawName, ...rawValue] = part.trim().split("=");
27
+ if (rawName !== cookieName) continue;
28
+ try {
29
+ const value = decodeURIComponent(rawValue.join("="));
30
+ return validAnonymousId(value) ? value : null;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+ return null;
36
+ }
37
+
38
+ // src/utils.ts
39
+ var MAX_PARAM_LENGTH = 2048;
40
+ var MAX_ROUTE_LENGTH = 255;
41
+ var MAX_URL_LENGTH = 8192;
42
+ var MAX_UTM_KEYS = 50;
43
+ var MAX_VALUES_PER_PARAM = 10;
44
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
45
+ var EVENT_TYPE_PATTERN = /^[a-z][a-z0-9_.-]{0,127}$/;
46
+ var TIMEZONE_SUFFIX_PATTERN = /(?:z|[+-]\d{2}:\d{2})$/i;
47
+ var MAX_EVENT_ID_LENGTH = 255;
48
+ var MAX_EVENT_PROPERTIES_LENGTH = 32768;
49
+ var MAX_PROFILE_ID_LENGTH = 255;
50
+ var PROFILE_ID_CONTROL_PATTERN = /[\p{Cc}\p{Cf}]/u;
51
+ function nowIso() {
52
+ return (/* @__PURE__ */ new Date()).toISOString();
53
+ }
54
+ function randomId(prefix) {
55
+ const uuid = globalThis.crypto?.randomUUID?.();
56
+ if (uuid) return `${prefix}_${uuid}`;
57
+ const random = Math.random().toString(36).slice(2);
58
+ return `${prefix}_${Date.now().toString(36)}${random}`;
59
+ }
60
+ function truncate(value) {
61
+ return value.slice(0, MAX_PARAM_LENGTH);
62
+ }
63
+ function unique(values) {
64
+ return [...new Set(values.filter(Boolean).map(truncate))];
65
+ }
66
+ function valuesFor(searchParams, wantedKey) {
67
+ const values = [];
68
+ for (const [key, value] of searchParams.entries()) {
69
+ if (key.toLowerCase() === wantedKey) values.push(value);
70
+ }
71
+ return unique(values).slice(0, MAX_VALUES_PER_PARAM);
72
+ }
73
+ function isUuid(value) {
74
+ return UUID_PATTERN.test(value);
75
+ }
76
+ function normalizeProfileId(value) {
77
+ const normalized = value.trim();
78
+ if (!normalized || [...normalized].length > MAX_PROFILE_ID_LENGTH || PROFILE_ID_CONTROL_PATTERN.test(normalized)) {
79
+ return null;
80
+ }
81
+ return normalized;
82
+ }
83
+ function safePageUrl(input) {
84
+ try {
85
+ const url = new URL(input);
86
+ return `${url.origin}${url.pathname}`.slice(0, MAX_URL_LENGTH);
87
+ } catch {
88
+ return "";
89
+ }
90
+ }
91
+ function safeReferrer(input) {
92
+ if (!input) return null;
93
+ const safe = safePageUrl(input);
94
+ return safe || null;
95
+ }
96
+ function captureTouchpoint(location, referrer, capturedAt = nowIso()) {
97
+ const url = new URL(location.href);
98
+ const clickIds = {
99
+ gclid: valuesFor(url.searchParams, "gclid"),
100
+ gbraid: valuesFor(url.searchParams, "gbraid"),
101
+ wbraid: valuesFor(url.searchParams, "wbraid")
102
+ };
103
+ const utm = {};
104
+ for (const key of [...new Set([...url.searchParams.keys()].map((key2) => key2.toLowerCase()))].filter((candidate) => candidate.startsWith("utm_")).slice(0, MAX_UTM_KEYS)) {
105
+ utm[key] = valuesFor(url.searchParams, key);
106
+ }
107
+ return {
108
+ ahRoute: valuesFor(url.searchParams, "ah_route")[0]?.slice(0, MAX_ROUTE_LENGTH) ?? null,
109
+ clickIds,
110
+ utm,
111
+ landingUrl: safePageUrl(url.href),
112
+ referrer: safeReferrer(referrer),
113
+ // Browsers do not know Google's server-side click timestamp. This is the
114
+ // first-party observation time and is the upper bound available to the SDK.
115
+ clickTime: capturedAt
116
+ };
117
+ }
118
+ function toJsonValue(value) {
119
+ if (value === void 0) return void 0;
120
+ try {
121
+ return JSON.parse(JSON.stringify(value));
122
+ } catch {
123
+ return void 0;
124
+ }
125
+ }
126
+ function normalizeEventFields(input) {
127
+ const eventType = input.eventType?.trim().toLowerCase();
128
+ if (!eventType || !EVENT_TYPE_PATTERN.test(eventType) && !isUuid(eventType)) {
129
+ throw new Error(
130
+ "AdHub eventType must be an Event Definition UUID or event key."
131
+ );
132
+ }
133
+ const occurredAtInput = input.occurredAt?.trim() || nowIso();
134
+ if (!TIMEZONE_SUFFIX_PATTERN.test(occurredAtInput)) {
135
+ throw new Error("AdHub occurredAt must include a timezone offset.");
136
+ }
137
+ const occurredAtDate = new Date(occurredAtInput);
138
+ if (Number.isNaN(occurredAtDate.getTime())) {
139
+ throw new Error("AdHub occurredAt must be a valid ISO-8601 timestamp.");
140
+ }
141
+ const result = {
142
+ eventType,
143
+ occurredAt: occurredAtDate.toISOString()
144
+ };
145
+ if (input.eventId !== void 0) {
146
+ const eventId = input.eventId.trim();
147
+ if (!eventId || eventId.length > MAX_EVENT_ID_LENGTH || [...eventId].some((character) => character.charCodeAt(0) < 32 || character === "\x7F")) {
148
+ throw new Error("AdHub eventId must be 1-255 characters without control characters.");
149
+ }
150
+ result.eventId = eventId;
151
+ }
152
+ if (input.value !== void 0) {
153
+ if (!Number.isFinite(input.value) || input.value < 0) {
154
+ throw new Error("AdHub event value must be a finite non-negative number.");
155
+ }
156
+ result.value = input.value;
157
+ }
158
+ if (input.currency !== void 0) {
159
+ const currency = input.currency.trim().toUpperCase();
160
+ if (!/^[A-Z]{3}$/.test(currency)) {
161
+ throw new Error("AdHub event currency must be a three-letter ISO 4217 code.");
162
+ }
163
+ result.currency = currency;
164
+ }
165
+ if (input.properties !== void 0) {
166
+ const properties = toJsonValue(input.properties);
167
+ if (!properties || typeof properties !== "object" || Array.isArray(properties) || JSON.stringify(properties).length > MAX_EVENT_PROPERTIES_LENGTH) {
168
+ throw new Error("AdHub event properties must be a JSON object no larger than 32 KiB.");
169
+ }
170
+ result.properties = properties;
171
+ }
172
+ return result;
173
+ }
174
+ function normalizeBehaviorEventFields(input) {
175
+ const eventName = input.eventName?.trim().toLowerCase();
176
+ if (!eventName || !EVENT_TYPE_PATTERN.test(eventName)) {
177
+ throw new Error(
178
+ "AdHub behavior eventName must start with a letter and use letters, digits, _, . or -."
179
+ );
180
+ }
181
+ const occurredAtInput = input.occurredAt?.trim() || nowIso();
182
+ if (!TIMEZONE_SUFFIX_PATTERN.test(occurredAtInput)) {
183
+ throw new Error("AdHub behavior occurredAt must include a timezone offset.");
184
+ }
185
+ const occurredAtDate = new Date(occurredAtInput);
186
+ if (Number.isNaN(occurredAtDate.getTime())) {
187
+ throw new Error("AdHub behavior occurredAt must be a valid ISO-8601 timestamp.");
188
+ }
189
+ const result = {
190
+ eventName,
191
+ occurredAt: occurredAtDate.toISOString()
192
+ };
193
+ if (input.eventId !== void 0) {
194
+ const eventId = input.eventId.trim();
195
+ if (!eventId || eventId.length > MAX_EVENT_ID_LENGTH || [...eventId].some((character) => character.charCodeAt(0) < 32 || character === "\x7F")) {
196
+ throw new Error("AdHub behavior eventId must be 1-255 characters without control characters.");
197
+ }
198
+ result.eventId = eventId;
199
+ }
200
+ if (input.pageUrl !== void 0) {
201
+ const pageUrl = safePageUrl(input.pageUrl);
202
+ if (pageUrl) result.pageUrl = pageUrl;
203
+ }
204
+ if (input.path !== void 0) {
205
+ const path = input.path.trim().slice(0, 2048);
206
+ if (path) result.path = path;
207
+ }
208
+ if (input.title !== void 0) {
209
+ result.title = input.title.trim().slice(0, 512);
210
+ }
211
+ if (input.referrer !== void 0) {
212
+ result.referrer = input.referrer === null ? null : safeReferrer(input.referrer);
213
+ }
214
+ if (input.properties !== void 0) {
215
+ const properties = toJsonValue(input.properties);
216
+ if (!properties || typeof properties !== "object" || Array.isArray(properties) || JSON.stringify(properties).length > MAX_EVENT_PROPERTIES_LENGTH) {
217
+ throw new Error("AdHub behavior properties must be a JSON object no larger than 32 KiB.");
218
+ }
219
+ result.properties = properties;
220
+ }
221
+ return result;
222
+ }
223
+ function normalizePageviewFields(input = {}) {
224
+ return {
225
+ ...normalizeBehaviorEventFields({ eventName: "pageview", ...input }),
226
+ eventName: "pageview"
227
+ };
228
+ }
229
+ function sanitizeProfile(profile) {
230
+ const profileId = normalizeProfileId(profile.profileId);
231
+ if (!profileId) return null;
232
+ const result = { profileId };
233
+ if (profile.email?.trim()) result.email = profile.email.trim().slice(0, 320);
234
+ if (profile.firstName?.trim()) result.firstName = profile.firstName.trim().slice(0, 200);
235
+ if (profile.lastName?.trim()) result.lastName = profile.lastName.trim().slice(0, 200);
236
+ if (profile.properties) {
237
+ const properties = toJsonValue(profile.properties);
238
+ if (properties && typeof properties === "object" && !Array.isArray(properties) && JSON.stringify(properties).length <= 32768) {
239
+ result.properties = properties;
240
+ }
241
+ }
242
+ return result;
243
+ }
244
+
245
+ // src/storage.ts
246
+ var COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 395;
247
+ var MAX_QUEUE_SIZE = 100;
248
+ function isPendingRequest(value) {
249
+ if (!value || typeof value !== "object") return false;
250
+ const item = value;
251
+ return typeof item.requestId === "string" && (item.path === "/api/v1/saas/sdk/touchpoints" || item.path === "/api/v1/saas/sdk/identify" || item.path === "/api/v1/saas/sdk/behavior-events" || item.path === "/api/v1/saas/sdk/page-engagements" || item.path === "/api/v1/saas/sdk/events") && typeof item.body === "object" && typeof item.attempts === "number" && typeof item.createdAt === "string";
252
+ }
253
+ var BrowserStore = class {
254
+ constructor(projectKey) {
255
+ this.suffix = getAdHubAnonymousIdCookieName(projectKey).slice("adhub_project_anonymous_id_".length);
256
+ }
257
+ get anonymousKey() {
258
+ return `adhub_project_anonymous_id_${this.suffix}`;
259
+ }
260
+ get queueKey() {
261
+ return `adhub_project_sdk_queue_${this.suffix}`;
262
+ }
263
+ get profileKey() {
264
+ return `adhub_project_profile_id_${this.suffix}`;
265
+ }
266
+ get sessionKey() {
267
+ return `adhub_project_session_${this.suffix}`;
268
+ }
269
+ readAnonymousId() {
270
+ const fromCookie = this.readCookie(this.anonymousKey);
271
+ if (this.validAnonymousId(fromCookie)) return fromCookie;
272
+ const fromLocal = this.readLocal(this.anonymousKey);
273
+ return this.validAnonymousId(fromLocal) ? fromLocal : null;
274
+ }
275
+ writeAnonymousId(anonymousId) {
276
+ this.writeLocal(this.anonymousKey, anonymousId);
277
+ try {
278
+ const secure = window.location.protocol === "https:" ? "; Secure" : "";
279
+ document.cookie = `${this.anonymousKey}=${encodeURIComponent(anonymousId)}; Path=/; Max-Age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secure}`;
280
+ } catch {
281
+ }
282
+ }
283
+ readProfileId() {
284
+ const stored = this.readLocal(this.profileKey);
285
+ return stored === null ? null : normalizeProfileId(stored);
286
+ }
287
+ writeProfile(profile) {
288
+ this.writeLocal(this.profileKey, profile.profileId);
289
+ }
290
+ clearProfile() {
291
+ try {
292
+ localStorage.removeItem(this.profileKey);
293
+ } catch {
294
+ }
295
+ }
296
+ readSession(maxAgeMs, now = Date.now()) {
297
+ const raw = this.readLocal(this.sessionKey);
298
+ if (!raw) return null;
299
+ try {
300
+ const value = JSON.parse(raw);
301
+ if (!value || typeof value !== "object") return null;
302
+ const record = value;
303
+ if (typeof record.id !== "string" || typeof record.lastSeenAt !== "number") return null;
304
+ if (!this.validAnonymousId(record.id)) return null;
305
+ if (now - record.lastSeenAt > maxAgeMs) return null;
306
+ return { id: record.id, lastSeenAt: record.lastSeenAt };
307
+ } catch {
308
+ return null;
309
+ }
310
+ }
311
+ writeSession(id, lastSeenAt = Date.now()) {
312
+ this.writeLocal(this.sessionKey, JSON.stringify({ id, lastSeenAt }));
313
+ }
314
+ loadQueue() {
315
+ const raw = this.readLocal(this.queueKey);
316
+ if (!raw) return [];
317
+ try {
318
+ const value = JSON.parse(raw);
319
+ if (!Array.isArray(value)) return [];
320
+ return value.filter(isPendingRequest).slice(-MAX_QUEUE_SIZE);
321
+ } catch {
322
+ return [];
323
+ }
324
+ }
325
+ saveQueue(queue) {
326
+ this.writeLocal(this.queueKey, JSON.stringify(queue.slice(-MAX_QUEUE_SIZE)));
327
+ }
328
+ readCookie(name) {
329
+ try {
330
+ for (const part of document.cookie.split(";")) {
331
+ const [rawName, ...rawValue] = part.trim().split("=");
332
+ if (rawName === name) return decodeURIComponent(rawValue.join("="));
333
+ }
334
+ } catch {
335
+ }
336
+ return null;
337
+ }
338
+ readLocal(key) {
339
+ try {
340
+ return localStorage.getItem(key);
341
+ } catch {
342
+ return null;
343
+ }
344
+ }
345
+ writeLocal(key, value) {
346
+ try {
347
+ localStorage.setItem(key, value);
348
+ } catch {
349
+ }
350
+ }
351
+ validAnonymousId(value) {
352
+ return value !== null && value.length >= 8 && value.length <= 255 && !/\s/.test(value);
353
+ }
354
+ };
355
+
356
+ // src/client.ts
357
+ var DEFAULT_ENDPOINT = "https://api.adhub.so";
358
+ var SDK_NAME = "nextjs";
359
+ var SDK_VERSION = "0.1.0";
360
+ var REQUEST_TIMEOUT_MS = 5e3;
361
+ var RETRY_INTERVAL_MS = 15e3;
362
+ var PAGE_ENGAGEMENT_INTERVAL_MS = 5e3;
363
+ var DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
364
+ var BEHAVIOR_EVENTS_PATH = "/api/v1/saas/sdk/behavior-events";
365
+ var PAGE_ENGAGEMENTS_PATH = "/api/v1/saas/sdk/page-engagements";
366
+ var EMPTY_STATE = {
367
+ initialized: false,
368
+ anonymousId: null,
369
+ sessionId: null,
370
+ profileId: null,
371
+ queuedCount: 0,
372
+ sending: false,
373
+ lastSentAt: null,
374
+ lastError: null,
375
+ lastIngest: null,
376
+ capturedTouchpoint: null
377
+ };
378
+ function parseIngestResult(value) {
379
+ if (!value || typeof value !== "object") return null;
380
+ const result = value;
381
+ const accepted = result.accepted;
382
+ const requestId = result.requestId;
383
+ const stored = result.stored;
384
+ const reason = result.reason;
385
+ const isCollectorResult = typeof accepted === "boolean" && typeof requestId === "string" && typeof stored === "boolean" && (reason === null || reason === void 0 || typeof reason === "string");
386
+ if (isCollectorResult) {
387
+ return {
388
+ accepted,
389
+ requestId,
390
+ stored,
391
+ reason: typeof reason === "string" ? reason : null
392
+ };
393
+ }
394
+ const eventId = result.eventId;
395
+ const externalEventId = result.externalEventId;
396
+ const attributionStatus = result.attributionStatus;
397
+ const attributionReason = result.attributionReason;
398
+ const deliveryStatus = result.deliveryStatus;
399
+ const googleRequestId = result.googleRequestId;
400
+ const isEventTrackResult = typeof eventId === "string" && typeof externalEventId === "string" && typeof attributionStatus === "string";
401
+ if (!isEventTrackResult) return null;
402
+ const eventResult = {
403
+ accepted: true,
404
+ requestId: externalEventId,
405
+ stored: true,
406
+ reason: typeof attributionReason === "string" ? attributionReason : null,
407
+ eventId,
408
+ externalEventId,
409
+ attributionStatus,
410
+ attributionReason: typeof attributionReason === "string" ? attributionReason : null,
411
+ deliveryStatus: typeof deliveryStatus === "string" ? deliveryStatus : null,
412
+ googleRequestId: typeof googleRequestId === "string" ? googleRequestId : null
413
+ };
414
+ if (typeof result.duplicate === "boolean") eventResult.duplicate = result.duplicate;
415
+ if (Array.isArray(result.deliveries)) {
416
+ const deliveries = result.deliveries.filter((item) => {
417
+ if (!item || typeof item !== "object") return false;
418
+ const delivery = item;
419
+ return typeof delivery.bindingId === "string" && typeof delivery.advertisingAccountId === "string" && typeof delivery.conversionActionId === "string" && typeof delivery.status === "string";
420
+ });
421
+ if (deliveries.length) eventResult.deliveries = deliveries;
422
+ }
423
+ return eventResult;
424
+ }
425
+ function browserAvailable() {
426
+ return typeof window !== "undefined" && typeof document !== "undefined";
427
+ }
428
+ function dataAttributePropertyName(attributeName) {
429
+ return attributeName.slice("data-".length).split("-").filter(Boolean).map((part, index) => index === 0 ? part : `${part.charAt(0).toUpperCase()}${part.slice(1)}`).join("");
430
+ }
431
+ function compactElementText(value) {
432
+ const text = value?.replace(/\s+/g, " ").trim().slice(0, 512);
433
+ return text || void 0;
434
+ }
435
+ function normalizeEndpoint(endpoint) {
436
+ const value = endpoint?.trim() || DEFAULT_ENDPOINT;
437
+ if (value.startsWith("/") && !value.startsWith("//")) {
438
+ return value === "/" ? "" : value.replace(/\/$/, "");
439
+ }
440
+ try {
441
+ const parsed = new URL(value);
442
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
443
+ return parsed.toString().replace(/\/$/, "");
444
+ } catch {
445
+ return null;
446
+ }
447
+ }
448
+ function errorMessage(error) {
449
+ return error instanceof Error ? error.message : "Unknown SDK delivery error";
450
+ }
451
+ function cloneState(state) {
452
+ return {
453
+ ...state,
454
+ capturedTouchpoint: state.capturedTouchpoint ? {
455
+ ...state.capturedTouchpoint,
456
+ clickIds: {
457
+ gclid: [...state.capturedTouchpoint.clickIds.gclid],
458
+ gbraid: [...state.capturedTouchpoint.clickIds.gbraid],
459
+ wbraid: [...state.capturedTouchpoint.clickIds.wbraid]
460
+ },
461
+ utm: Object.fromEntries(
462
+ Object.entries(state.capturedTouchpoint.utm).map(([key, values]) => [key, [...values]])
463
+ )
464
+ } : null
465
+ };
466
+ }
467
+ var AdHubBrowserClient = class {
468
+ constructor() {
469
+ this.state = cloneState(EMPTY_STATE);
470
+ this.listeners = /* @__PURE__ */ new Set();
471
+ this.store = null;
472
+ this.queue = [];
473
+ this.endpoint = DEFAULT_ENDPOINT;
474
+ this.projectKey = "";
475
+ this.debug = false;
476
+ this.flushPromise = null;
477
+ this.retryTimer = null;
478
+ this.pageEngagementTimer = null;
479
+ this.pageDebounceTimer = null;
480
+ this.activePageVisit = null;
481
+ this.lifecycleInstalled = false;
482
+ this.pageviewTrackingInstalled = false;
483
+ this.behaviorTrackingInstalled = false;
484
+ this.sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS;
485
+ this.autoFlush = true;
486
+ this.autoPageview = true;
487
+ this.autoPageEngagement = true;
488
+ this.autoTrackOutgoingLinks = true;
489
+ this.autoTrackDataAttributes = true;
490
+ this.trackHashChanges = false;
491
+ this.lastPageSignature = "";
492
+ this.originalPushState = null;
493
+ this.originalReplaceState = null;
494
+ this.patchedPushState = null;
495
+ this.patchedReplaceState = null;
496
+ this.onOnline = () => {
497
+ if (this.autoFlush) void this.flush();
498
+ };
499
+ this.onPageHide = () => {
500
+ this.pausePageVisit();
501
+ if (this.autoFlush) void this.flush();
502
+ };
503
+ this.onVisibilityChange = () => {
504
+ if (document.visibilityState === "hidden") {
505
+ this.pausePageVisit();
506
+ if (this.autoFlush) void this.flush();
507
+ return;
508
+ }
509
+ this.resumePageVisit();
510
+ };
511
+ this.onLocationChange = () => {
512
+ if (this.pageDebounceTimer) clearTimeout(this.pageDebounceTimer);
513
+ this.pageDebounceTimer = setTimeout(() => this.page(), 50);
514
+ };
515
+ this.onPopState = () => {
516
+ window.dispatchEvent(new Event("locationchange"));
517
+ };
518
+ this.onHashChange = () => {
519
+ window.dispatchEvent(new Event("locationchange"));
520
+ };
521
+ this.onDocumentClick = (event) => {
522
+ if (!(event.target instanceof Element)) return;
523
+ if (this.autoTrackDataAttributes) this.trackDataAttributeClick(event.target);
524
+ if (this.autoTrackOutgoingLinks) this.trackOutgoingLinkClick(event.target);
525
+ };
526
+ }
527
+ init(options) {
528
+ try {
529
+ const projectKey = options.projectKey?.trim();
530
+ const endpoint = normalizeEndpoint(options.endpoint);
531
+ if (!projectKey || !isUuid(projectKey)) {
532
+ this.updateState({ lastError: "AdHub init requires projectKey to be a UUID." });
533
+ return;
534
+ }
535
+ if (!endpoint) {
536
+ this.updateState({
537
+ lastError: "AdHub init requires an HTTP endpoint or same-origin path."
538
+ });
539
+ return;
540
+ }
541
+ if (!browserAvailable()) return;
542
+ if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) return;
543
+ this.projectKey = projectKey;
544
+ this.endpoint = endpoint;
545
+ this.debug = options.debug ?? false;
546
+ this.autoFlush = options.autoFlush ?? true;
547
+ this.autoPageview = options.autoPageview ?? true;
548
+ this.autoPageEngagement = options.autoPageEngagement ?? true;
549
+ this.autoTrackOutgoingLinks = options.autoTrackOutgoingLinks ?? true;
550
+ this.autoTrackDataAttributes = options.autoTrackDataAttributes ?? true;
551
+ this.trackHashChanges = options.trackHashChanges ?? false;
552
+ this.store = new BrowserStore(projectKey);
553
+ this.queue = this.store.loadQueue();
554
+ this.sessionTimeoutMs = Number.isFinite(options.sessionTimeoutMinutes) ? Math.max(1, Math.min(24 * 60, options.sessionTimeoutMinutes ?? 30)) * 60 * 1e3 : DEFAULT_SESSION_TIMEOUT_MS;
555
+ const anonymousId = this.store.readAnonymousId() ?? randomId("anon");
556
+ this.store.writeAnonymousId(anonymousId);
557
+ const session = this.currentSession();
558
+ const touchpoint = captureTouchpoint(window.location, document.referrer);
559
+ this.state = {
560
+ initialized: true,
561
+ anonymousId,
562
+ sessionId: session,
563
+ profileId: this.store.readProfileId(),
564
+ queuedCount: this.queue.length,
565
+ sending: false,
566
+ lastSentAt: null,
567
+ lastError: null,
568
+ lastIngest: null,
569
+ capturedTouchpoint: touchpoint
570
+ };
571
+ this.emit();
572
+ let timezone = null;
573
+ try {
574
+ timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || null;
575
+ } catch {
576
+ }
577
+ const data = {
578
+ ...touchpoint,
579
+ sessionId: session,
580
+ locale: navigator.language || null,
581
+ timezone
582
+ };
583
+ this.enqueue("/api/v1/saas/sdk/touchpoints", "touchpoint.capture", data);
584
+ if (this.autoPageview) this.page();
585
+ this.installLifecycle();
586
+ if (this.autoPageview) this.installPageviewTracking();
587
+ if (this.autoTrackOutgoingLinks || this.autoTrackDataAttributes) {
588
+ this.installBehaviorTracking();
589
+ }
590
+ this.scheduleFlush();
591
+ } catch (error) {
592
+ this.reportError(error);
593
+ }
594
+ }
595
+ identify(input) {
596
+ try {
597
+ if (!this.state.initialized || !this.store) {
598
+ this.updateState({ lastError: "Call init() before identify()." });
599
+ return;
600
+ }
601
+ const profile = sanitizeProfile(input);
602
+ if (!profile) {
603
+ this.updateState({
604
+ lastError: "identify() requires profileId to be 1-255 characters without control characters."
605
+ });
606
+ return;
607
+ }
608
+ const dataProfile = { profileId: profile.profileId };
609
+ if (profile.email !== void 0) dataProfile.email = profile.email;
610
+ if (profile.firstName !== void 0) dataProfile.firstName = profile.firstName;
611
+ if (profile.lastName !== void 0) dataProfile.lastName = profile.lastName;
612
+ if (profile.properties !== void 0) {
613
+ const properties = toJsonValue(profile.properties);
614
+ if (properties !== void 0) dataProfile.properties = properties;
615
+ }
616
+ const data = {
617
+ profile: dataProfile,
618
+ identifiedAt: nowIso(),
619
+ pageUrl: safePageUrl(window.location.href)
620
+ };
621
+ this.store.writeProfile(profile);
622
+ this.updateState({ profileId: profile.profileId, lastError: null });
623
+ this.enqueue("/api/v1/saas/sdk/identify", "profile.identify", data);
624
+ this.scheduleFlush();
625
+ } catch (error) {
626
+ this.reportError(error);
627
+ }
628
+ }
629
+ page(input = {}) {
630
+ try {
631
+ if (!this.state.initialized || !this.store) {
632
+ this.updateState({ lastError: "Call init() before page()." });
633
+ return;
634
+ }
635
+ const normalized = normalizePageviewFields({
636
+ ...this.currentPageFields(),
637
+ ...input
638
+ });
639
+ const signature = [
640
+ normalized.pageUrl,
641
+ normalized.path,
642
+ normalized.title,
643
+ normalized.eventId
644
+ ].join("|");
645
+ if (!input.eventId && signature === this.lastPageSignature) return;
646
+ this.lastPageSignature = signature;
647
+ this.finishPageVisit();
648
+ const pageViewId = normalized.eventId ?? randomId("page");
649
+ const sessionId = this.enqueueBehaviorEvent({ ...normalized, eventId: pageViewId });
650
+ if (this.autoPageEngagement) {
651
+ this.startPageVisit(normalized, pageViewId, sessionId);
652
+ }
653
+ } catch (error) {
654
+ this.reportError(error);
655
+ }
656
+ }
657
+ behavior(input) {
658
+ try {
659
+ if (!this.state.initialized || !this.store) {
660
+ this.updateState({ lastError: "Call init() before behavior()." });
661
+ return;
662
+ }
663
+ const normalized = normalizeBehaviorEventFields({
664
+ ...this.currentPageFields(),
665
+ ...input
666
+ });
667
+ this.enqueueBehaviorEvent(normalized);
668
+ } catch (error) {
669
+ this.reportError(error);
670
+ }
671
+ }
672
+ track(input) {
673
+ try {
674
+ if (!this.state.initialized || !this.store) {
675
+ this.updateState({ lastError: "Call init() before track()." });
676
+ return;
677
+ }
678
+ const profileId = this.state.profileId;
679
+ if (!profileId) {
680
+ this.updateState({ lastError: "Call identify() before track()." });
681
+ return;
682
+ }
683
+ const normalized = normalizeEventFields(input);
684
+ const data = {
685
+ profileId,
686
+ eventType: normalized.eventType,
687
+ occurredAt: normalized.occurredAt
688
+ };
689
+ if (normalized.eventId !== void 0) data.eventId = normalized.eventId;
690
+ if (normalized.value !== void 0) data.value = normalized.value;
691
+ if (normalized.currency !== void 0) data.currency = normalized.currency;
692
+ if (normalized.properties !== void 0) data.properties = normalized.properties;
693
+ this.updateState({ lastError: null });
694
+ this.enqueue("/api/v1/saas/sdk/events", "event.track", data);
695
+ this.scheduleFlush();
696
+ } catch (error) {
697
+ this.reportError(error);
698
+ }
699
+ }
700
+ reset() {
701
+ try {
702
+ if (!this.state.initialized || !this.store) return;
703
+ this.finishPageVisit();
704
+ const anonymousId = randomId("anon");
705
+ this.store.clearProfile();
706
+ this.store.writeAnonymousId(anonymousId);
707
+ const sessionId = randomId("sess");
708
+ this.store.writeSession(sessionId);
709
+ this.updateState({ anonymousId, sessionId, profileId: null, lastError: null });
710
+ this.lastPageSignature = "";
711
+ if (this.autoPageview) this.page();
712
+ } catch (error) {
713
+ this.reportError(error);
714
+ }
715
+ }
716
+ flush() {
717
+ if (this.flushPromise) return this.flushPromise;
718
+ this.flushPromise = this.performFlush().catch((error) => {
719
+ this.reportError(error);
720
+ return { sent: 0, failed: this.queue.length, remaining: this.queue.length };
721
+ }).finally(() => {
722
+ this.flushPromise = null;
723
+ });
724
+ return this.flushPromise;
725
+ }
726
+ getState() {
727
+ return cloneState(this.state);
728
+ }
729
+ subscribe(listener) {
730
+ this.listeners.add(listener);
731
+ try {
732
+ listener(this.getState());
733
+ } catch {
734
+ }
735
+ return () => this.listeners.delete(listener);
736
+ }
737
+ destroy() {
738
+ this.finishPageVisit();
739
+ if (browserAvailable() && this.lifecycleInstalled) {
740
+ window.removeEventListener("online", this.onOnline);
741
+ window.removeEventListener("pagehide", this.onPageHide);
742
+ document.removeEventListener("visibilitychange", this.onVisibilityChange);
743
+ this.lifecycleInstalled = false;
744
+ }
745
+ if (browserAvailable() && this.pageviewTrackingInstalled) {
746
+ window.removeEventListener("locationchange", this.onLocationChange);
747
+ window.removeEventListener("popstate", this.onPopState);
748
+ window.removeEventListener("hashchange", this.onHashChange);
749
+ if (this.patchedPushState && history.pushState === this.patchedPushState && this.originalPushState) {
750
+ history.pushState = this.originalPushState;
751
+ }
752
+ if (this.patchedReplaceState && history.replaceState === this.patchedReplaceState && this.originalReplaceState) {
753
+ history.replaceState = this.originalReplaceState;
754
+ }
755
+ this.pageviewTrackingInstalled = false;
756
+ this.originalPushState = null;
757
+ this.originalReplaceState = null;
758
+ this.patchedPushState = null;
759
+ this.patchedReplaceState = null;
760
+ }
761
+ if (browserAvailable() && this.behaviorTrackingInstalled) {
762
+ document.removeEventListener("click", this.onDocumentClick, true);
763
+ this.behaviorTrackingInstalled = false;
764
+ }
765
+ if (this.pageDebounceTimer) {
766
+ clearTimeout(this.pageDebounceTimer);
767
+ this.pageDebounceTimer = null;
768
+ }
769
+ if (this.retryTimer) {
770
+ clearInterval(this.retryTimer);
771
+ this.retryTimer = null;
772
+ }
773
+ if (this.pageEngagementTimer) {
774
+ clearInterval(this.pageEngagementTimer);
775
+ this.pageEngagementTimer = null;
776
+ }
777
+ this.listeners.clear();
778
+ }
779
+ enqueue(path, type, data) {
780
+ if (!this.state.anonymousId || !this.store) return;
781
+ const requestId = randomId("req");
782
+ const body = {
783
+ schemaVersion: "1.0",
784
+ type,
785
+ requestId,
786
+ sentAt: nowIso(),
787
+ projectKey: this.projectKey,
788
+ anonymousId: this.state.anonymousId,
789
+ data
790
+ };
791
+ this.queue.push({ requestId, path, body, attempts: 0, createdAt: body.sentAt });
792
+ this.queue = this.queue.slice(-100);
793
+ this.persistQueue();
794
+ }
795
+ currentSession() {
796
+ if (!this.store) return randomId("sess");
797
+ const existing = this.store.readSession(this.sessionTimeoutMs);
798
+ const sessionId = existing?.id ?? randomId("sess");
799
+ this.store.writeSession(sessionId);
800
+ return sessionId;
801
+ }
802
+ currentPageFields() {
803
+ return {
804
+ pageUrl: safePageUrl(window.location.href),
805
+ path: window.location.pathname || "/",
806
+ title: document.title,
807
+ referrer: document.referrer || null
808
+ };
809
+ }
810
+ enqueueBehaviorEvent(normalized) {
811
+ const sessionId = this.currentSession();
812
+ if (sessionId !== this.state.sessionId) this.updateState({ sessionId });
813
+ const data = {
814
+ eventName: normalized.eventName,
815
+ occurredAt: normalized.occurredAt,
816
+ sessionId
817
+ };
818
+ if (this.state.profileId) data.profileId = this.state.profileId;
819
+ if (normalized.eventId !== void 0) data.eventId = normalized.eventId;
820
+ if (normalized.pageUrl !== void 0) data.pageUrl = normalized.pageUrl;
821
+ if (normalized.path !== void 0) data.path = normalized.path;
822
+ if (normalized.title !== void 0) data.title = normalized.title;
823
+ if (normalized.referrer !== void 0) data.referrer = normalized.referrer;
824
+ if (normalized.properties !== void 0) data.properties = normalized.properties;
825
+ this.updateState({ lastError: null });
826
+ this.enqueue(BEHAVIOR_EVENTS_PATH, "behavior.event", data);
827
+ this.scheduleFlush();
828
+ return sessionId;
829
+ }
830
+ startPageVisit(normalized, pageViewId, sessionId) {
831
+ const now = Date.now();
832
+ this.activePageVisit = {
833
+ pageViewId,
834
+ sessionId,
835
+ startedAtMs: now,
836
+ activeSinceMs: document.visibilityState === "hidden" ? null : now,
837
+ activeDurationMs: 0,
838
+ lastQueuedDurationSeconds: 0,
839
+ pageUrl: normalized.pageUrl ?? safePageUrl(window.location.href),
840
+ path: normalized.path ?? (window.location.pathname || "/"),
841
+ ...normalized.title !== void 0 ? { title: normalized.title } : {},
842
+ ...normalized.referrer !== void 0 ? { referrer: normalized.referrer } : {}
843
+ };
844
+ }
845
+ checkpointPageVisit(now = Date.now()) {
846
+ const visit = this.activePageVisit;
847
+ if (!visit || visit.activeSinceMs === null) return;
848
+ visit.activeDurationMs += Math.max(0, now - visit.activeSinceMs);
849
+ visit.activeSinceMs = now;
850
+ this.store?.writeSession(visit.sessionId, now);
851
+ }
852
+ queuePageEngagement() {
853
+ const visit = this.activePageVisit;
854
+ if (!visit) return;
855
+ const durationSeconds = Math.floor(visit.activeDurationMs / 1e3);
856
+ if (durationSeconds < 1 || durationSeconds <= visit.lastQueuedDurationSeconds) return;
857
+ const data = {
858
+ pageViewId: visit.pageViewId,
859
+ sessionId: visit.sessionId,
860
+ startedAt: new Date(visit.startedAtMs).toISOString(),
861
+ occurredAt: nowIso(),
862
+ durationSeconds,
863
+ pageUrl: visit.pageUrl,
864
+ path: visit.path
865
+ };
866
+ if (this.state.profileId) data.profileId = this.state.profileId;
867
+ if (visit.title !== void 0) data.title = visit.title;
868
+ if (visit.referrer !== void 0) data.referrer = visit.referrer;
869
+ this.queue = this.queue.filter((item) => {
870
+ if (item.path !== PAGE_ENGAGEMENTS_PATH) return true;
871
+ const body = item.body;
872
+ return body.data?.pageViewId !== visit.pageViewId;
873
+ });
874
+ visit.lastQueuedDurationSeconds = durationSeconds;
875
+ this.enqueue(PAGE_ENGAGEMENTS_PATH, "page.engagement", data);
876
+ this.scheduleFlush();
877
+ }
878
+ pausePageVisit() {
879
+ const visit = this.activePageVisit;
880
+ if (!visit || visit.activeSinceMs === null) return;
881
+ this.checkpointPageVisit();
882
+ visit.activeSinceMs = null;
883
+ this.queuePageEngagement();
884
+ }
885
+ resumePageVisit() {
886
+ const visit = this.activePageVisit;
887
+ if (!visit || visit.activeSinceMs !== null) return;
888
+ const session = this.store?.readSession(this.sessionTimeoutMs);
889
+ if (!session || session.id !== visit.sessionId) {
890
+ this.activePageVisit = null;
891
+ this.lastPageSignature = "";
892
+ if (this.autoPageview) this.page();
893
+ return;
894
+ }
895
+ visit.activeSinceMs = Date.now();
896
+ }
897
+ finishPageVisit() {
898
+ if (!this.activePageVisit) return;
899
+ this.checkpointPageVisit();
900
+ this.queuePageEngagement();
901
+ this.activePageVisit = null;
902
+ }
903
+ async performFlush() {
904
+ if (!this.state.initialized || !this.queue.length || typeof fetch !== "function") {
905
+ return { sent: 0, failed: 0, remaining: this.queue.length };
906
+ }
907
+ this.updateState({ sending: true });
908
+ let sent = 0;
909
+ let failed = 0;
910
+ while (this.queue.length) {
911
+ const item = this.queue[0];
912
+ if (!item) break;
913
+ const controller = new AbortController();
914
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
915
+ try {
916
+ const response = await fetch(`${this.endpoint}${item.path}`, {
917
+ method: "POST",
918
+ headers: {
919
+ "Content-Type": "application/json",
920
+ "Idempotency-Key": item.requestId,
921
+ "X-AdHub-Project-Key": this.projectKey,
922
+ "X-AdHub-SDK": SDK_NAME,
923
+ "X-AdHub-SDK-Version": SDK_VERSION
924
+ },
925
+ body: JSON.stringify(item.body),
926
+ keepalive: true,
927
+ credentials: "omit",
928
+ signal: controller.signal
929
+ });
930
+ if (response.ok) {
931
+ let ingestResult = null;
932
+ try {
933
+ ingestResult = parseIngestResult(await response.json());
934
+ } catch {
935
+ }
936
+ this.removeRequest(item.requestId);
937
+ sent += 1;
938
+ this.updateState({
939
+ lastSentAt: nowIso(),
940
+ lastError: null,
941
+ ...ingestResult ? { lastIngest: ingestResult } : {}
942
+ });
943
+ continue;
944
+ }
945
+ failed += 1;
946
+ const message = `AdHub endpoint returned HTTP ${response.status}.`;
947
+ const retryable = response.status === 408 || response.status === 429 || response.status >= 500;
948
+ if (retryable) {
949
+ item.attempts += 1;
950
+ } else {
951
+ this.removeRequest(item.requestId);
952
+ }
953
+ this.updateState({ lastError: message });
954
+ this.log(message);
955
+ if (retryable) break;
956
+ } catch (error) {
957
+ failed += 1;
958
+ item.attempts += 1;
959
+ this.updateState({ lastError: errorMessage(error) });
960
+ this.log(errorMessage(error));
961
+ break;
962
+ } finally {
963
+ clearTimeout(timeout);
964
+ this.persistQueue();
965
+ }
966
+ }
967
+ this.updateState({ sending: false, queuedCount: this.queue.length });
968
+ return { sent, failed, remaining: this.queue.length };
969
+ }
970
+ removeRequest(requestId) {
971
+ this.queue = this.queue.filter((item) => item.requestId !== requestId);
972
+ }
973
+ persistQueue() {
974
+ this.store?.saveQueue(this.queue);
975
+ this.updateState({ queuedCount: this.queue.length });
976
+ }
977
+ installLifecycle() {
978
+ if (this.lifecycleInstalled) return;
979
+ window.addEventListener("online", this.onOnline);
980
+ window.addEventListener("pagehide", this.onPageHide);
981
+ document.addEventListener("visibilitychange", this.onVisibilityChange);
982
+ if (this.autoFlush) {
983
+ this.retryTimer = setInterval(() => {
984
+ if (this.queue.length) void this.flush();
985
+ }, RETRY_INTERVAL_MS);
986
+ }
987
+ if (this.autoPageEngagement) {
988
+ this.pageEngagementTimer = setInterval(() => {
989
+ if (document.visibilityState === "hidden") return;
990
+ this.checkpointPageVisit();
991
+ this.queuePageEngagement();
992
+ }, PAGE_ENGAGEMENT_INTERVAL_MS);
993
+ }
994
+ this.lifecycleInstalled = true;
995
+ }
996
+ installPageviewTracking() {
997
+ if (this.pageviewTrackingInstalled) return;
998
+ this.originalPushState = history.pushState;
999
+ this.originalReplaceState = history.replaceState;
1000
+ const dispatchLocationChange = () => {
1001
+ window.dispatchEvent(new Event("locationchange"));
1002
+ };
1003
+ const originalPushState = this.originalPushState;
1004
+ const originalReplaceState = this.originalReplaceState;
1005
+ this.patchedPushState = function pushState(...args) {
1006
+ const result = originalPushState.apply(this, args);
1007
+ dispatchLocationChange();
1008
+ return result;
1009
+ };
1010
+ this.patchedReplaceState = function replaceState(...args) {
1011
+ const result = originalReplaceState.apply(this, args);
1012
+ dispatchLocationChange();
1013
+ return result;
1014
+ };
1015
+ history.pushState = this.patchedPushState;
1016
+ history.replaceState = this.patchedReplaceState;
1017
+ window.addEventListener("locationchange", this.onLocationChange);
1018
+ window.addEventListener("popstate", this.onPopState);
1019
+ if (this.trackHashChanges) window.addEventListener("hashchange", this.onHashChange);
1020
+ this.pageviewTrackingInstalled = true;
1021
+ }
1022
+ installBehaviorTracking() {
1023
+ if (this.behaviorTrackingInstalled) return;
1024
+ document.addEventListener("click", this.onDocumentClick, true);
1025
+ this.behaviorTrackingInstalled = true;
1026
+ }
1027
+ trackDataAttributeClick(target) {
1028
+ const element = target.closest("[data-adhub-track], [data-track]");
1029
+ if (!element) return;
1030
+ const eventName = element.getAttribute("data-adhub-track") ?? element.getAttribute("data-track");
1031
+ if (!eventName) return;
1032
+ const properties = {};
1033
+ for (const attribute of Array.from(element.attributes)) {
1034
+ if (!attribute.name.startsWith("data-") || attribute.name === "data-adhub-track" || attribute.name === "data-track") {
1035
+ continue;
1036
+ }
1037
+ const propertyName = dataAttributePropertyName(attribute.name);
1038
+ if (propertyName) properties[propertyName] = attribute.value;
1039
+ }
1040
+ this.behavior({
1041
+ eventName,
1042
+ ...Object.keys(properties).length ? { properties } : {}
1043
+ });
1044
+ }
1045
+ trackOutgoingLinkClick(target) {
1046
+ const link = target.closest("a[href]");
1047
+ const href = link?.getAttribute("href");
1048
+ if (!link || !href) return;
1049
+ try {
1050
+ const url = new URL(href, window.location.href);
1051
+ if (!["http:", "https:"].includes(url.protocol)) return;
1052
+ if (url.hostname === window.location.hostname) return;
1053
+ const properties = {
1054
+ href: safePageUrl(url.href)
1055
+ };
1056
+ const text = compactElementText(
1057
+ link.innerText || link.textContent || link.getAttribute("title") || target.getAttribute("alt") || target.getAttribute("title")
1058
+ );
1059
+ if (text) properties.text = text;
1060
+ if (link.target) properties.target = link.target;
1061
+ this.behavior({
1062
+ eventName: "link_out",
1063
+ properties
1064
+ });
1065
+ } catch {
1066
+ }
1067
+ }
1068
+ scheduleFlush() {
1069
+ if (this.autoFlush) queueMicrotask(() => void this.flush());
1070
+ }
1071
+ updateState(patch) {
1072
+ this.state = { ...this.state, ...patch };
1073
+ this.emit();
1074
+ }
1075
+ emit() {
1076
+ const state = this.getState();
1077
+ for (const listener of this.listeners) {
1078
+ try {
1079
+ listener(state);
1080
+ } catch {
1081
+ }
1082
+ }
1083
+ }
1084
+ reportError(error) {
1085
+ const message = errorMessage(error);
1086
+ this.updateState({ lastError: message, sending: false });
1087
+ this.log(message);
1088
+ }
1089
+ log(message) {
1090
+ if (this.debug && typeof console !== "undefined") console.warn(`[AdHub SDK] ${message}`);
1091
+ }
1092
+ };
1093
+ function createAdHubClient() {
1094
+ return new AdHubBrowserClient();
1095
+ }
1096
+
1097
+ // src/index.ts
1098
+ var adhub = createAdHubClient();
1099
+ var serverSnapshot = adhub.getState();
1100
+ var currentSnapshot = serverSnapshot;
1101
+ function refreshSnapshot() {
1102
+ currentSnapshot = adhub.getState();
1103
+ }
1104
+ function subscribe(listener) {
1105
+ return adhub.subscribe((state) => {
1106
+ currentSnapshot = state;
1107
+ listener();
1108
+ });
1109
+ }
1110
+ var methods = {
1111
+ identify(profile) {
1112
+ adhub.identify(profile);
1113
+ refreshSnapshot();
1114
+ },
1115
+ page(input) {
1116
+ adhub.page(input);
1117
+ refreshSnapshot();
1118
+ },
1119
+ behavior(event) {
1120
+ adhub.behavior(event);
1121
+ refreshSnapshot();
1122
+ },
1123
+ track(event) {
1124
+ adhub.track(event);
1125
+ refreshSnapshot();
1126
+ },
1127
+ reset() {
1128
+ adhub.reset();
1129
+ refreshSnapshot();
1130
+ },
1131
+ async flush() {
1132
+ const result = await adhub.flush();
1133
+ refreshSnapshot();
1134
+ return result;
1135
+ },
1136
+ getState() {
1137
+ return adhub.getState();
1138
+ }
1139
+ };
1140
+ function initAdHub(options) {
1141
+ adhub.init(options);
1142
+ refreshSnapshot();
1143
+ }
1144
+ function AdHubComponent({ profile, profileId, ...options }) {
1145
+ const identifiedProfile = profile !== void 0 ? profile : profileId !== void 0 ? profileId ? { profileId } : null : void 0;
1146
+ const optionsKey = JSON.stringify(options);
1147
+ const profileKey = JSON.stringify(identifiedProfile);
1148
+ useEffect(() => {
1149
+ initAdHub(options);
1150
+ }, [optionsKey]);
1151
+ useEffect(() => {
1152
+ const currentProfileId = methods.getState().profileId;
1153
+ if (identifiedProfile === void 0) return;
1154
+ if (!identifiedProfile) {
1155
+ if (currentProfileId) methods.reset();
1156
+ return;
1157
+ }
1158
+ if (currentProfileId && currentProfileId !== identifiedProfile.profileId) methods.reset();
1159
+ if (methods.getState().profileId !== identifiedProfile.profileId) methods.identify(identifiedProfile);
1160
+ }, [profileKey]);
1161
+ return null;
1162
+ }
1163
+ function useAdHub() {
1164
+ const state = useSyncExternalStore(
1165
+ subscribe,
1166
+ () => currentSnapshot,
1167
+ () => serverSnapshot
1168
+ );
1169
+ return useMemo(() => ({ state, ...methods }), [state]);
1170
+ }
1171
+ export {
1172
+ AdHubComponent,
1173
+ getAdHubAnonymousIdCookieName,
1174
+ initAdHub,
1175
+ readAdHubAnonymousIdFromCookie,
1176
+ useAdHub
1177
+ };
1178
+ //# sourceMappingURL=index.js.map