@adhub-so/adhub-nextjs-sdk 0.1.1 → 0.3.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.js CHANGED
@@ -356,13 +356,129 @@ var BrowserStore = class {
356
356
  // src/client.ts
357
357
  var DEFAULT_ENDPOINT = "https://api.adhub.so";
358
358
  var SDK_NAME = "nextjs";
359
- var SDK_VERSION = "0.1.0";
359
+ var SDK_VERSION = "0.3.0";
360
360
  var REQUEST_TIMEOUT_MS = 5e3;
361
361
  var RETRY_INTERVAL_MS = 15e3;
362
362
  var PAGE_ENGAGEMENT_INTERVAL_MS = 5e3;
363
363
  var DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
364
364
  var BEHAVIOR_EVENTS_PATH = "/api/v1/saas/sdk/behavior-events";
365
365
  var PAGE_ENGAGEMENTS_PATH = "/api/v1/saas/sdk/page-engagements";
366
+ var SDK_CONFIG_PATH = "/api/v1/saas/sdk/config";
367
+ var GOOGLE_ADS_CONVERSION_ID = /^AW-\d{6,20}$/;
368
+ var CLARITY_PROJECT_ID = /^[0-9a-z]{4,32}$/;
369
+ function decideGoogleAdsTag(payload) {
370
+ if (!payload || typeof payload !== "object") return { action: "skip" };
371
+ const tag = payload.googleAdsWebsiteTag;
372
+ if (!tag || typeof tag !== "object") return { action: "skip" };
373
+ const record = tag;
374
+ if (record.enabled !== true) return { action: "skip" };
375
+ if (typeof record.conversionId !== "string" || record.conversionId.trim() === "") {
376
+ return { action: "skip" };
377
+ }
378
+ const conversionId = record.conversionId.trim();
379
+ if (!GOOGLE_ADS_CONVERSION_ID.test(conversionId)) return { action: "invalid" };
380
+ return { action: "inject", conversionId };
381
+ }
382
+ function adHubGtagMarker() {
383
+ const current = window.__ADHUB_GTAG__;
384
+ if (current && typeof current.js === "boolean" && Array.isArray(current.configuredIds)) {
385
+ return current;
386
+ }
387
+ const marker = { js: false, configuredIds: [] };
388
+ window.__ADHUB_GTAG__ = marker;
389
+ return marker;
390
+ }
391
+ function gtagScriptSrc(conversionId) {
392
+ return `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(conversionId)}`;
393
+ }
394
+ function installGtagShim() {
395
+ window.dataLayer = window.dataLayer || [];
396
+ if (typeof window.gtag === "function") return;
397
+ window.gtag = function gtag() {
398
+ window.dataLayer?.push(arguments);
399
+ };
400
+ }
401
+ function ensureGtagScript(conversionId) {
402
+ const src = gtagScriptSrc(conversionId);
403
+ for (const script2 of document.getElementsByTagName("script")) {
404
+ if (script2.src === src) return;
405
+ }
406
+ const script = document.createElement("script");
407
+ script.async = true;
408
+ script.src = src;
409
+ script.setAttribute("data-adhub-gtag", conversionId);
410
+ (document.head ?? document.documentElement).appendChild(script);
411
+ }
412
+ function injectGoogleAdsWebsiteTag(conversionId) {
413
+ const marker = adHubGtagMarker();
414
+ if (marker.configuredIds.includes(conversionId)) return;
415
+ installGtagShim();
416
+ ensureGtagScript(conversionId);
417
+ const gtag = window.gtag;
418
+ if (typeof gtag !== "function") return;
419
+ if (!marker.js) {
420
+ marker.js = true;
421
+ gtag("js", /* @__PURE__ */ new Date());
422
+ }
423
+ marker.configuredIds.push(conversionId);
424
+ gtag("config", conversionId);
425
+ }
426
+ function decideClarity(payload) {
427
+ if (!payload || typeof payload !== "object") return { action: "skip" };
428
+ const clarity = payload.clarity;
429
+ if (!clarity || typeof clarity !== "object") return { action: "skip" };
430
+ const record = clarity;
431
+ if (record.enabled !== true) return { action: "skip" };
432
+ if (typeof record.projectId !== "string" || record.projectId.trim() === "") {
433
+ return { action: "skip" };
434
+ }
435
+ const projectId = record.projectId.trim();
436
+ if (!CLARITY_PROJECT_ID.test(projectId)) return { action: "invalid" };
437
+ return { action: "inject", projectId };
438
+ }
439
+ function clarityScriptSrc(projectId) {
440
+ return `https://www.clarity.ms/tag/${projectId}`;
441
+ }
442
+ function installClarityQueue() {
443
+ window.clarity = window.clarity || function clarity() {
444
+ const stub = window.clarity;
445
+ if (!stub) return;
446
+ (stub.q = stub.q || []).push(arguments);
447
+ };
448
+ }
449
+ function clarityProjectOnPage() {
450
+ const marker = window.__ADHUB_CLARITY__;
451
+ if (marker && typeof marker.projectId === "string" && CLARITY_PROJECT_ID.test(marker.projectId)) {
452
+ return marker.projectId;
453
+ }
454
+ const match = /^https:\/\/www\.clarity\.ms\/tag\/([0-9a-z]{4,32})$/;
455
+ for (const script of document.getElementsByTagName("script")) {
456
+ const projectId = match.exec(script.src)?.[1];
457
+ if (projectId) return projectId;
458
+ }
459
+ return null;
460
+ }
461
+ function injectClarity(projectId) {
462
+ const installed = clarityProjectOnPage();
463
+ if (installed) {
464
+ if (!window.__ADHUB_CLARITY__) window.__ADHUB_CLARITY__ = { projectId: installed };
465
+ if (installed === projectId) installClarityQueue();
466
+ return installed === projectId;
467
+ }
468
+ installClarityQueue();
469
+ const script = document.createElement("script");
470
+ script.async = true;
471
+ script.src = clarityScriptSrc(projectId);
472
+ script.setAttribute("data-adhub-clarity", projectId);
473
+ const firstScript = document.getElementsByTagName("script")[0];
474
+ if (firstScript?.parentNode) {
475
+ firstScript.parentNode.insertBefore(script, firstScript);
476
+ } else {
477
+ (document.head ?? document.documentElement).appendChild(script);
478
+ }
479
+ window.__ADHUB_CLARITY__ = { projectId };
480
+ return true;
481
+ }
366
482
  var EMPTY_STATE = {
367
483
  initialized: false,
368
484
  anonymousId: null,
@@ -488,7 +604,12 @@ var AdHubBrowserClient = class {
488
604
  this.autoTrackOutgoingLinks = true;
489
605
  this.autoTrackDataAttributes = true;
490
606
  this.trackHashChanges = false;
607
+ this.waitForConsent = false;
608
+ this.sdkConfigAbort = null;
609
+ this.clarityIdentifiedProfileId = null;
491
610
  this.lastPageSignature = "";
611
+ this.lastTrackedPageUrl = "";
612
+ this.pendingPageReferrer = null;
492
613
  this.originalPushState = null;
493
614
  this.originalReplaceState = null;
494
615
  this.patchedPushState = null;
@@ -539,10 +660,17 @@ var AdHubBrowserClient = class {
539
660
  return;
540
661
  }
541
662
  if (!browserAvailable()) return;
542
- if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) return;
663
+ if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) {
664
+ if (this.waitForConsent && options.waitForConsent !== true) {
665
+ this.waitForConsent = false;
666
+ this.scheduleSdkConfigTags();
667
+ }
668
+ return;
669
+ }
543
670
  this.projectKey = projectKey;
544
671
  this.endpoint = endpoint;
545
672
  this.debug = options.debug ?? false;
673
+ this.waitForConsent = options.waitForConsent === true;
546
674
  this.autoFlush = options.autoFlush ?? true;
547
675
  this.autoPageview = options.autoPageview ?? true;
548
676
  this.autoPageEngagement = options.autoPageEngagement ?? true;
@@ -588,6 +716,7 @@ var AdHubBrowserClient = class {
588
716
  this.installBehaviorTracking();
589
717
  }
590
718
  this.scheduleFlush();
719
+ this.scheduleSdkConfigTags();
591
720
  } catch (error) {
592
721
  this.reportError(error);
593
722
  }
