@adhub-so/adhub-nextjs-sdk 0.2.0 → 0.4.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/dist/index.cjs CHANGED
@@ -40,6 +40,7 @@ function hashKey(input) {
40
40
  }
41
41
  return (hash >>> 0).toString(36);
42
42
  }
43
+ var ANONYMOUS_ID_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 395;
43
44
  function validAnonymousId(value) {
44
45
  return value !== null && value.length >= 8 && value.length <= 255 && !/\s/.test(value);
45
46
  }
@@ -61,6 +62,27 @@ function readAdHubAnonymousIdFromCookie(cookieHeader, projectKey) {
61
62
  }
62
63
  return null;
63
64
  }
65
+ function cookieDomainForHost(domain, hostname) {
66
+ const candidate = domain?.trim().toLowerCase().replace(/^\./, "").replace(/\.$/, "");
67
+ const host = hostname?.trim().toLowerCase().replace(/\.$/, "");
68
+ if (!candidate || !host) return null;
69
+ if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(candidate)) return null;
70
+ if (/^[\d.]+$/.test(candidate)) return null;
71
+ return host === candidate || host.endsWith(`.${candidate}`) ? candidate : null;
72
+ }
73
+ function serializeAdHubAnonymousIdCookie(input) {
74
+ const parts = [
75
+ `${getAdHubAnonymousIdCookieName(input.projectKey)}=${encodeURIComponent(input.anonymousId)}`
76
+ ];
77
+ if (input.domain) parts.push(`Domain=${input.domain}`);
78
+ parts.push(
79
+ "Path=/",
80
+ `Max-Age=${input.maxAgeSeconds ?? ANONYMOUS_ID_COOKIE_MAX_AGE_SECONDS}`,
81
+ "SameSite=Lax"
82
+ );
83
+ if (input.secure) parts.push("Secure");
84
+ return parts.join("; ");
85
+ }
64
86
 
65
87
  // src/utils.ts
66
88
  var MAX_PARAM_LENGTH = 2048;
@@ -270,7 +292,6 @@ function sanitizeProfile(profile) {
270
292
  }
271
293
 
272
294
  // src/storage.ts
273
- var COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 395;
274
295
  var MAX_QUEUE_SIZE = 100;
