@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/README.md +205 -0
- package/dist/chunk-NF56G46G.js +140 -0
- package/dist/chunk-NF56G46G.js.map +1 -0
- package/dist/index.cjs +1206 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +133 -0
- package/dist/index.d.ts +133 -0
- package/dist/index.js +1178 -0
- package/dist/index.js.map +1 -0
- package/dist/server.cjs +358 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.d.cts +84 -0
- package/dist/server.d.ts +84 -0
- package/dist/server.js +275 -0
- package/dist/server.js.map +1 -0
- 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 +63 -0
package/README.md
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
# AdHub Next.js SDK
|
|
2
|
+
|
|
3
|
+
`@adhub-so/adhub-nextjs-sdk` is AdHub's first-party SDK for Next.js. It captures Google Ads landing touchpoints, maintains anonymous and authenticated identity, records page and product behavior, sends browser business events, and proxies requests through a Next.js Route Handler so AdHub receives the original browser IP, user agent, and edge geo headers.
|
|
4
|
+
|
|
5
|
+
This package targets Next.js only. It does not publish a framework-neutral browser entry, SPA bootstrap API, or global IIFE bundle.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @adhub-so/adhub-nextjs-sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
For a local sibling checkout:
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@adhub-so/adhub-nextjs-sdk": "file:../adhub-nextjs-sdk"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## App Router setup
|
|
24
|
+
|
|
25
|
+
### 1. Add the component
|
|
26
|
+
|
|
27
|
+
Render `AdHubComponent` once in the root layout. A relative `endpoint` sends browser requests through your own Next.js origin, which improves delivery and preserves the real browser context through the Route Handler in the next step.
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
// app/layout.tsx
|
|
31
|
+
import { AdHubComponent } from "@adhub-so/adhub-nextjs-sdk";
|
|
32
|
+
|
|
33
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
34
|
+
return (
|
|
35
|
+
<html lang="en">
|
|
36
|
+
<body>
|
|
37
|
+
<AdHubComponent
|
|
38
|
+
projectKey={process.env.NEXT_PUBLIC_ADHUB_PROJECT_KEY!}
|
|
39
|
+
endpoint="/api/adhub"
|
|
40
|
+
/>
|
|
41
|
+
{children}
|
|
42
|
+
</body>
|
|
43
|
+
</html>
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The Project key is a public browser identifier. Never pass an ingestion key or another server secret to `AdHubComponent` or a `NEXT_PUBLIC_*` environment variable.
|
|
49
|
+
|
|
50
|
+
If authenticated profile data is already available to the layout, it can be supplied as a serializable prop:
|
|
51
|
+
|
|
52
|
+
```tsx
|
|
53
|
+
<AdHubComponent
|
|
54
|
+
projectKey={process.env.NEXT_PUBLIC_ADHUB_PROJECT_KEY!}
|
|
55
|
+
endpoint="/api/adhub"
|
|
56
|
+
profile={{ profileId: user.id, email: user.email }}
|
|
57
|
+
/>
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`profileId` can be passed directly when no other profile fields are needed. Changing directly from one non-null profile to another rotates the browser identity boundary before identifying the next user. Passing `null` resets the authenticated identity while retaining a new anonymous browser identity.
|
|
61
|
+
|
|
62
|
+
### 2. Add the Route Handler
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
// app/api/adhub/[...path]/route.ts
|
|
66
|
+
import { createRouteHandler } from "@adhub-so/adhub-nextjs-sdk/server";
|
|
67
|
+
|
|
68
|
+
export const runtime = "nodejs";
|
|
69
|
+
|
|
70
|
+
const handler = createRouteHandler({
|
|
71
|
+
apiUrl: process.env.ADHUB_API_URL ?? "https://api.adhub.so",
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
export const { POST, OPTIONS } = handler;
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The handler only forwards the supported SDK ingestion paths. It carries the original `Origin`, `User-Agent`, client IP, country, region, city, project key, idempotency key, SDK name, and SDK version to AdHub. It does not proxy general SaaS APIs.
|
|
78
|
+
|
|
79
|
+
### 3. Track from Client Components
|
|
80
|
+
|
|
81
|
+
`useAdHub()` is the client API for Next.js Client Components. It exposes a reactive `state` plus identity, page, behavior, event, reset, and flush actions.
|
|
82
|
+
|
|
83
|
+
```tsx
|
|
84
|
+
"use client";
|
|
85
|
+
|
|
86
|
+
import { useAdHub } from "@adhub-so/adhub-nextjs-sdk";
|
|
87
|
+
|
|
88
|
+
export function SignupButton({ userId }: { userId: string }) {
|
|
89
|
+
const adhub = useAdHub();
|
|
90
|
+
|
|
91
|
+
async function completeSignup() {
|
|
92
|
+
const currentProfileId = adhub.getState().profileId;
|
|
93
|
+
if (currentProfileId && currentProfileId !== userId) adhub.reset();
|
|
94
|
+
if (adhub.getState().profileId !== userId) {
|
|
95
|
+
adhub.identify({ profileId: userId });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
adhub.track({ eventType: "signup.completed" });
|
|
99
|
+
await adhub.flush();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return <button onClick={() => void completeSignup()}>Create account</button>;
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Use `behavior()` for non-sensitive product analytics and `track()` for configured AdHub business events:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
adhub.behavior({
|
|
110
|
+
eventName: "pricing_cta_clicked",
|
|
111
|
+
properties: { plan: "growth" },
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
adhub.track({
|
|
115
|
+
eventType: "purchase",
|
|
116
|
+
eventId: `order:${order.id}`,
|
|
117
|
+
value: order.total,
|
|
118
|
+
currency: order.currency,
|
|
119
|
+
});
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Browser `track()` requires an identified profile. Trusted payment, refund, and subscription facts should normally be sent from the server instead.
|
|
123
|
+
|
|
124
|
+
## Capture before hydration
|
|
125
|
+
|
|
126
|
+
Next.js 15.3 and newer can initialize AdHub synchronously from `instrumentation-client.ts`. Use this advanced setup when application code may remove attribution query parameters before React hydrates. In that case, use `initAdHub()` here instead of relying on `AdHubComponent` to initialize.
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
// src/instrumentation-client.ts
|
|
130
|
+
import { initAdHub } from "@adhub-so/adhub-nextjs-sdk";
|
|
131
|
+
|
|
132
|
+
initAdHub({
|
|
133
|
+
projectKey: process.env.NEXT_PUBLIC_ADHUB_PROJECT_KEY!,
|
|
134
|
+
endpoint: "/api/adhub",
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Only synchronous top-level work in `instrumentation-client.ts` is guaranteed to complete before hydration. `initAdHub()` captures and persists the landing touchpoint synchronously; network delivery remains queued and asynchronous.
|
|
139
|
+
|
|
140
|
+
## Server events
|
|
141
|
+
|
|
142
|
+
Import trusted server functionality only from `@adhub-so/adhub-nextjs-sdk/server` so ingestion credentials cannot enter the client module graph.
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
import { createAdHubServerClient } from "@adhub-so/adhub-nextjs-sdk/server";
|
|
146
|
+
|
|
147
|
+
const adhub = createAdHubServerClient({
|
|
148
|
+
projectKey: process.env.ADHUB_PROJECT_KEY!,
|
|
149
|
+
ingestionKey: process.env.ADHUB_INGESTION_KEY!,
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
await adhub.track({
|
|
153
|
+
eventType: "purchase",
|
|
154
|
+
profileId: payment.userId,
|
|
155
|
+
eventId: `payment:${payment.id}`,
|
|
156
|
+
occurredAt: payment.paidAt.toISOString(),
|
|
157
|
+
value: payment.amount,
|
|
158
|
+
currency: payment.currency,
|
|
159
|
+
properties: { orderId: payment.orderId },
|
|
160
|
+
});
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`eventId` is required for trusted server events and is used as the idempotency key. Reuse the same ID for retries of the same business fact.
|
|
164
|
+
|
|
165
|
+
When a trusted event is sent during an OAuth callback, pass the anonymous ID
|
|
166
|
+
that this SDK persisted in the browser cookie. AdHub will claim that anonymous
|
|
167
|
+
identity for the profile before attributing the event:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
import {
|
|
171
|
+
createAdHubServerClient,
|
|
172
|
+
readAdHubAnonymousId,
|
|
173
|
+
} from "@adhub-so/adhub-nextjs-sdk/server";
|
|
174
|
+
|
|
175
|
+
const adhub = createAdHubServerClient({
|
|
176
|
+
projectKey: process.env.ADHUB_PROJECT_KEY!,
|
|
177
|
+
ingestionKey: process.env.ADHUB_INGESTION_KEY!,
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
await adhub.track({
|
|
181
|
+
eventType: process.env.ADHUB_SIGNUP_EVENT_TYPE_ID!,
|
|
182
|
+
profileId: user.id,
|
|
183
|
+
anonymousId: readAdHubAnonymousId(request.headers.get("cookie"), process.env.ADHUB_PROJECT_KEY!),
|
|
184
|
+
eventId: `signup:${user.id}`,
|
|
185
|
+
occurredAt: user.created_at,
|
|
186
|
+
});
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Attribution testing
|
|
190
|
+
|
|
191
|
+
AdHub's dashboard can create zero-write preview envelopes through the explicit testing entry:
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
import { createAttributionTestEnvelopes } from "@adhub-so/adhub-nextjs-sdk/testing";
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
This helper does not initialize browser tracking, modify storage, or send network requests.
|
|
198
|
+
|
|
199
|
+
## Public entries
|
|
200
|
+
|
|
201
|
+
- `@adhub-so/adhub-nextjs-sdk`: `AdHubComponent`, `initAdHub`, `useAdHub`, and client-side types.
|
|
202
|
+
- `@adhub-so/adhub-nextjs-sdk/server`: `createRouteHandler`, `createAdHubServerClient`, server payload helpers, errors, and server types.
|
|
203
|
+
- `@adhub-so/adhub-nextjs-sdk/testing`: the dashboard attribution-test envelope helper and its types.
|
|
204
|
+
|
|
205
|
+
The package does not expose `./browser`, redundant framework subpaths, a global IIFE, a client factory, or generic singleton event functions. Browser operations stay behind the Next.js component, initialization entry, and client Hook.
|
|
@@ -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
|
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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"]}
|