@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/README.md +49 -2
- package/dist/chunk-NF56G46G.js +140 -0
- package/dist/chunk-NF56G46G.js.map +1 -0
- package/dist/index.cjs +220 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -4
- package/dist/index.d.ts +13 -4
- package/dist/index.js +220 -25
- package/dist/index.js.map +1 -1
- package/dist/server.cjs +108 -34
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +5 -0
- package/dist/server.d.ts +5 -0
- package/dist/server.js +108 -34
- package/dist/server.js.map +1 -1
- package/dist/testing.cjs +149 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +6 -0
- package/dist/testing.d.ts +6 -0
- package/dist/testing.js +72 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-DMUJO8Kj.d.cts +62 -0
- package/dist/types-DMUJO8Kj.d.ts +62 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -44,7 +44,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
44
44
|
|
|
45
45
|
That completes the basic browser integration. With no `endpoint`, the SDK sends directly to `https://api.adhub.so`. It automatically captures landing parameters and pageviews, sends queued events, retries transient failures, and restores pending events after a reload.
|
|
46
46
|
|
|
47
|
-
If the AdHub project has a Google Ads website tag enabled, the SDK also loads that `AW-…` tag so Google can measure its own sessions and conversions. This is not AdSense, and it does not replace AdHub offline conversion uploads. Set `waitForConsent` when
|
|
47
|
+
If the AdHub project has a Google Ads website tag enabled, the SDK also loads that `AW-…` tag so Google can measure its own sessions and conversions. This is not AdSense, and it does not replace AdHub offline conversion uploads. If Microsoft Clarity is enabled for the project, the SDK loads that tag too. Set `waitForConsent` when those tags must wait for a consent choice. See [Google Ads website tag](#google-ads-website-tag) and [Microsoft Clarity](#microsoft-clarity).
|
|
48
48
|
|
|
49
49
|
Do not add a Route Handler or call `flush()` after every event for this setup.
|
|
50
50
|
|
|
@@ -106,7 +106,9 @@ Browser payloads can be modified by users. Trusted payment, refund, subscription
|
|
|
106
106
|
The minimal setup above does not require any of the following features. Use them only for a specific application requirement.
|
|
107
107
|
|
|
108
108
|
- [Google Ads website tag](#google-ads-website-tag) for consent, SPA page views, and the same-origin config proxy.
|
|
109
|
+
- [Microsoft Clarity](#microsoft-clarity) when the project enables Clarity session recordings.
|
|
109
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.
|
|
110
112
|
- [Capture before hydration](#capture-before-hydration) when application code removes attribution parameters before React hydrates.
|
|
111
113
|
- [Manual flush and queue control](#manual-flush-and-queue-control) for tests, diagnostics, or `autoFlush: false`.
|
|
112
114
|
- [Trusted server events](#trusted-server-events) for payments and other authoritative business facts.
|
|
@@ -125,7 +127,7 @@ After `init`, the SDK requests `GET /api/v1/saas/sdk/config`. When `googleAdsWeb
|
|
|
125
127
|
|
|
126
128
|
A disabled tag, a null conversion id, a non-OK response, or a network failure does not throw and does not block touchpoints, identity, pageviews, or events. The SDK writes an `[AdHub SDK]` console warning only when `debug` is on.
|
|
127
129
|
|
|
128
|
-
`waitForConsent` skips the config request
|
|
130
|
+
`waitForConsent` skips the config request, so neither this tag nor Microsoft Clarity is loaded. There is no consent callback. After the visitor allows the tags, call `init` again for the same project with `waitForConsent` omitted or `false` and the SDK loads them. A tag that was already injected is not removed.
|
|
129
131
|
|
|
130
132
|
```tsx
|
|
131
133
|
<AdHubComponent
|
|
@@ -136,6 +138,27 @@ A disabled tag, a null conversion id, a non-OK response, or a network failure do
|
|
|
136
138
|
|
|
137
139
|
Same-origin proxy mode must forward this GET. Export `GET` from the catch-all Route Handler as well as `POST` and `OPTIONS`. `script-src` must allow `https://www.googletagmanager.com` when the tag is enabled. Direct delivery to `https://api.adhub.so` does not need the Route Handler.
|
|
138
140
|
|
|
141
|
+
### Microsoft Clarity
|
|
142
|
+
|
|
143
|
+
The same `GET /api/v1/saas/sdk/config` response may include `clarity`. When `clarity.enabled` is true and `clarity.projectId` is the Clarity project id, the SDK installs Microsoft's tag once for the page:
|
|
144
|
+
|
|
145
|
+
```js
|
|
146
|
+
(function(c,l,a,r,i,t,y){
|
|
147
|
+
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
|
|
148
|
+
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
|
|
149
|
+
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
|
|
150
|
+
})(window, document, "clarity", "script", PROJECT_ID);
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
- An existing `window.clarity` is reused. Otherwise the SDK defines the standard queue function.
|
|
154
|
+
- `https://www.clarity.ms/tag/<projectId>` is inserted once, before the first script tag (or appended when the page has none), and marked with `data-adhub-clarity`. A script whose `src` is already that URL is left in place. A Clarity script for a different project is also left in place; the SDK does not add a second tag.
|
|
155
|
+
- Injection is idempotent. `window.__ADHUB_CLARITY__` records `{ projectId }`, so a later `init` on the same page does not insert another script.
|
|
156
|
+
- `identify()` calls `clarity('identify', profileId)` when `window.clarity` is available. Only the AdHub profile id is sent. Email and name are not.
|
|
157
|
+
|
|
158
|
+
A disabled tag, a missing or invalid project id, a non-OK response, or a network failure does not throw and does not block touchpoints, identity, pageviews, or events. The SDK writes an `[AdHub SDK]` console warning only when `debug` is on.
|
|
159
|
+
|
|
160
|
+
`waitForConsent` skips the shared config request, so Clarity waits along with the Google Ads tag. `script-src` must allow `https://www.clarity.ms` when the tag is enabled. Clarity also sends its own beacons to `https://*.clarity.ms`.
|
|
161
|
+
|
|
139
162
|
### First-party Route Handler
|
|
140
163
|
|
|
141
164
|
This is an optional delivery mode, not a prerequisite for using the browser SDK. Direct delivery already gives AdHub the browser connection IP, User-Agent, and site Origin.
|
|
@@ -148,6 +171,7 @@ The optional Route Handler can provide:
|
|
|
148
171
|
- Vercel, Cloudflare, or CloudFront geo headers available at the customer's edge.
|
|
149
172
|
- A centralized self-hosted, regional, or test AdHub API target through `apiUrl`.
|
|
150
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.
|
|
151
175
|
|
|
152
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.
|
|
153
177
|
|
|
@@ -177,6 +201,29 @@ The handler preserves the original Origin, User-Agent, client IP, supported edge
|
|
|
177
201
|
|
|
178
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.
|
|
179
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
|
+
|
|
180
227
|
### Capture before hydration
|
|
181
228
|
|
|
182
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,GAAm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EAAoE,CAAA;AAAA,IACtF;AACA,IAAA,MAAA,CAAO,OAAA,GAAU,OAAA;AAAA,EACnB;AAEA,EAAA,IAAI,KAAA,CAAM,UAAU,MAAA,EAAW;AAC7B,IAAA,IAAI,CAAC,OAAO,QAAA,CAAS,KAAA,CAAM,KAAK,CAAA,IAAK,KAAA,CAAM,QAAQ,CAAA,EAAG;AACpD,MAAA,MAAM,IAAI,MAAM,yDAAyD,CAAA;AAAA,IAC3E;AACA,IAAA,MAAA,CAAO,QAAQ,KAAA,CAAM,KAAA;AAAA,EACvB;AAEA,EAAA,IAAI,KAAA,CAAM,aAAa,MAAA,EAAW;AAChC,IAAA,MAAM,QAAA,GAAW,KAAA,CAAM,QAAA,CAAS,IAAA,GAAO,WAAA,EAAY;AACnD,IAAA,IAAI,CAAC,YAAA,CAAa,IAAA,CAAK,QAAQ,CAAA,EAAG;AAChC,MAAA,MAAM,IAAI,MAAM,4DAA4D,CAAA;AAAA,IAC9E;AACA,IAAA,MAAA,CAAO,QAAA,GAAW,QAAA;AAAA,EACpB;AAEA,EAAA,IAAI,KAAA,CAAM,eAAe,MAAA,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"]}
|