@@ -622,6 +751,7 @@ var AdHubBrowserClient = class {
622
751
  this.updateState({ profileId: profile.profileId, lastError: null });
623
752
  this.enqueue("/api/v1/saas/sdk/identify", "profile.identify", data);
624
753
  this.scheduleFlush();
754
+ this.identifyInClarity(profile.profileId);
625
755
  } catch (error) {
626
756
  this.reportError(error);
627
757
  }
@@ -642,7 +772,10 @@ var AdHubBrowserClient = class {
642
772
  normalized.title,
643
773
  normalized.eventId
644
774
  ].join("|");
645
- if (!input.eventId && signature === this.lastPageSignature) return;
775
+ if (!input.eventId && signature === this.lastPageSignature) {
776
+ this.pendingPageReferrer = null;
777
+ return;
778
+ }
646
779
  this.lastPageSignature = signature;
647
780
  this.finishPageVisit();
648
781
  const pageViewId = normalized.eventId ?? randomId("page");
@@ -650,6 +783,9 @@ var AdHubBrowserClient = class {
650
783
  if (this.autoPageEngagement) {
651
784
  this.startPageVisit(normalized, pageViewId, sessionId);
652
785
  }
786
+ this.lastTrackedPageUrl = normalized.pageUrl ?? safePageUrl(window.location.href);
787
+ this.pendingPageReferrer = null;
788
+ this.trackGoogleAdsPageView();
653
789
  } catch (error) {
654
790
  this.reportError(error);
655
791
  }