275
296
  function isPendingRequest(value) {
276
297
  if (!value || typeof value !== "object") return false;
@@ -279,6 +300,8 @@ function isPendingRequest(value) {
279
300
  }
280
301
  var BrowserStore = class {
281
302
  constructor(projectKey) {
303
+ this.cookieDomain = null;
304
+ this.projectKey = projectKey;
282
305
  this.suffix = getAdHubAnonymousIdCookieName(projectKey).slice("adhub_project_anonymous_id_".length);
283
306
  }
284
307
  get anonymousKey() {
@@ -290,6 +313,9 @@ var BrowserStore = class {
290
313
  get profileKey() {
291
314
  return `adhub_project_profile_id_${this.suffix}`;
292
315
  }
316
+ get cookieDomainKey() {
317
+ return `adhub_project_cookie_domain_${this.suffix}`;
318
+ }
293
319
  get sessionKey() {
294
320
  return `adhub_project_session_${this.suffix}`;
295
321
  }
@@ -299,11 +325,48 @@ var BrowserStore = class {
299
325
  const fromLocal = this.readLocal(this.anonymousKey);
300
326
  return this.validAnonymousId(fromLocal) ? fromLocal : null;
301
327
  }
328
+ /**
329
+ * Shares the anonymous-id cookie with every subdomain of `domain`.
330
+ * Returns false, and keeps the host-only cookie, when this page is not on that domain.
331
+ */
332
+ setCookieDomain(domain) {
333
+ let hostname = null;
334
+ try {
335
+ hostname = window.location.hostname;
336
+ } catch {
337
+ hostname = null;
338
+ }
339
+ this.cookieDomain = cookieDomainForHost(domain, hostname);
340
+ return this.cookieDomain !== null;
341
+ }
302
342
  writeAnonymousId(anonymousId) {
303
343
  this.writeLocal(this.anonymousKey, anonymousId);
304
344
  try {
305
- const secure = window.location.protocol === "https:" ? "; Secure" : "";
306
- document.cookie = `${this.anonymousKey}=${encodeURIComponent(anonymousId)}; Path=/; Max-Age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secure}`;
345
+ const stored = this.readCookieValues(this.anonymousKey);
346
+ const unchanged = stored.length > 0 && stored.every((value) => value === anonymousId);
347
+ const domainApplied = (this.readLocal(this.cookieDomainKey) || null) === this.cookieDomain;
348
+ if (unchanged && domainApplied) return;
349
+ const secure = window.location.protocol === "https:";
350
+ const write = (domain, maxAgeSeconds = ANONYMOUS_ID_COOKIE_MAX_AGE_SECONDS) => {
351
+ document.cookie = serializeAdHubAnonymousIdCookie({
352
+ projectKey: this.projectKey,
353
+ anonymousId,
354
+ domain,
355
+ secure,
356
+ maxAgeSeconds
357
+ });
358
+ };
359
+ if (this.cookieDomain) {
360
+ write(null, 0);
361
+ write(this.cookieDomain);
362
+ if (this.readCookieValues(this.anonymousKey).includes(anonymousId)) {
363
+ this.writeLocal(this.cookieDomainKey, this.cookieDomain);
364
+ return;
365
+ }
366
+ this.cookieDomain = null;
367
+ }
368
+ write(null);
369
+ this.writeLocal(this.cookieDomainKey, "");
307
370
  } catch {
308
371
  }
309
372
  }
@@ -362,6 +425,19 @@ var BrowserStore = class {
362
425
  }
363
426
  return null;
364
427
  }
428
+ readCookieValues(name) {
429
+ const values = [];
430
+ for (const part of document.cookie.split(";")) {
431
+ const [rawName, ...rawValue] = part.trim().split("=");
432
+ if (rawName !== name) continue;
433
+ try {
434
+ values.push(decodeURIComponent(rawValue.join("=")));
435
+ } catch {
436
+ values.push("");
437
+ }
438
+ }
439
+ return values;
440
+ }
365
441
  readLocal(key) {
366
442
  try {
367
443
  return localStorage.getItem(key);
@@ -383,7 +459,7 @@ var BrowserStore = class {
383
459
  // src/client.ts
384
460
  var DEFAULT_ENDPOINT = "https://api.adhub.so";
385
461
  var SDK_NAME = "nextjs";
386
- var SDK_VERSION = "0.2.0";
462
+ var SDK_VERSION = "0.4.0";
387
463
  var REQUEST_TIMEOUT_MS = 5e3;
388
464
  var RETRY_INTERVAL_MS = 15e3;
389
465
  var PAGE_ENGAGEMENT_INTERVAL_MS = 5e3;
@@ -392,6 +468,7 @@ var BEHAVIOR_EVENTS_PATH = "/api/v1/saas/sdk/behavior-events";
392
468
  var PAGE_ENGAGEMENTS_PATH = "/api/v1/saas/sdk/page-engagements";
393
469
  var SDK_CONFIG_PATH = "/api/v1/saas/sdk/config";
394
470
  var GOOGLE_ADS_CONVERSION_ID = /^AW-\d{6,20}$/;
471
+ var CLARITY_PROJECT_ID = /^[0-9a-z]{4,32}$/;
395
472
  function decideGoogleAdsTag(payload) {
396
473
  if (!payload || typeof payload !== "object") return { action: "skip" };
397
474
  const tag = payload.googleAdsWebsiteTag;
@@ -449,6 +526,62 @@ function injectGoogleAdsWebsiteTag(conversionId) {
449
526
  marker.configuredIds.push(conversionId);
450
527
  gtag("config", conversionId);
451
528
  }
529
+ function decideClarity(payload) {
530
+ if (!payload || typeof payload !== "object") return { action: "skip" };
531
+ const clarity = payload.clarity;
532
+ if (!clarity || typeof clarity !== "object") return { action: "skip" };
533
+ const record = clarity;
534
+ if (record.enabled !== true) return { action: "skip" };
535
+ if (typeof record.projectId !== "string" || record.projectId.trim() === "") {
536
+ return { action: "skip" };
537
+ }
538
+ const projectId = record.projectId.trim();
539
+ if (!CLARITY_PROJECT_ID.test(projectId)) return { action: "invalid" };
540
+ return { action: "inject", projectId };
541
+ }
542
+ function clarityScriptSrc(projectId) {
543
+ return `https://www.clarity.ms/tag/${projectId}`;
544
+ }
545
+ function installClarityQueue() {
546
+ window.clarity = window.clarity || function clarity() {
547
+ const stub = window.clarity;
548
+ if (!stub) return;
549
+ (stub.q = stub.q || []).push(arguments);
550
+ };
551
+ }
552
+ function clarityProjectOnPage() {
553
+ const marker = window.__ADHUB_CLARITY__;
554
+ if (marker && typeof marker.projectId === "string" && CLARITY_PROJECT_ID.test(marker.projectId)) {
555
+ return marker.projectId;
556
+ }
557
+ const match = /^https:\/\/www\.clarity\.ms\/tag\/([0-9a-z]{4,32})$/;
558
+ for (const script of document.getElementsByTagName("script")) {
559
+ const projectId = match.exec(script.src)?.[1];
560
+ if (projectId) return projectId;
561
+ }
562
+ return null;
563
+ }
564
+ function injectClarity(projectId) {
565
+ const installed = clarityProjectOnPage();
566
+ if (installed) {
567
+ if (!window.__ADHUB_CLARITY__) window.__ADHUB_CLARITY__ = { projectId: installed };
568
+ if (installed === projectId) installClarityQueue();
569
+ return installed === projectId;
570
+ }
571
+ installClarityQueue();
572
+ const script = document.createElement("script");
573
+ script.async = true;
574
+ script.src = clarityScriptSrc(projectId);
575
+ script.setAttribute("data-adhub-clarity", projectId);
576
+ const firstScript = document.getElementsByTagName("script")[0];
577
+ if (firstScript?.parentNode) {
578
+ firstScript.parentNode.insertBefore(script, firstScript);
579
+ } else {
580
+ (document.head ?? document.documentElement).appendChild(script);
581
+ }
582
+ window.__ADHUB_CLARITY__ = { projectId };
583
+ return true;
584
+ }
452
585
  var EMPTY_STATE = {
453
586
  initialized: false,
454
587
  anonymousId: null,
@@ -557,6 +690,9 @@ var AdHubBrowserClient = class {
557
690
  this.store = null;
558
691
  this.queue = [];
559
692
  this.endpoint = DEFAULT_ENDPOINT;
693
+ this.cookieDomainOption = null;
694
+ /** The endpoint confirmed that it accepts and sets first-party cookies. */
695
+ this.endpointSharesCookies = false;
560
696
  this.projectKey = "";
561
697
  this.debug = false;
562
698
  this.flushPromise = null;
@@ -575,7 +711,8 @@ var AdHubBrowserClient = class {
575
711
  this.autoTrackDataAttributes = true;
576
712
  this.trackHashChanges = false;
577
713
  this.waitForConsent = false;
578
- this.gtagAbort = null;
714
+ this.sdkConfigAbort = null;
715
+ this.clarityIdentifiedProfileId = null;
579
716
  this.lastPageSignature = "";
580
717
  this.lastTrackedPageUrl = "";
581
718
  this.pendingPageReferrer = null;
@@ -632,12 +769,14 @@ var AdHubBrowserClient = class {
632
769
  if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) {
633
770
  if (this.waitForConsent && options.waitForConsent !== true) {
634
771
  this.waitForConsent = false;
635
- this.scheduleGoogleAdsWebsiteTag();
772
+ this.scheduleSdkConfigTags();
636
773
  }
637
774
  return;
638
775
  }
639
776
  this.projectKey = projectKey;
640
777
  this.endpoint = endpoint;
778
+ this.cookieDomainOption = options.cookieDomain?.trim() || null;
779
+ this.endpointSharesCookies = false;
641
780
  this.debug = options.debug ?? false;
642
781
  this.waitForConsent = options.waitForConsent === true;
643
782
  this.autoFlush = options.autoFlush ?? true;
@@ -647,6 +786,9 @@ var AdHubBrowserClient = class {
647
786
  this.autoTrackDataAttributes = options.autoTrackDataAttributes ?? true;
648
787
  this.trackHashChanges = options.trackHashChanges ?? false;
649
788
  this.store = new BrowserStore(projectKey);
789
+ if (this.cookieDomainOption && !this.store.setCookieDomain(this.cookieDomainOption)) {
790
+ this.log("cookieDomain was ignored because this page is not on that domain.");
791
+ }
650
792
  this.queue = this.store.loadQueue();
651
793
  this.sessionTimeoutMs = Number.isFinite(options.sessionTimeoutMinutes) ? Math.max(1, Math.min(24 * 60, options.sessionTimeoutMinutes ?? 30)) * 60 * 1e3 : DEFAULT_SESSION_TIMEOUT_MS;
652
794
  const anonymousId = this.store.readAnonymousId() ?? randomId("anon");
@@ -685,7 +827,7 @@ var AdHubBrowserClient = class {
685
827
  this.installBehaviorTracking();
686
828
  }
687
829
  this.scheduleFlush();
688
- this.scheduleGoogleAdsWebsiteTag();
830
+ this.scheduleSdkConfigTags();
689
831
  } catch (error) {
690
832
  this.reportError(error);
691
833
  }
@@ -720,6 +862,7 @@ var AdHubBrowserClient = class {
720
862
  this.updateState({ profileId: profile.profileId, lastError: null });
721
863
  this.enqueue("/api/v1/saas/sdk/identify", "profile.identify", data);
722
864
  this.scheduleFlush();
865
+ this.identifyInClarity(profile.profileId);
723
866
  } catch (error) {
724
867
  this.reportError(error);
725
868
  }
@@ -811,6 +954,7 @@ var AdHubBrowserClient = class {
811
954
  const sessionId = randomId("sess");
812
955
  this.store.writeSession(sessionId);
813
956
  this.updateState({ anonymousId, sessionId, profileId: null, lastError: null });
957
+ this.clarityIdentifiedProfileId = null;
814
958
  this.lastPageSignature = "";
815
959
  this.lastTrackedPageUrl = "";
816
960
  this.pendingPageReferrer = null;
@@ -841,8 +985,8 @@ var AdHubBrowserClient = class {
841
985
  return () => this.listeners.delete(listener);
842
986
  }
843
987
  destroy() {
844
- this.gtagAbort?.abort();
845
- this.gtagAbort = null;
988
+ this.sdkConfigAbort?.abort();
989
+ this.sdkConfigAbort = null;
846
990
  this.finishPageVisit();
847
991
  if (browserAvailable() && this.lifecycleInstalled) {
848
992
  window.removeEventListener("online", this.onOnline);
@@ -1031,7 +1175,7 @@ var AdHubBrowserClient = class {
1031
1175
  }),
1032
1176
  body: JSON.stringify(item.body),
1033
1177
  keepalive: true,
1034
- credentials: "omit",
1178
+ credentials: this.credentialsMode(),
1035
1179
  signal: controller.signal
1036
1180
  });
1037
1181
  if (response.ok) {
@@ -1081,50 +1225,101 @@ var AdHubBrowserClient = class {
1081
1225
  this.store?.saveQueue(this.queue);
1082
1226
  this.updateState({ queuedCount: this.queue.length });
1083
1227
  }
1084
- scheduleGoogleAdsWebsiteTag() {
1228
+ scheduleSdkConfigTags() {
1085
1229
  if (!browserAvailable() || this.waitForConsent) return;
1086
- this.gtagAbort?.abort();
1230
+ this.sdkConfigAbort?.abort();
1087
1231
  const abort = new AbortController();
1088
- this.gtagAbort = abort;
1232
+ this.sdkConfigAbort = abort;
1089
1233
  queueMicrotask(() => {
1090
1234
  if (abort.signal.aborted) return;
1091
- void this.fetchAndInjectGoogleAdsWebsiteTag(abort);
1235
+ void this.fetchAndApplySdkConfig(abort);
1092
1236
  });
1093
1237
  }
1094
- async fetchAndInjectGoogleAdsWebsiteTag(abort) {
1238
+ async fetchAndApplySdkConfig(abort) {
1095
1239
  const timeout = setTimeout(() => abort.abort(), REQUEST_TIMEOUT_MS);
1096
1240
  try {
1097
1241
  const response = await fetch(`${this.endpoint}${SDK_CONFIG_PATH}`, {
1098
1242
  method: "GET",
1099
1243
  headers: this.sdkHeaders(),
1100
- credentials: "omit",
1244
+ credentials: this.endpointIsSameOrigin() ? "same-origin" : "omit",
1101
1245
  signal: abort.signal
1102
1246
  });
1103
1247
  if (abort.signal.aborted) return;
1104
1248
  if (!response.ok) {
1105
- this.log(`Google Ads website tag config returned HTTP ${response.status}.`);
1249
+ this.log(`SDK config returned HTTP ${response.status}.`);
1106
1250
  return;
1107
1251
  }
1108
1252
  let payload;
1109
1253
  try {
1110
1254
  payload = await response.json();
1111
1255
  } catch (error) {
1112
- this.log(`Google Ads website tag config was not applied: ${errorMessage(error)}`);
1256
+ this.log(`SDK config was not applied: ${errorMessage(error)}`);
1113
1257
  return;
1114
1258
  }
1115
1259
  if (abort.signal.aborted) return;
1116
- const decision = decideGoogleAdsTag(payload);
1260
+ this.applyIdentityCookieDomain(payload);
1261
+ this.applyGoogleAdsWebsiteTag(payload);
1262
+ this.applyClarity(payload);
1263
+ } catch (error) {
1264
+ if (abort.signal.aborted) return;
1265
+ this.log(`SDK config was not applied: ${errorMessage(error)}`);
1266
+ } finally {
1267
+ clearTimeout(timeout);
1268
+ }
1269
+ }
1270
+ endpointIsSameOrigin() {
1271
+ return this.endpoint === "" || this.endpoint.startsWith("/");
1272
+ }
1273
+ /**
1274
+ * Cookies travel to a same-origin proxy always, and to another host only
1275
+ * after its SDK config confirmed a shared cookie domain. The default API
1276
+ * answers with a wildcard CORS origin, which browsers reject for
1277
+ * credentialed requests, so it must stay "omit".
1278
+ */
1279
+ credentialsMode() {
1280
+ if (this.endpointIsSameOrigin()) return "same-origin";
1281
+ return this.endpointSharesCookies ? "include" : "omit";
1282
+ }
1283
+ applyIdentityCookieDomain(payload) {
1284
+ if (!this.store || !payload || typeof payload !== "object") return;
1285
+ const domain = payload.identityCookieDomain;
1286
+ if (typeof domain !== "string" || !domain.trim()) return;
1287
+ if (!this.store.setCookieDomain(this.cookieDomainOption ?? domain)) return;
1288
+ this.endpointSharesCookies = true;
1289
+ if (this.state.anonymousId) this.store.writeAnonymousId(this.state.anonymousId);
1290
+ }
1291
+ applyGoogleAdsWebsiteTag(payload) {
1292
+ const decision = decideGoogleAdsTag(payload);
1293
+ if (decision.action === "skip") return;
1294
+ if (decision.action === "invalid") {
1295
+ this.log("Google Ads website tag config did not include a valid AW- conversion id.");
1296
+ return;
1297
+ }
1298
+ injectGoogleAdsWebsiteTag(decision.conversionId);
1299
+ }
1300
+ applyClarity(payload) {
1301
+ try {
1302
+ const decision = decideClarity(payload);
1117
1303
  if (decision.action === "skip") return;
1118
1304
  if (decision.action === "invalid") {
1119
- this.log("Google Ads website tag config did not include a valid AW- conversion id.");
1305
+ this.log("Microsoft Clarity config did not include a valid project id.");
1120
1306
  return;
1121
1307
  }
1122
- injectGoogleAdsWebsiteTag(decision.conversionId);
1308
+ if (!injectClarity(decision.projectId)) return;
1309
+ const profileId = this.state.profileId;
1310
+ if (profileId) this.identifyInClarity(profileId);
1123
1311
  } catch (error) {
1124
- if (abort.signal.aborted) return;
1125
- this.log(`Google Ads website tag config was not applied: ${errorMessage(error)}`);
1126
- } finally {
1127
- clearTimeout(timeout);
1312
+ this.log(`Microsoft Clarity was not applied: ${errorMessage(error)}`);
1313
+ }
1314
+ }
1315
+ identifyInClarity(profileId) {
1316
+ if (!profileId || this.clarityIdentifiedProfileId === profileId) return;
1317
+ if (!browserAvailable() || typeof window.clarity !== "function") return;
1318
+ try {
1319
+ window.clarity("identify", profileId);
1320
+ this.clarityIdentifiedProfileId = profileId;
1321
+ } catch (error) {
1322
+ this.log(`Microsoft Clarity identify was not sent: ${errorMessage(error)}`);
1128
1323
  }
1129
1324
  }
1130
1325
  trackGoogleAdsPageView() {