@adhub-so/adhub-nextjs-sdk 0.3.0 → 0.4.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/README.md CHANGED
@@ -108,6 +108,7 @@ The minimal setup above does not require any of the following features. Use them
108
108
  - [Google Ads website tag](#google-ads-website-tag) for consent, SPA page views, and the same-origin config proxy.
109
109
  - [Microsoft Clarity](#microsoft-clarity) when the project enables Clarity session recordings.
110
110
  - [First-party Route Handler](#first-party-route-handler) for a same-origin collection path, customer-edge geo headers, or a custom API target.
111
+ - [Visitor identity cookie](#visitor-identity-cookie) to share one visitor across subdomains or keep the cookie longer in Safari.
111
112
  - [Capture before hydration](#capture-before-hydration) when application code removes attribution parameters before React hydrates.
112
113
  - [Manual flush and queue control](#manual-flush-and-queue-control) for tests, diagnostics, or `autoFlush: false`.
113
114
  - [Trusted server events](#trusted-server-events) for payments and other authoritative business facts.
@@ -170,6 +171,7 @@ The optional Route Handler can provide:
170
171
  - Vercel, Cloudflare, or CloudFront geo headers available at the customer's edge.
171
172
  - A centralized self-hosted, regional, or test AdHub API target through `apiUrl`.
172
173
  - A restricted proxy that accepts only supported SDK ingestion paths.
174
+ - A visitor identity cookie set by your own server, which Safari keeps for its full lifetime.
173
175
 
174
176
  The tradeoff is an extra network hop, another Next.js server request, and an additional failure point. It requires an App Router server runtime and does not work with a purely static export. It also does not make browser events trusted and must not use an ingestion key.
175
177
 
@@ -199,6 +201,29 @@ The handler preserves the original Origin, User-Agent, client IP, supported edge
199
201
 
200
202
  Do not configure only one half of proxy mode. Setting `endpoint="/api/adhub"` without deploying the matching catch-all Route Handler causes 404 responses and leaves requests in the retry queue.
201
203
 
204
+ ### Visitor identity cookie
205
+
206
+ The SDK keeps the anonymous visitor ID in a first-party cookie for 395 days. Two optional settings make that cookie more durable.
207
+
208
+ **Share one identity across subdomains.** By default the cookie belongs to the current hostname, so `www.example.com` and `app.example.com` see two different visitors and a click on the marketing site is not linked to a signup in the app. Set `cookieDomain` to the shared parent domain on every site:
209
+
210
+ ```tsx
211
+ <AdHubComponent
212
+ projectKey={process.env.NEXT_PUBLIC_ADHUB_PROJECT_KEY!}
213
+ cookieDomain="example.com"
214
+ />
215
+ ```
216
+
217
+ The option is ignored when the page is not on that domain. With a first-party tracking domain as `endpoint`, AdHub reports the shared domain itself and `cookieDomain` can be omitted.
218
+
219
+ **Keep the cookie for its full lifetime in Safari.** Safari expires cookies written by JavaScript after 7 days. With the [First-party Route Handler](#first-party-route-handler), your own server sets the cookie on every accepted request, which is not subject to that limit. When you also use `cookieDomain`, pass the same value to the handler:
220
+
221
+ ```ts
222
+ const handler = createRouteHandler({ cookieDomain: "example.com" });
223
+ ```
224
+
225
+ The SDK does not rewrite a cookie that already holds the current ID, so the server-set cookie is preserved. A first-party tracking domain alone does not lift Safari's limit, because its server is not your site's server.
226
+
202
227
  ### Capture before hydration
203
228
 
204
229
  Next.js 15.3 and newer can initialize AdHub synchronously from `instrumentation-client.ts`. Use this only when application code may remove attribution query parameters before React hydrates.
@@ -0,0 +1,140 @@
1
+ // src/utils.ts
2
+ var MAX_PARAM_LENGTH = 2048;
3
+ var MAX_ROUTE_LENGTH = 255;
4
+ var MAX_URL_LENGTH = 8192;
5
+ var MAX_UTM_KEYS = 50;
6
+ var MAX_VALUES_PER_PARAM = 10;
7
+ 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;
8
+ var EVENT_TYPE_PATTERN = /^[a-z][a-z0-9_.-]{0,127}$/;
9
+ var TIMEZONE_SUFFIX_PATTERN = /(?:z|[+-]\d{2}:\d{2})$/i;
10
+ var MAX_EVENT_ID_LENGTH = 255;
11
+ var MAX_EVENT_PROPERTIES_LENGTH = 32768;
12
+ var MAX_PROFILE_ID_LENGTH = 255;
13
+ var PROFILE_ID_CONTROL_PATTERN = /[\p{Cc}\p{Cf}]/u;
14
+ function nowIso() {
15
+ return (/* @__PURE__ */ new Date()).toISOString();
16
+ }
17
+ function randomId(prefix) {
18
+ const uuid = globalThis.crypto?.randomUUID?.();
19
+ if (uuid) return `${prefix}_${uuid}`;
20
+ const random = Math.random().toString(36).slice(2);
21
+ return `${prefix}_${Date.now().toString(36)}${random}`;
22
+ }
23
+ function truncate(value) {
24
+ return value.slice(0, MAX_PARAM_LENGTH);
25
+ }
26
+ function unique(values) {
27
+ return [...new Set(values.filter(Boolean).map(truncate))];
28
+ }
29
+ function valuesFor(searchParams, wantedKey) {
30
+ const values = [];
31
+ for (const [key, value] of searchParams.entries()) {
32
+ if (key.toLowerCase() === wantedKey) values.push(value);
33
+ }
34
+ return unique(values).slice(0, MAX_VALUES_PER_PARAM);
35
+ }
36
+ function isUuid(value) {
37
+ return UUID_PATTERN.test(value);
38
+ }
39
+ function normalizeProfileId(value) {
40
+ const normalized = value.trim();
41
+ if (!normalized || [...normalized].length > MAX_PROFILE_ID_LENGTH || PROFILE_ID_CONTROL_PATTERN.test(normalized)) {
42
+ return null;
43
+ }
44
+ return normalized;
45
+ }
46
+ function safePageUrl(input) {
47
+ try {
48
+ const url = new URL(input);
49
+ return `${url.origin}${url.pathname}`.slice(0, MAX_URL_LENGTH);
50
+ } catch {
51
+ return "";
52
+ }
53
+ }
54
+ function safeReferrer(input) {
55
+ if (!input) return null;
56
+ const safe = safePageUrl(input);
57
+ return safe || null;
58
+ }
59
+ function captureTouchpoint(location, referrer, capturedAt = nowIso()) {
60
+ const url = new URL(location.href);
61
+ const clickIds = {
62
+ gclid: valuesFor(url.searchParams, "gclid"),
63
+ gbraid: valuesFor(url.searchParams, "gbraid"),
64
+ wbraid: valuesFor(url.searchParams, "wbraid")
65
+ };
66
+ const utm = {};
67
+ for (const key of [...new Set([...url.searchParams.keys()].map((key2) => key2.toLowerCase()))].filter((candidate) => candidate.startsWith("utm_")).slice(0, MAX_UTM_KEYS)) {
68
+ utm[key] = valuesFor(url.searchParams, key);
69
+ }
70
+ return {
71
+ ahRoute: valuesFor(url.searchParams, "ah_route")[0]?.slice(0, MAX_ROUTE_LENGTH) ?? null,
72
+ clickIds,
73
+ utm,
74
+ landingUrl: safePageUrl(url.href),
75
+ referrer: safeReferrer(referrer),
76
+ // Browsers do not know Google's server-side click timestamp. This is the
77
+ // first-party observation time and is the upper bound available to the SDK.
78
+ clickTime: capturedAt
79
+ };
80
+ }
81
+ function toJsonValue(value) {
82
+ if (value === void 0) return void 0;
83
+ try {
84
+ return JSON.parse(JSON.stringify(value));
85
+ } catch {
86
+ return void 0;
87
+ }
88
+ }
89
+ function normalizeEventFields(input) {
90
+ const eventType = input.eventType?.trim().toLowerCase();
91
+ if (!eventType || !EVENT_TYPE_PATTERN.test(eventType) && !isUuid(eventType)) {
92
+ throw new Error(
93
+ "AdHub eventType must be an Event Definition UUID or event key."
94
+ );
95
+ }
96
+ const occurredAtInput = input.occurredAt?.trim() || nowIso();
97
+ if (!TIMEZONE_SUFFIX_PATTERN.test(occurredAtInput)) {
98
+ throw new Error("AdHub occurredAt must include a timezone offset.");
99
+ }
100
+ const occurredAtDate = new Date(occurredAtInput);
101
+ if (Number.isNaN(occurredAtDate.getTime())) {
102
+ throw new Error("AdHub occurredAt must be a valid ISO-8601 timestamp.");
103
+ }
104
+ const result = {
105
+ eventType,
106
+ occurredAt: occurredAtDate.toISOString()
107
+ };
108
+ if (input.eventId !== void 0) {
109
+ const eventId = input.eventId.trim();
110
+ if (!eventId || eventId.length > MAX_EVENT_ID_LENGTH || [...eventId].some((character) => character.charCodeAt(0) < 32 || character === "\x7F")) {
111
+ throw new Error("AdHub eventId must be 1-255 characters without control characters.");
112
+ }
113
+ result.eventId = eventId;
114
+ }
115
+ if (input.value !== void 0) {
116
+ if (!Number.isFinite(input.value) || input.value < 0) {
117
+ throw new Error("AdHub event value must be a finite non-negative number.");
118
+ }
119
+ result.value = input.value;
120
+ }
121
+ if (input.currency !== void 0) {
122
+ const currency = input.currency.trim().toUpperCase();
123
+ if (!/^[A-Z]{3}$/.test(currency)) {
124
+ throw new Error("AdHub event currency must be a three-letter ISO 4217 code.");
125
+ }
126
+ result.currency = currency;
127
+ }
128
+ if (input.properties !== void 0) {
129
+ const properties = toJsonValue(input.properties);
130
+ if (!properties || typeof properties !== "object" || Array.isArray(properties) || JSON.stringify(properties).length > MAX_EVENT_PROPERTIES_LENGTH) {
131
+ throw new Error("AdHub event properties must be a JSON object no larger than 32 KiB.");
132
+ }
133
+ result.properties = properties;
134
+ }
135
+ return result;
136
+ }
137
+
138
+ export { captureTouchpoint, isUuid, normalizeEventFields, normalizeProfileId, nowIso, randomId, safePageUrl };
139
+ //# sourceMappingURL=chunk-NF56G46G.js.map
140
+ //# sourceMappingURL=chunk-NF56G46G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils.ts"],"names":["key"],"mappings":";AAUA,IAAM,gBAAA,GAAmB,IAAA;AACzB,IAAM,gBAAA,GAAmB,GAAA;AACzB,IAAM,cAAA,GAAiB,IAAA;AACvB,IAAM,YAAA,GAAe,EAAA;AACrB,IAAM,oBAAA,GAAuB,EAAA;AAC7B,IAAM,YAAA,GAAe,4EAAA;AACrB,IAAM,kBAAA,GAAqB,2BAAA;AAC3B,IAAM,uBAAA,GAA0B,yBAAA;AAChC,IAAM,mBAAA,GAAsB,GAAA;AAC5B,IAAM,2BAAA,GAA8B,KAAA;AACpC,IAAM,qBAAA,GAAwB,GAAA;AAC9B,IAAM,0BAAA,GAA6B,iBAAA;AA2B5B,SAAS,MAAA,GAAiB;AAC/B,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC;AAEO,SAAS,SAAS,MAAA,EAAwB;AAC/C,EAAA,MAAM,IAAA,GAAO,UAAA,CAAW,MAAA,EAAQ,UAAA,IAAa;AAC7C,EAAA,IAAI,IAAA,EAAM,OAAO,CAAA,EAAG,MAAM,IAAI,IAAI,CAAA,CAAA;AAElC,EAAA,MAAM,MAAA,GAAS,KAAK,MAAA,EAAO,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A,EAAW;AAClC,IAAA,MAAM,UAAA,GAAa,WAAA,CAAY,KAAA,CAAM,UAAU,CAAA;AAC/C,IAAA,IACE,CAAC,UAAA,IACD,OAAO,UAAA,KAAe,YACtB,KAAA,CAAM,OAAA,CAAQ,UAAU,CAAA,IACxB,IAAA,CAAK,SAAA,CAAU,UAAU,CAAA,CAAE,SAAS,2BAAA,EACpC;AACA,MAAA,MAAM,IAAI,MAAM,qEAAqE,CAAA;AAAA,IACvF;AACA,IAAA,MAAA,CAAO,UAAA,GAAa,UAAA;AAAA,EACtB;AAEA,EAAA,OAAO,MAAA;AACT","file":"chunk-NF56G46G.js","sourcesContent":["import type {\n BrowserBehaviorEventInput,\n BrowserPageviewInput,\n CapturedTouchpoint,\n ClickIdentifiers,\n IdentifyProfile,\n JsonObject,\n JsonValue,\n} from \"./types\";\n\nconst MAX_PARAM_LENGTH = 2_048;\nconst MAX_ROUTE_LENGTH = 255;\nconst MAX_URL_LENGTH = 8_192;\nconst MAX_UTM_KEYS = 50;\nconst MAX_VALUES_PER_PARAM = 10;\nconst 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;\nconst EVENT_TYPE_PATTERN = /^[a-z][a-z0-9_.-]{0,127}$/;\nconst TIMEZONE_SUFFIX_PATTERN = /(?:z|[+-]\\d{2}:\\d{2})$/i;\nconst MAX_EVENT_ID_LENGTH = 255;\nconst MAX_EVENT_PROPERTIES_LENGTH = 32_768;\nconst MAX_PROFILE_ID_LENGTH = 255;\nconst PROFILE_ID_CONTROL_PATTERN = /[\\p{Cc}\\p{Cf}]/u;\n\nexport interface NormalizedEventFields {\n eventType: string;\n occurredAt: string;\n eventId?: string;\n value?: number;\n currency?: string;\n properties?: JsonObject;\n}\n\nexport interface NormalizedBehaviorEventFields {\n eventName: string;\n occurredAt: string;\n eventId?: string;\n pageUrl?: string;\n path?: string;\n title?: string;\n referrer?: string | null;\n properties?: JsonObject;\n}\n\nexport interface NormalizedPageviewFields\n extends Omit<NormalizedBehaviorEventFields, \"eventName\"> {\n eventName: \"pageview\";\n}\n\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n\nexport function randomId(prefix: string): string {\n const uuid = globalThis.crypto?.randomUUID?.();\n if (uuid) return `${prefix}_${uuid}`;\n\n const random = Math.random().toString(36).slice(2);\n return `${prefix}_${Date.now().toString(36)}${random}`;\n}\n\nfunction truncate(value: string): string {\n return value.slice(0, MAX_PARAM_LENGTH);\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.filter(Boolean).map(truncate))];\n}\n\nfunction valuesFor(searchParams: URLSearchParams, wantedKey: string): string[] {\n const values: string[] = [];\n for (const [key, value] of searchParams.entries()) {\n if (key.toLowerCase() === wantedKey) values.push(value);\n }\n return unique(values).slice(0, MAX_VALUES_PER_PARAM);\n}\n\nexport function isUuid(value: string): boolean {\n return UUID_PATTERN.test(value);\n}\n\nexport function normalizeProfileId(value: string): string | null {\n const normalized = value.trim();\n if (\n !normalized ||\n [...normalized].length > MAX_PROFILE_ID_LENGTH ||\n PROFILE_ID_CONTROL_PATTERN.test(normalized)\n ) {\n return null;\n }\n return normalized;\n}\n\nexport function safePageUrl(input: string): string {\n try {\n const url = new URL(input);\n return `${url.origin}${url.pathname}`.slice(0, MAX_URL_LENGTH);\n } catch {\n return \"\";\n }\n}\n\nexport function safeReferrer(input: string): string | null {\n if (!input) return null;\n const safe = safePageUrl(input);\n return safe || null;\n}\n\nexport function captureTouchpoint(\n location: Pick<Location, \"href\">,\n referrer: string,\n capturedAt = nowIso(),\n): CapturedTouchpoint {\n const url = new URL(location.href);\n const clickIds: ClickIdentifiers = {\n gclid: valuesFor(url.searchParams, \"gclid\"),\n gbraid: valuesFor(url.searchParams, \"gbraid\"),\n wbraid: valuesFor(url.searchParams, \"wbraid\"),\n };\n const utm: Record<string, string[]> = {};\n\n for (const key of [...new Set([...url.searchParams.keys()].map((key) => key.toLowerCase()))]\n .filter((candidate) => candidate.startsWith(\"utm_\"))\n .slice(0, MAX_UTM_KEYS)) {\n utm[key] = valuesFor(url.searchParams, key);\n }\n\n return {\n ahRoute: valuesFor(url.searchParams, \"ah_route\")[0]?.slice(0, MAX_ROUTE_LENGTH) ?? null,\n clickIds,\n utm,\n landingUrl: safePageUrl(url.href),\n referrer: safeReferrer(referrer),\n // Browsers do not know Google's server-side click timestamp. This is the\n // first-party observation time and is the upper bound available to the SDK.\n clickTime: capturedAt,\n };\n}\n\nexport function toJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) return undefined;\n try {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n } catch {\n return undefined;\n }\n}\n\ninterface EventFieldsInput {\n eventType: string;\n eventId?: string;\n occurredAt?: string;\n value?: number;\n currency?: string;\n properties?: Record<string, unknown>;\n}\n\nexport function normalizeEventFields(input: EventFieldsInput): NormalizedEventFields {\n const eventType = input.eventType?.trim().toLowerCase();\n if (!eventType || (!EVENT_TYPE_PATTERN.test(eventType) && !isUuid(eventType))) {\n throw new Error(\n \"AdHub eventType must be an Event Definition UUID or event key.\",\n );\n }\n\n const occurredAtInput = input.occurredAt?.trim() || nowIso();\n if (!TIMEZONE_SUFFIX_PATTERN.test(occurredAtInput)) {\n throw new Error(\"AdHub occurredAt must include a timezone offset.\");\n }\n const occurredAtDate = new Date(occurredAtInput);\n if (Number.isNaN(occurredAtDate.getTime())) {\n throw new Error(\"AdHub occurredAt must be a valid ISO-8601 timestamp.\");\n }\n\n const result: NormalizedEventFields = {\n eventType,\n occurredAt: occurredAtDate.toISOString(),\n };\n\n if (input.eventId !== undefined) {\n const eventId = input.eventId.trim();\n if (\n !eventId ||\n eventId.length > MAX_EVENT_ID_LENGTH ||\n [...eventId].some((character) => character.charCodeAt(0) < 32 || character === \"\\u007f\")\n ) {\n throw new Error(\"AdHub eventId must be 1-255 characters without control characters.\");\n }\n result.eventId = eventId;\n }\n\n if (input.value !== undefined) {\n if (!Number.isFinite(input.value) || input.value < 0) {\n throw new Error(\"AdHub event value must be a finite non-negative number.\");\n }\n result.value = input.value;\n }\n\n if (input.currency !== undefined) {\n const currency = input.currency.trim().toUpperCase();\n if (!/^[A-Z]{3}$/.test(currency)) {\n throw new Error(\"AdHub event currency must be a three-letter ISO 4217 code.\");\n }\n result.currency = currency;\n }\n\n if (input.properties !== undefined) {\n const properties = toJsonValue(input.properties);\n if (\n !properties ||\n typeof properties !== \"object\" ||\n Array.isArray(properties) ||\n JSON.stringify(properties).length > MAX_EVENT_PROPERTIES_LENGTH\n ) {\n throw new Error(\"AdHub event properties must be a JSON object no larger than 32 KiB.\");\n }\n result.properties = properties;\n }\n\n return result;\n}\n\nexport function normalizeBehaviorEventFields(\n input: BrowserBehaviorEventInput,\n): NormalizedBehaviorEventFields {\n const eventName = input.eventName?.trim().toLowerCase();\n if (!eventName || !EVENT_TYPE_PATTERN.test(eventName)) {\n throw new Error(\n \"AdHub behavior eventName must start with a letter and use letters, digits, _, . or -.\",\n );\n }\n\n const occurredAtInput = input.occurredAt?.trim() || nowIso();\n if (!TIMEZONE_SUFFIX_PATTERN.test(occurredAtInput)) {\n throw new Error(\"AdHub behavior occurredAt must include a timezone offset.\");\n }\n const occurredAtDate = new Date(occurredAtInput);\n if (Number.isNaN(occurredAtDate.getTime())) {\n throw new Error(\"AdHub behavior occurredAt must be a valid ISO-8601 timestamp.\");\n }\n\n const result: NormalizedBehaviorEventFields = {\n eventName,\n occurredAt: occurredAtDate.toISOString(),\n };\n\n if (input.eventId !== undefined) {\n const eventId = input.eventId.trim();\n if (\n !eventId ||\n eventId.length > MAX_EVENT_ID_LENGTH ||\n [...eventId].some((character) => character.charCodeAt(0) < 32 || character === \"\\u007f\")\n ) {\n throw new Error(\"AdHub behavior eventId must be 1-255 characters without control characters.\");\n }\n result.eventId = eventId;\n }\n\n if (input.pageUrl !== undefined) {\n const pageUrl = safePageUrl(input.pageUrl);\n if (pageUrl) result.pageUrl = pageUrl;\n }\n if (input.path !== undefined) {\n const path = input.path.trim().slice(0, 2_048);\n if (path) result.path = path;\n }\n if (input.title !== undefined) {\n result.title = input.title.trim().slice(0, 512);\n }\n if (input.referrer !== undefined) {\n result.referrer = input.referrer === null ? null : safeReferrer(input.referrer);\n }\n\n if (input.properties !== undefined) {\n const properties = toJsonValue(input.properties);\n if (\n !properties ||\n typeof properties !== \"object\" ||\n Array.isArray(properties) ||\n JSON.stringify(properties).length > MAX_EVENT_PROPERTIES_LENGTH\n ) {\n throw new Error(\"AdHub behavior properties must be a JSON object no larger than 32 KiB.\");\n }\n result.properties = properties;\n }\n\n return result;\n}\n\nexport function normalizePageviewFields(input: BrowserPageviewInput = {}): NormalizedPageviewFields {\n return {\n ...normalizeBehaviorEventFields({ eventName: \"pageview\", ...input }),\n eventName: \"pageview\",\n };\n}\n\nexport function sanitizeProfile(profile: IdentifyProfile): IdentifyProfile | null {\n const profileId = normalizeProfileId(profile.profileId);\n if (!profileId) return null;\n\n const result: IdentifyProfile = { profileId };\n if (profile.email?.trim()) result.email = profile.email.trim().slice(0, 320);\n if (profile.firstName?.trim()) result.firstName = profile.firstName.trim().slice(0, 200);\n if (profile.lastName?.trim()) result.lastName = profile.lastName.trim().slice(0, 200);\n if (profile.properties) {\n const properties = toJsonValue(profile.properties);\n if (\n properties &&\n typeof properties === \"object\" &&\n !Array.isArray(properties) &&\n JSON.stringify(properties).length <= 32_768\n ) {\n result.properties = properties;\n }\n }\n return result;\n}\n"]}
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.3.0";
462
+ var SDK_VERSION = "0.4.1";
387
463
  var REQUEST_TIMEOUT_MS = 5e3;
388
464
  var RETRY_INTERVAL_MS = 15e3;
389
465
  var PAGE_ENGAGEMENT_INTERVAL_MS = 5e3;
@@ -614,6 +690,9 @@ var AdHubBrowserClient = class {
614
690
  this.store = null;
615
691
  this.queue = [];
616
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;
617
696
  this.projectKey = "";
618
697
  this.debug = false;
619
698
  this.flushPromise = null;
@@ -696,6 +775,8 @@ var AdHubBrowserClient = class {
696
775
  }
697
776
  this.projectKey = projectKey;
698
777
  this.endpoint = endpoint;
778
+ this.cookieDomainOption = options.cookieDomain?.trim() || null;
779
+ this.endpointSharesCookies = false;
699
780
  this.debug = options.debug ?? false;
700
781
  this.waitForConsent = options.waitForConsent === true;
701
782
  this.autoFlush = options.autoFlush ?? true;
@@ -705,6 +786,9 @@ var AdHubBrowserClient = class {
705
786
  this.autoTrackDataAttributes = options.autoTrackDataAttributes ?? true;
706
787
  this.trackHashChanges = options.trackHashChanges ?? false;
707
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
+ }
708
792
  this.queue = this.store.loadQueue();
709
793
  this.sessionTimeoutMs = Number.isFinite(options.sessionTimeoutMinutes) ? Math.max(1, Math.min(24 * 60, options.sessionTimeoutMinutes ?? 30)) * 60 * 1e3 : DEFAULT_SESSION_TIMEOUT_MS;
710
794
  const anonymousId = this.store.readAnonymousId() ?? randomId("anon");
@@ -1091,7 +1175,7 @@ var AdHubBrowserClient = class {
1091
1175
  }),
1092
1176
  body: JSON.stringify(item.body),
1093
1177
  keepalive: true,
1094
- credentials: "omit",
1178
+ credentials: this.credentialsMode(),
1095
1179
  signal: controller.signal
1096
1180
  });
1097
1181
  if (response.ok) {
@@ -1157,7 +1241,7 @@ var AdHubBrowserClient = class {
1157
1241
  const response = await fetch(`${this.endpoint}${SDK_CONFIG_PATH}`, {
1158
1242
  method: "GET",
1159
1243
  headers: this.sdkHeaders(),
1160
- credentials: "omit",
1244
+ credentials: this.endpointIsSameOrigin() ? "same-origin" : "omit",
1161
1245
  signal: abort.signal
1162
1246
  });
1163
1247
  if (abort.signal.aborted) return;
@@ -1173,6 +1257,7 @@ var AdHubBrowserClient = class {
1173
1257
  return;
1174
1258
  }
1175
1259
  if (abort.signal.aborted) return;
1260
+ this.applyIdentityCookieDomain(payload);
1176
1261
  this.applyGoogleAdsWebsiteTag(payload);
1177
1262
  this.applyClarity(payload);
1178
1263
  } catch (error) {
@@ -1182,6 +1267,27 @@ var AdHubBrowserClient = class {
1182
1267
  clearTimeout(timeout);
1183
1268
  }
1184
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
+ }
1185
1291
  applyGoogleAdsWebsiteTag(payload) {
1186
1292
  const decision = decideGoogleAdsTag(payload);
1187
1293
  if (decision.action === "skip") return;