@@ -707,7 +843,10 @@ var AdHubBrowserClient = class {
707
843
  const sessionId = randomId("sess");
708
844
  this.store.writeSession(sessionId);
709
845
  this.updateState({ anonymousId, sessionId, profileId: null, lastError: null });
846
+ this.clarityIdentifiedProfileId = null;
710
847
  this.lastPageSignature = "";
848
+ this.lastTrackedPageUrl = "";
849
+ this.pendingPageReferrer = null;
711
850
  if (this.autoPageview) this.page();
712
851
  } catch (error) {
713
852
  this.reportError(error);
@@ -735,6 +874,8 @@ var AdHubBrowserClient = class {
735
874
  return () => this.listeners.delete(listener);
736
875
  }
737
876
  destroy() {
877
+ this.sdkConfigAbort?.abort();
878
+ this.sdkConfigAbort = null;
738
879
  this.finishPageVisit();
739
880
  if (browserAvailable() && this.lifecycleInstalled) {
740
881
  window.removeEventListener("online", this.onOnline);
@@ -800,11 +941,13 @@ var AdHubBrowserClient = class {
800
941
  return sessionId;
801
942
  }
802
943
  currentPageFields() {
944
+ const pageUrl = safePageUrl(window.location.href);
945
+ const referrer = this.pendingPageReferrer ?? (this.lastTrackedPageUrl && this.lastTrackedPageUrl !== pageUrl ? this.lastTrackedPageUrl : document.referrer || null);
803
946
  return {
804
- pageUrl: safePageUrl(window.location.href),
947
+ pageUrl,
805
948
  path: window.location.pathname || "/",
806
949
  title: document.title,
807
- referrer: document.referrer || null
950
+ referrer
808
951
  };
809
952
  }
810
953
  enqueueBehaviorEvent(normalized) {
@@ -915,13 +1058,10 @@ var AdHubBrowserClient = class {
915
1058
  try {
916
1059
  const response = await fetch(`${this.endpoint}${item.path}`, {
917
1060
  method: "POST",
918
- headers: {
1061
+ headers: this.sdkHeaders({
919
1062
  "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
- },
1063
+ "Idempotency-Key": item.requestId
1064
+ }),
925
1065
  body: JSON.stringify(item.body),
926
1066
  keepalive: true,
927
1067
  credentials: "omit",
@@ -974,6 +1114,103 @@ var AdHubBrowserClient = class {
974
1114
  this.store?.saveQueue(this.queue);
975
1115
  this.updateState({ queuedCount: this.queue.length });
976
1116
  }
1117
+ scheduleSdkConfigTags() {
1118
+ if (!browserAvailable() || this.waitForConsent) return;
1119
+ this.sdkConfigAbort?.abort();
1120
+ const abort = new AbortController();
1121
+ this.sdkConfigAbort = abort;
1122
+ queueMicrotask(() => {
1123
+ if (abort.signal.aborted) return;
1124
+ void this.fetchAndApplySdkConfig(abort);
1125
+ });
1126
+ }
1127
+ async fetchAndApplySdkConfig(abort) {
1128
+ const timeout = setTimeout(() => abort.abort(), REQUEST_TIMEOUT_MS);
1129
+ try {
1130
+ const response = await fetch(`${this.endpoint}${SDK_CONFIG_PATH}`, {
1131
+ method: "GET",
1132
+ headers: this.sdkHeaders(),
1133
+ credentials: "omit",
1134
+ signal: abort.signal
1135
+ });
1136
+ if (abort.signal.aborted) return;
1137
+ if (!response.ok) {
1138
+ this.log(`SDK config returned HTTP ${response.status}.`);
1139
+ return;
1140
+ }
1141
+ let payload;
1142
+ try {
1143
+ payload = await response.json();
1144
+ } catch (error) {
1145
+ this.log(`SDK config was not applied: ${errorMessage(error)}`);
1146
+ return;
1147
+ }
1148
+ if (abort.signal.aborted) return;
1149
+ this.applyGoogleAdsWebsiteTag(payload);
1150
+ this.applyClarity(payload);
1151
+ } catch (error) {
1152
+ if (abort.signal.aborted) return;
1153
+ this.log(`SDK config was not applied: ${errorMessage(error)}`);
1154
+ } finally {
1155
+ clearTimeout(timeout);
1156
+ }
1157
+ }
1158
+ applyGoogleAdsWebsiteTag(payload) {
1159
+ const decision = decideGoogleAdsTag(payload);
1160
+ if (decision.action === "skip") return;
1161
+ if (decision.action === "invalid") {
1162
+ this.log("Google Ads website tag config did not include a valid AW- conversion id.");
1163
+ return;
1164
+ }
1165
+ injectGoogleAdsWebsiteTag(decision.conversionId);
1166
+ }
1167
+ applyClarity(payload) {
1168
+ try {
1169
+ const decision = decideClarity(payload);
1170
+ if (decision.action === "skip") return;
1171
+ if (decision.action === "invalid") {
1172
+ this.log("Microsoft Clarity config did not include a valid project id.");
1173
+ return;
1174
+ }
1175
+ if (!injectClarity(decision.projectId)) return;
1176
+ const profileId = this.state.profileId;
1177
+ if (profileId) this.identifyInClarity(profileId);
1178
+ } catch (error) {
1179
+ this.log(`Microsoft Clarity was not applied: ${errorMessage(error)}`);
1180
+ }
1181
+ }
1182
+ identifyInClarity(profileId) {
1183
+ if (!profileId || this.clarityIdentifiedProfileId === profileId) return;
1184
+ if (!browserAvailable() || typeof window.clarity !== "function") return;
1185
+ try {
1186
+ window.clarity("identify", profileId);
1187
+ this.clarityIdentifiedProfileId = profileId;
1188
+ } catch (error) {
1189
+ this.log(`Microsoft Clarity identify was not sent: ${errorMessage(error)}`);
1190
+ }
1191
+ }
1192
+ trackGoogleAdsPageView() {
1193
+ if (!this.autoPageview || !browserAvailable()) return;
1194
+ const marker = window.__ADHUB_GTAG__;
1195
+ if (!marker?.configuredIds.length || typeof window.gtag !== "function") return;
1196
+ try {
1197
+ window.gtag("event", "page_view", {
1198
+ page_location: window.location.href,
1199
+ page_path: `${window.location.pathname}${window.location.search}`,
1200
+ page_title: document.title
1201
+ });
1202
+ } catch (error) {
1203
+ this.log(`Google Ads page_view was not sent: ${errorMessage(error)}`);
1204
+ }
1205
+ }
1206
+ sdkHeaders(extra) {
1207
+ return {
1208
+ "X-AdHub-Project-Key": this.projectKey,
1209
+ "X-AdHub-SDK": SDK_NAME,
1210
+ "X-AdHub-SDK-Version": SDK_VERSION,
1211
+ ...extra
1212
+ };
1213
+ }
977
1214
  installLifecycle() {
978
1215
  if (this.lifecycleInstalled) return;
979
1216
  window.addEventListener("online", this.onOnline);
@@ -1002,14 +1239,25 @@ var AdHubBrowserClient = class {
1002
1239
  };
1003
1240
  const originalPushState = this.originalPushState;
1004
1241
  const originalReplaceState = this.originalReplaceState;
1242
+ const client = this;
1005
1243
  this.patchedPushState = function pushState(...args) {
1244
+ const previousPageUrl = safePageUrl(window.location.href);
1006
1245
  const result = originalPushState.apply(this, args);
1007
- dispatchLocationChange();
1246
+ const nextPageUrl = safePageUrl(window.location.href);
1247
+ if (previousPageUrl !== nextPageUrl) {
1248
+ client.pendingPageReferrer ?? (client.pendingPageReferrer = client.lastTrackedPageUrl || previousPageUrl);
1249
+ dispatchLocationChange();
1250
+ }
1008
1251
  return result;
1009
1252
  };
1010
1253
  this.patchedReplaceState = function replaceState(...args) {
1254
+ const previousPageUrl = safePageUrl(window.location.href);
1011
1255
  const result = originalReplaceState.apply(this, args);
1012
- dispatchLocationChange();
1256
+ const nextPageUrl = safePageUrl(window.location.href);
1257
+ if (previousPageUrl !== nextPageUrl) {
1258
+ client.pendingPageReferrer ?? (client.pendingPageReferrer = client.lastTrackedPageUrl || previousPageUrl);
1259
+ dispatchLocationChange();
1260
+ }
1013
1261
  return result;
1014
1262
  };
1015
1263
  history.pushState = this.patchedPushState;