@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.
@@ -0,0 +1,84 @@
1
+ import { J as JsonObject } from './types-DMUJO8Kj.cjs';
2
+
3
+ interface AdHubNextRouteHandlerOptions {
4
+ apiUrl?: string;
5
+ }
6
+ type AdHubNextRouteHandler = ((request: Request) => Promise<Response>) & {
7
+ POST: (request: Request) => Promise<Response>;
8
+ OPTIONS: () => Promise<Response>;
9
+ };
10
+ declare function createRouteHandler(options?: AdHubNextRouteHandlerOptions): AdHubNextRouteHandler;
11
+
12
+ declare function getAdHubAnonymousIdCookieName(projectKey: string): string;
13
+
14
+ interface AdHubServerClientOptions {
15
+ projectKey: string;
16
+ ingestionKey: string;
17
+ endpoint?: string;
18
+ timeoutMs?: number;
19
+ fetch?: typeof globalThis.fetch;
20
+ }
21
+ interface ServerEventInput {
22
+ eventType: string;
23
+ profileId: string;
24
+ anonymousId?: string;
25
+ eventId: string;
26
+ occurredAt?: string;
27
+ value?: number;
28
+ currency?: string;
29
+ properties?: Record<string, unknown>;
30
+ }
31
+ interface ServerEventPayload {
32
+ project: string;
33
+ profileId: string;
34
+ anonymousId?: string;
35
+ eventDefinitionId?: string;
36
+ eventKey?: string;
37
+ eventId: string;
38
+ occurredAt: string;
39
+ value?: number;
40
+ currency?: string;
41
+ properties?: JsonObject;
42
+ }
43
+ interface ServerEventDeliveryResult {
44
+ bindingId: string;
45
+ advertisingAccountId: string;
46
+ conversionActionId: string;
47
+ status: string;
48
+ googleRequestId?: string | null;
49
+ errorCode?: string | null;
50
+ errorMessage?: string | null;
51
+ retryable?: boolean;
52
+ outcomeUnknown?: boolean;
53
+ }
54
+ interface ServerEventTrackResult {
55
+ eventId: string;
56
+ externalEventId: string;
57
+ attributionStatus: string;
58
+ attributionReason?: string | null;
59
+ deliveryStatus?: string | null;
60
+ googleRequestId?: string | null;
61
+ duplicate?: boolean;
62
+ deliveries?: ServerEventDeliveryResult[];
63
+ }
64
+ interface AdHubServerClient {
65
+ track(event: ServerEventInput): Promise<ServerEventTrackResult>;
66
+ }
67
+ declare class AdHubServerError extends Error {
68
+ readonly status: number;
69
+ readonly code: string | null;
70
+ readonly retryable: boolean;
71
+ readonly outcomeUnknown: boolean;
72
+ constructor(message: string, options: {
73
+ status: number;
74
+ code?: string | null;
75
+ retryable?: boolean;
76
+ outcomeUnknown?: boolean;
77
+ });
78
+ }
79
+ declare function createServerEventPayload(projectKey: string, input: ServerEventInput): ServerEventPayload;
80
+ declare function createAdHubServerClient(options: AdHubServerClientOptions): AdHubServerClient;
81
+
82
+ declare function readAdHubAnonymousId(cookieHeader: string | null | undefined, projectKey: string): string | null;
83
+
84
+ export { type AdHubNextRouteHandlerOptions, type AdHubServerClient, type AdHubServerClientOptions, AdHubServerError, type ServerEventDeliveryResult, type ServerEventInput, type ServerEventPayload, type ServerEventTrackResult, createAdHubServerClient, createRouteHandler, createServerEventPayload, getAdHubAnonymousIdCookieName, readAdHubAnonymousId };
@@ -0,0 +1,84 @@
1
+ import { J as JsonObject } from './types-DMUJO8Kj.js';
2
+
3
+ interface AdHubNextRouteHandlerOptions {
4
+ apiUrl?: string;
5
+ }
6
+ type AdHubNextRouteHandler = ((request: Request) => Promise<Response>) & {
7
+ POST: (request: Request) => Promise<Response>;
8
+ OPTIONS: () => Promise<Response>;
9
+ };
10
+ declare function createRouteHandler(options?: AdHubNextRouteHandlerOptions): AdHubNextRouteHandler;
11
+
12
+ declare function getAdHubAnonymousIdCookieName(projectKey: string): string;
13
+
14
+ interface AdHubServerClientOptions {
15
+ projectKey: string;
16
+ ingestionKey: string;
17
+ endpoint?: string;
18
+ timeoutMs?: number;
19
+ fetch?: typeof globalThis.fetch;
20
+ }
21
+ interface ServerEventInput {
22
+ eventType: string;
23
+ profileId: string;
24
+ anonymousId?: string;
25
+ eventId: string;
26
+ occurredAt?: string;
27
+ value?: number;
28
+ currency?: string;
29
+ properties?: Record<string, unknown>;
30
+ }
31
+ interface ServerEventPayload {
32
+ project: string;
33
+ profileId: string;
34
+ anonymousId?: string;
35
+ eventDefinitionId?: string;
36
+ eventKey?: string;
37
+ eventId: string;
38
+ occurredAt: string;
39
+ value?: number;
40
+ currency?: string;
41
+ properties?: JsonObject;
42
+ }
43
+ interface ServerEventDeliveryResult {
44
+ bindingId: string;
45
+ advertisingAccountId: string;
46
+ conversionActionId: string;
47
+ status: string;
48
+ googleRequestId?: string | null;
49
+ errorCode?: string | null;
50
+ errorMessage?: string | null;
51
+ retryable?: boolean;
52
+ outcomeUnknown?: boolean;
53
+ }
54
+ interface ServerEventTrackResult {
55
+ eventId: string;
56
+ externalEventId: string;
57
+ attributionStatus: string;
58
+ attributionReason?: string | null;
59
+ deliveryStatus?: string | null;
60
+ googleRequestId?: string | null;
61
+ duplicate?: boolean;
62
+ deliveries?: ServerEventDeliveryResult[];
63
+ }
64
+ interface AdHubServerClient {
65
+ track(event: ServerEventInput): Promise<ServerEventTrackResult>;
66
+ }
67
+ declare class AdHubServerError extends Error {
68
+ readonly status: number;
69
+ readonly code: string | null;
70
+ readonly retryable: boolean;
71
+ readonly outcomeUnknown: boolean;
72
+ constructor(message: string, options: {
73
+ status: number;
74
+ code?: string | null;
75
+ retryable?: boolean;
76
+ outcomeUnknown?: boolean;
77
+ });
78
+ }
79
+ declare function createServerEventPayload(projectKey: string, input: ServerEventInput): ServerEventPayload;
80
+ declare function createAdHubServerClient(options: AdHubServerClientOptions): AdHubServerClient;
81
+
82
+ declare function readAdHubAnonymousId(cookieHeader: string | null | undefined, projectKey: string): string | null;
83
+
84
+ export { type AdHubNextRouteHandlerOptions, type AdHubServerClient, type AdHubServerClientOptions, AdHubServerError, type ServerEventDeliveryResult, type ServerEventInput, type ServerEventPayload, type ServerEventTrackResult, createAdHubServerClient, createRouteHandler, createServerEventPayload, getAdHubAnonymousIdCookieName, readAdHubAnonymousId };
package/dist/server.js ADDED
@@ -0,0 +1,275 @@
1
+ import { normalizeProfileId, isUuid, normalizeEventFields } from './chunk-NF56G46G.js';
2
+
3
+ // src/nextjs.ts
4
+ var DEFAULT_API_URL = "https://api.adhub.so";
5
+ var SDK_PATH_PREFIX = "/api/v1/saas/sdk/";
6
+ var SDK_PATHS = /* @__PURE__ */ new Set([
7
+ `${SDK_PATH_PREFIX}touchpoints`,
8
+ `${SDK_PATH_PREFIX}identify`,
9
+ `${SDK_PATH_PREFIX}behavior-events`,
10
+ `${SDK_PATH_PREFIX}page-engagements`,
11
+ `${SDK_PATH_PREFIX}events`
12
+ ]);
13
+ function normalizedApiUrl(value) {
14
+ const url = new URL(value?.trim() || DEFAULT_API_URL);
15
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
16
+ throw new TypeError("AdHub Next.js apiUrl must use HTTP or HTTPS.");
17
+ }
18
+ return url.toString().replace(/\/$/, "");
19
+ }
20
+ function sdkPath(request) {
21
+ const pathname = new URL(request.url).pathname;
22
+ const prefixIndex = pathname.indexOf(SDK_PATH_PREFIX);
23
+ if (prefixIndex < 0) return null;
24
+ const path = pathname.slice(prefixIndex);
25
+ return SDK_PATHS.has(path) ? path : null;
26
+ }
27
+ function firstForwardedValue(value) {
28
+ return value?.split(",", 1)[0]?.trim() || null;
29
+ }
30
+ function firstHeader(request, names) {
31
+ for (const name of names) {
32
+ const value = request.headers.get(name)?.trim();
33
+ if (value) return value;
34
+ }
35
+ return null;
36
+ }
37
+ function clientHeaders(request) {
38
+ const headers = new Headers({ "Content-Type": "application/json" });
39
+ const sourceUrl = new URL(request.url);
40
+ const origin = request.headers.get("origin") || `${sourceUrl.protocol}//${sourceUrl.host}`;
41
+ const userAgent = request.headers.get("user-agent");
42
+ const clientIp = firstHeader(request, ["cf-connecting-ip", "true-client-ip"]) || firstForwardedValue(request.headers.get("x-forwarded-for")) || firstForwardedValue(request.headers.get("x-vercel-forwarded-for")) || request.headers.get("x-real-ip");
43
+ const country = firstHeader(request, [
44
+ "cf-ipcountry",
45
+ "x-vercel-ip-country",
46
+ "cloudfront-viewer-country"
47
+ ]);
48
+ const region = firstHeader(request, ["x-vercel-ip-country-region"]);
49
+ const city = firstHeader(request, ["x-vercel-ip-city"]);
50
+ headers.set("Origin", origin);
51
+ if (userAgent) headers.set("User-Agent", userAgent);
52
+ if (clientIp) headers.set("X-AdHub-Client-IP", clientIp);
53
+ if (country) headers.set("X-AdHub-Client-Country", country);
54
+ if (region) headers.set("X-AdHub-Client-Region", region);
55
+ if (city) headers.set("X-AdHub-Client-City", city);
56
+ for (const name of [
57
+ "Idempotency-Key",
58
+ "X-AdHub-Project-Key",
59
+ "X-AdHub-SDK",
60
+ "X-AdHub-SDK-Version"
61
+ ]) {
62
+ const value = request.headers.get(name);
63
+ if (value) headers.set(name, value);
64
+ }
65
+ return headers;
66
+ }
67
+ function createRouteHandler(options = {}) {
68
+ const apiUrl = normalizedApiUrl(options.apiUrl);
69
+ const handler = (async (request) => {
70
+ const path = sdkPath(request);
71
+ if (request.method !== "POST" || !path) {
72
+ return Response.json({ error: "Not found" }, { status: 404 });
73
+ }
74
+ try {
75
+ const response = await fetch(`${apiUrl}${path}`, {
76
+ method: "POST",
77
+ headers: clientHeaders(request),
78
+ body: await request.text()
79
+ });
80
+ const responseHeaders = new Headers();
81
+ const contentType = response.headers.get("content-type");
82
+ const retryAfter = response.headers.get("retry-after");
83
+ if (contentType) responseHeaders.set("Content-Type", contentType);
84
+ if (retryAfter) responseHeaders.set("Retry-After", retryAfter);
85
+ return new Response(await response.arrayBuffer(), {
86
+ status: response.status,
87
+ headers: responseHeaders
88
+ });
89
+ } catch (error) {
90
+ return Response.json(
91
+ {
92
+ error: "Failed to proxy AdHub SDK request",
93
+ message: error instanceof Error ? error.message : String(error)
94
+ },
95
+ { status: 502 }
96
+ );
97
+ }
98
+ });
99
+ handler.POST = handler;
100
+ handler.OPTIONS = async () => new Response(null, {
101
+ status: 204,
102
+ headers: { Allow: "POST, OPTIONS" }
103
+ });
104
+ return handler;
105
+ }
106
+
107
+ // src/identity-cookie.ts
108
+ var COOKIE_PREFIX = "adhub_project_anonymous_id_";
109
+ function hashKey(input) {
110
+ let hash = 2166136261;
111
+ for (let index = 0; index < input.length; index += 1) {
112
+ hash ^= input.charCodeAt(index);
113
+ hash = Math.imul(hash, 16777619);
114
+ }
115
+ return (hash >>> 0).toString(36);
116
+ }
117
+ function validAnonymousId(value) {
118
+ return value !== null && value.length >= 8 && value.length <= 255 && !/\s/.test(value);
119
+ }
120
+ function getAdHubAnonymousIdCookieName(projectKey) {
121
+ return `${COOKIE_PREFIX}${hashKey(projectKey.trim())}`;
122
+ }
123
+ function readAdHubAnonymousIdFromCookie(cookieHeader, projectKey) {
124
+ if (!cookieHeader) return null;
125
+ const cookieName = getAdHubAnonymousIdCookieName(projectKey);
126
+ for (const part of cookieHeader.split(";")) {
127
+ const [rawName, ...rawValue] = part.trim().split("=");
128
+ if (rawName !== cookieName) continue;
129
+ try {
130
+ const value = decodeURIComponent(rawValue.join("="));
131
+ return validAnonymousId(value) ? value : null;
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+ return null;
137
+ }
138
+
139
+ // src/server.ts
140
+ var DEFAULT_ENDPOINT = "https://api.adhub.so";
141
+ var DEFAULT_TIMEOUT_MS = 1e4;
142
+ var AdHubServerError = class extends Error {
143
+ constructor(message, options) {
144
+ super(message);
145
+ this.name = "AdHubServerError";
146
+ this.status = options.status;
147
+ this.code = options.code ?? null;
148
+ this.retryable = options.retryable ?? false;
149
+ this.outcomeUnknown = options.outcomeUnknown ?? false;
150
+ }
151
+ };
152
+ function normalizeEndpoint(endpoint) {
153
+ let parsed;
154
+ try {
155
+ parsed = new URL(endpoint?.trim() || DEFAULT_ENDPOINT);
156
+ } catch {
157
+ throw new Error("AdHub server endpoint must be a valid HTTP(S) URL.");
158
+ }
159
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
160
+ throw new Error("AdHub server endpoint must be a valid HTTP(S) URL.");
161
+ }
162
+ return parsed.toString().replace(/\/$/, "");
163
+ }
164
+ function createServerEventPayload(projectKey, input) {
165
+ const normalizedProjectKey = projectKey.trim();
166
+ const profileId = normalizeProfileId(input.profileId);
167
+ if (!isUuid(normalizedProjectKey)) {
168
+ throw new Error("AdHub server projectKey must be a UUID.");
169
+ }
170
+ if (!profileId) {
171
+ throw new Error(
172
+ "AdHub server profileId must be 1-255 characters without control characters."
173
+ );
174
+ }
175
+ const normalized = normalizeEventFields(input);
176
+ if (!normalized.eventId) {
177
+ throw new Error("AdHub server eventId is required.");
178
+ }
179
+ const payload = {
180
+ project: normalizedProjectKey,
181
+ profileId,
182
+ eventId: normalized.eventId,
183
+ occurredAt: normalized.occurredAt
184
+ };
185
+ if (input.anonymousId !== void 0) payload.anonymousId = input.anonymousId;
186
+ if (isUuid(normalized.eventType)) payload.eventDefinitionId = normalized.eventType;
187
+ else payload.eventKey = normalized.eventType;
188
+ if (normalized.value !== void 0) payload.value = normalized.value;
189
+ if (normalized.currency !== void 0) payload.currency = normalized.currency;
190
+ if (normalized.properties !== void 0) payload.properties = normalized.properties;
191
+ return payload;
192
+ }
193
+ function errorDetails(value, status) {
194
+ const envelope = value && typeof value === "object" ? value : {};
195
+ const error = envelope.error;
196
+ const message = typeof error?.message === "string" ? error.message : `AdHub server endpoint returned HTTP ${status}.`;
197
+ return new AdHubServerError(message, {
198
+ status,
199
+ code: typeof error?.code === "string" ? error.code : null,
200
+ retryable: error?.retryable === true,
201
+ outcomeUnknown: error?.outcome_unknown === true || error?.outcomeUnknown === true
202
+ });
203
+ }
204
+ async function readJson(response) {
205
+ try {
206
+ return await response.json();
207
+ } catch {
208
+ return void 0;
209
+ }
210
+ }
211
+ var DefaultAdHubServerClient = class {
212
+ constructor(options) {
213
+ this.projectKey = options.projectKey.trim();
214
+ if (!isUuid(this.projectKey)) {
215
+ throw new Error("AdHub server projectKey must be a UUID.");
216
+ }
217
+ this.ingestionKey = options.ingestionKey.trim();
218
+ if (!this.ingestionKey || this.ingestionKey.length > 4096) {
219
+ throw new Error("AdHub server ingestionKey is required.");
220
+ }
221
+ this.endpoint = normalizeEndpoint(options.endpoint);
222
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
223
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 3e5) {
224
+ throw new Error("AdHub server timeoutMs must be between 1 and 300000.");
225
+ }
226
+ const fetchImpl = options.fetch ?? globalThis.fetch;
227
+ if (typeof fetchImpl !== "function") {
228
+ throw new Error("AdHub server client requires a Fetch API implementation.");
229
+ }
230
+ this.fetchImpl = fetchImpl;
231
+ }
232
+ async track(event) {
233
+ const payload = createServerEventPayload(this.projectKey, event);
234
+ const controller = new AbortController();
235
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
236
+ let response;
237
+ try {
238
+ response = await this.fetchImpl(`${this.endpoint}/api/v1/saas/events/track`, {
239
+ method: "POST",
240
+ headers: {
241
+ "Authorization": `Bearer ${this.ingestionKey}`,
242
+ "Content-Type": "application/json",
243
+ "Idempotency-Key": payload.eventId
244
+ },
245
+ body: JSON.stringify(payload),
246
+ signal: controller.signal
247
+ });
248
+ } catch (error) {
249
+ if (error instanceof AdHubServerError) throw error;
250
+ const message = error instanceof Error ? error.message : "AdHub server request failed.";
251
+ throw new AdHubServerError(message, { status: 0, retryable: true });
252
+ } finally {
253
+ clearTimeout(timeout);
254
+ }
255
+ const result = await readJson(response);
256
+ if (!response.ok) throw errorDetails(result, response.status);
257
+ if (!result || typeof result !== "object" || Array.isArray(result)) {
258
+ throw new AdHubServerError("AdHub server returned an invalid event response.", {
259
+ status: response.status,
260
+ retryable: response.status >= 500
261
+ });
262
+ }
263
+ return result;
264
+ }
265
+ };
266
+ function createAdHubServerClient(options) {
267
+ return new DefaultAdHubServerClient(options);
268
+ }
269
+ function readAdHubAnonymousId(cookieHeader, projectKey) {
270
+ return readAdHubAnonymousIdFromCookie(cookieHeader, projectKey);
271
+ }
272
+
273
+ export { AdHubServerError, createAdHubServerClient, createRouteHandler, createServerEventPayload, getAdHubAnonymousIdCookieName, readAdHubAnonymousId };
274
+ //# sourceMappingURL=server.js.map
275
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/nextjs.ts","../src/identity-cookie.ts","../src/server.ts"],"names":[],"mappings":";;;AASA,IAAM,eAAA,GAAkB,sBAAA;AACxB,IAAM,eAAA,GAAkB,mBAAA;AACxB,IAAM,SAAA,uBAAgB,GAAA,CAAI;AAAA,EACxB,GAAG,eAAe,CAAA,WAAA,CAAA;AAAA,EAClB,GAAG,eAAe,CAAA,QAAA,CAAA;AAAA,EAClB,GAAG,eAAe,CAAA,eAAA,CAAA;AAAA,EAClB,GAAG,eAAe,CAAA,gBAAA,CAAA;AAAA,EAClB,GAAG,eAAe,CAAA,MAAA;AACpB,CAAC,CAAA;AAED,SAAS,iBAAiB,KAAA,EAAmC;AAC3D,EAAA,MAAM,MAAM,IAAI,GAAA,CAAI,KAAA,EAAO,IAAA,MAAU,eAAe,CAAA;AACpD,EAAA,IAAI,GAAA,CAAI,QAAA,KAAa,QAAA,IAAY,GAAA,CAAI,aAAa,OAAA,EAAS;AACzD,IAAA,MAAM,IAAI,UAAU,8CAA8C,CAAA;AAAA,EACpE;AACA,EAAA,OAAO,GAAA,CAAI,QAAA,EAAS,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AACzC;AAEA,SAAS,QAAQ,OAAA,EAAiC;AAChD,EAAA,MAAM,QAAA,GAAW,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA,CAAE,QAAA;AACtC,EAAA,MAAM,WAAA,GAAc,QAAA,CAAS,OAAA,CAAQ,eAAe,CAAA;AACpD,EAAA,IAAI,WAAA,GAAc,GAAG,OAAO,IAAA;AAC5B,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,KAAA,CAAM,WAAW,CAAA;AACvC,EAAA,OAAO,SAAA,CAAU,GAAA,CAAI,IAAI,CAAA,GAAI,IAAA,GAAO,IAAA;AACtC;A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SAC7B;AAAA,QACA,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,OAAO,CAAA;AAAA,QAC5B,QAAQ,UAAA,CAAW;AAAA,OACpB,CAAA;AAAA,IACH,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,KAAA,YAAiB,kBAAkB,MAAM,KAAA;AAC7C,MAAA,MAAM,OAAA,GAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,8BAAA;AACzD,MAAA,MAAM,IAAI,iBAAiB,OAAA,EAAS,EAAE,QAAQ,CAAA,EAAG,SAAA,EAAW,MAAM,CAAA;AAAA,IACpE,CAAA,SAAE;AACA,MAAA,YAAA,CAAa,OAAO,CAAA;AAAA,IACtB;AAEA,IAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,QAAQ,CAAA;AACtC,IAAA,IAAI,CAAC,QAAA,CAAS,EAAA,QAAU,YAAA,CAAa,MAAA,EAAQ,SAAS,MAAM,CAAA;AAC5D,IAAA,IAAI,CAAC,UAAU,OAAO,MAAA,KAAW,YAAY,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,EAAG;AAClE,MAAA,MAAM,IAAI,iBAAiB,kDAAA,EAAoD;AAAA,QAC7E,QAAQ,QAAA,CAAS,MAAA;AAAA,QACjB,SAAA,EAAW,SAAS,MAAA,IAAU;AAAA,OAC/B,CAAA;AAAA,IACH;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF,CAAA;AAEO,SAAS,wBAAwB,OAAA,EAAsD;AAC5F,EAAA,OAAO,IAAI,yBAAyB,OAAO,CAAA;AAC7C;AAIO,SAAS,oBAAA,CACd,cACA,UAAA,EACe;AACf,EAAA,OAAO,8BAAA,CAA+B,cAAc,UAAU,CAAA;AAChE","file":"server.js","sourcesContent":["export interface AdHubNextRouteHandlerOptions {\n apiUrl?: string;\n}\n\ntype AdHubNextRouteHandler = ((request: Request) => Promise<Response>) & {\n POST: (request: Request) => Promise<Response>;\n OPTIONS: () => Promise<Response>;\n};\n\nconst DEFAULT_API_URL = \"https://api.adhub.so\";\nconst SDK_PATH_PREFIX = \"/api/v1/saas/sdk/\";\nconst SDK_PATHS = new Set([\n `${SDK_PATH_PREFIX}touchpoints`,\n `${SDK_PATH_PREFIX}identify`,\n `${SDK_PATH_PREFIX}behavior-events`,\n `${SDK_PATH_PREFIX}page-engagements`,\n `${SDK_PATH_PREFIX}events`,\n]);\n\nfunction normalizedApiUrl(value: string | undefined): string {\n const url = new URL(value?.trim() || DEFAULT_API_URL);\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\"AdHub Next.js apiUrl must use HTTP or HTTPS.\");\n }\n return url.toString().replace(/\\/$/, \"\");\n}\n\nfunction sdkPath(request: Request): string | null {\n const pathname = new URL(request.url).pathname;\n const prefixIndex = pathname.indexOf(SDK_PATH_PREFIX);\n if (prefixIndex < 0) return null;\n const path = pathname.slice(prefixIndex);\n return SDK_PATHS.has(path) ? path : null;\n}\n\nfunction firstForwardedValue(value: string | null): string | null {\n return value?.split(\",\", 1)[0]?.trim() || null;\n}\n\nfunction firstHeader(request: Request, names: string[]): string | null {\n for (const name of names) {\n const value = request.headers.get(name)?.trim();\n if (value) return value;\n }\n return null;\n}\n\nfunction clientHeaders(request: Request): Headers {\n const headers = new Headers({ \"Content-Type\": \"application/json\" });\n const sourceUrl = new URL(request.url);\n const origin = request.headers.get(\"origin\") || `${sourceUrl.protocol}//${sourceUrl.host}`;\n const userAgent = request.headers.get(\"user-agent\");\n const clientIp =\n firstHeader(request, [\"cf-connecting-ip\", \"true-client-ip\"]) ||\n firstForwardedValue(request.headers.get(\"x-forwarded-for\")) ||\n firstForwardedValue(request.headers.get(\"x-vercel-forwarded-for\")) ||\n request.headers.get(\"x-real-ip\");\n const country = firstHeader(request, [\n \"cf-ipcountry\",\n \"x-vercel-ip-country\",\n \"cloudfront-viewer-country\",\n ]);\n const region = firstHeader(request, [\"x-vercel-ip-country-region\"]);\n const city = firstHeader(request, [\"x-vercel-ip-city\"]);\n\n headers.set(\"Origin\", origin);\n if (userAgent) headers.set(\"User-Agent\", userAgent);\n if (clientIp) headers.set(\"X-AdHub-Client-IP\", clientIp);\n if (country) headers.set(\"X-AdHub-Client-Country\", country);\n if (region) headers.set(\"X-AdHub-Client-Region\", region);\n if (city) headers.set(\"X-AdHub-Client-City\", city);\n\n for (const name of [\n \"Idempotency-Key\",\n \"X-AdHub-Project-Key\",\n \"X-AdHub-SDK\",\n \"X-AdHub-SDK-Version\",\n ]) {\n const value = request.headers.get(name);\n if (value) headers.set(name, value);\n }\n return headers;\n}\n\nexport function createRouteHandler(\n options: AdHubNextRouteHandlerOptions = {},\n): AdHubNextRouteHandler {\n const apiUrl = normalizedApiUrl(options.apiUrl);\n const handler = (async (request: Request): Promise<Response> => {\n const path = sdkPath(request);\n if (request.method !== \"POST\" || !path) {\n return Response.json({ error: \"Not found\" }, { status: 404 });\n }\n\n try {\n const response = await fetch(`${apiUrl}${path}`, {\n method: \"POST\",\n headers: clientHeaders(request),\n body: await request.text(),\n });\n const responseHeaders = new Headers();\n const contentType = response.headers.get(\"content-type\");\n const retryAfter = response.headers.get(\"retry-after\");\n if (contentType) responseHeaders.set(\"Content-Type\", contentType);\n if (retryAfter) responseHeaders.set(\"Retry-After\", retryAfter);\n return new Response(await response.arrayBuffer(), {\n status: response.status,\n headers: responseHeaders,\n });\n } catch (error) {\n return Response.json(\n {\n error: \"Failed to proxy AdHub SDK request\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n }) as AdHubNextRouteHandler;\n\n handler.POST = handler;\n handler.OPTIONS = async () =>\n new Response(null, {\n status: 204,\n headers: { Allow: \"POST, OPTIONS\" },\n });\n return handler;\n}\n","const COOKIE_PREFIX = \"adhub_project_anonymous_id_\";\n\nfunction hashKey(input: string): string {\n let hash = 2_166_136_261;\n for (let index = 0; index < input.length; index += 1) {\n hash ^= input.charCodeAt(index);\n hash = Math.imul(hash, 16_777_619);\n }\n return (hash >>> 0).toString(36);\n}\n\nfunction validAnonymousId(value: string | null): value is string {\n return value !== null && value.length >= 8 && value.length <= 255 && !/\\s/.test(value);\n}\n\nexport function getAdHubAnonymousIdCookieName(projectKey: string): string {\n return `${COOKIE_PREFIX}${hashKey(projectKey.trim())}`;\n}\n\nexport function readAdHubAnonymousIdFromCookie(\n cookieHeader: string | null | undefined,\n projectKey: string,\n): string | null {\n if (!cookieHeader) return null;\n const cookieName = getAdHubAnonymousIdCookieName(projectKey);\n for (const part of cookieHeader.split(\";\")) {\n const [rawName, ...rawValue] = part.trim().split(\"=\");\n if (rawName !== cookieName) continue;\n try {\n const value = decodeURIComponent(rawValue.join(\"=\"));\n return validAnonymousId(value) ? value : null;\n } catch {\n return null;\n }\n }\n return null;\n}\n","import type { JsonObject, JsonValue } from \"./types\";\nimport { readAdHubAnonymousIdFromCookie } from \"./identity-cookie\";\nimport { isUuid, normalizeEventFields, normalizeProfileId } from \"./utils\";\n\nconst DEFAULT_ENDPOINT = \"https://api.adhub.so\";\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\nexport interface AdHubServerClientOptions {\n projectKey: string;\n ingestionKey: string;\n endpoint?: string;\n timeoutMs?: number;\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface ServerEventInput {\n eventType: string;\n profileId: string;\n anonymousId?: string;\n eventId: string;\n occurredAt?: string;\n value?: number;\n currency?: string;\n properties?: Record<string, unknown>;\n}\n\nexport interface ServerEventPayload {\n project: string;\n profileId: string;\n anonymousId?: string;\n eventDefinitionId?: string;\n eventKey?: string;\n eventId: string;\n occurredAt: string;\n value?: number;\n currency?: string;\n properties?: JsonObject;\n}\n\nexport interface ServerEventDeliveryResult {\n bindingId: string;\n advertisingAccountId: string;\n conversionActionId: string;\n status: string;\n googleRequestId?: string | null;\n errorCode?: string | null;\n errorMessage?: string | null;\n retryable?: boolean;\n outcomeUnknown?: boolean;\n}\n\nexport interface ServerEventTrackResult {\n eventId: string;\n externalEventId: string;\n attributionStatus: string;\n attributionReason?: string | null;\n deliveryStatus?: string | null;\n googleRequestId?: string | null;\n duplicate?: boolean;\n deliveries?: ServerEventDeliveryResult[];\n}\n\nexport interface AdHubServerClient {\n track(event: ServerEventInput): Promise<ServerEventTrackResult>;\n}\n\ninterface ServerErrorEnvelope {\n error?: {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n outcome_unknown?: unknown;\n outcomeUnknown?: unknown;\n };\n}\n\nexport class AdHubServerError extends Error {\n readonly status: number;\n readonly code: string | null;\n readonly retryable: boolean;\n readonly outcomeUnknown: boolean;\n\n constructor(\n message: string,\n options: {\n status: number;\n code?: string | null;\n retryable?: boolean;\n outcomeUnknown?: boolean;\n },\n ) {\n super(message);\n this.name = \"AdHubServerError\";\n this.status = options.status;\n this.code = options.code ?? null;\n this.retryable = options.retryable ?? false;\n this.outcomeUnknown = options.outcomeUnknown ?? false;\n }\n}\n\nfunction normalizeEndpoint(endpoint: string | undefined): string {\n let parsed: URL;\n try {\n parsed = new URL(endpoint?.trim() || DEFAULT_ENDPOINT);\n } catch {\n throw new Error(\"AdHub server endpoint must be a valid HTTP(S) URL.\");\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new Error(\"AdHub server endpoint must be a valid HTTP(S) URL.\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n\nexport function createServerEventPayload(\n projectKey: string,\n input: ServerEventInput,\n): ServerEventPayload {\n const normalizedProjectKey = projectKey.trim();\n const profileId = normalizeProfileId(input.profileId);\n if (!isUuid(normalizedProjectKey)) {\n throw new Error(\"AdHub server projectKey must be a UUID.\");\n }\n if (!profileId) {\n throw new Error(\n \"AdHub server profileId must be 1-255 characters without control characters.\",\n );\n }\n\n const normalized = normalizeEventFields(input);\n if (!normalized.eventId) {\n throw new Error(\"AdHub server eventId is required.\");\n }\n\n const payload: ServerEventPayload = {\n project: normalizedProjectKey,\n profileId,\n eventId: normalized.eventId,\n occurredAt: normalized.occurredAt,\n };\n if (input.anonymousId !== undefined) payload.anonymousId = input.anonymousId;\n if (isUuid(normalized.eventType)) payload.eventDefinitionId = normalized.eventType;\n else payload.eventKey = normalized.eventType;\n if (normalized.value !== undefined) payload.value = normalized.value;\n if (normalized.currency !== undefined) payload.currency = normalized.currency;\n if (normalized.properties !== undefined) payload.properties = normalized.properties;\n return payload;\n}\n\nfunction errorDetails(value: unknown, status: number): AdHubServerError {\n const envelope = value && typeof value === \"object\" ? value as ServerErrorEnvelope : {};\n const error = envelope.error;\n const message = typeof error?.message === \"string\"\n ? error.message\n : `AdHub server endpoint returned HTTP ${status}.`;\n return new AdHubServerError(message, {\n status,\n code: typeof error?.code === \"string\" ? error.code : null,\n retryable: error?.retryable === true,\n outcomeUnknown: error?.outcome_unknown === true || error?.outcomeUnknown === true,\n });\n}\n\nasync function readJson(response: Response): Promise<JsonValue | undefined> {\n try {\n return await response.json() as JsonValue;\n } catch {\n return undefined;\n }\n}\n\nclass DefaultAdHubServerClient implements AdHubServerClient {\n private readonly projectKey: string;\n private readonly ingestionKey: string;\n private readonly endpoint: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n constructor(options: AdHubServerClientOptions) {\n this.projectKey = options.projectKey.trim();\n if (!isUuid(this.projectKey)) {\n throw new Error(\"AdHub server projectKey must be a UUID.\");\n }\n this.ingestionKey = options.ingestionKey.trim();\n if (!this.ingestionKey || this.ingestionKey.length > 4_096) {\n throw new Error(\"AdHub server ingestionKey is required.\");\n }\n this.endpoint = normalizeEndpoint(options.endpoint);\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (!Number.isFinite(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 300_000) {\n throw new Error(\"AdHub server timeoutMs must be between 1 and 300000.\");\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\"AdHub server client requires a Fetch API implementation.\");\n }\n this.fetchImpl = fetchImpl;\n }\n\n async track(event: ServerEventInput): Promise<ServerEventTrackResult> {\n const payload = createServerEventPayload(this.projectKey, event);\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.endpoint}/api/v1/saas/events/track`, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${this.ingestionKey}`,\n \"Content-Type\": \"application/json\",\n \"Idempotency-Key\": payload.eventId,\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n } catch (error) {\n if (error instanceof AdHubServerError) throw error;\n const message = error instanceof Error ? error.message : \"AdHub server request failed.\";\n throw new AdHubServerError(message, { status: 0, retryable: true });\n } finally {\n clearTimeout(timeout);\n }\n\n const result = await readJson(response);\n if (!response.ok) throw errorDetails(result, response.status);\n if (!result || typeof result !== \"object\" || Array.isArray(result)) {\n throw new AdHubServerError(\"AdHub server returned an invalid event response.\", {\n status: response.status,\n retryable: response.status >= 500,\n });\n }\n return result as unknown as ServerEventTrackResult;\n }\n}\n\nexport function createAdHubServerClient(options: AdHubServerClientOptions): AdHubServerClient {\n return new DefaultAdHubServerClient(options);\n}\n\nexport { getAdHubAnonymousIdCookieName } from \"./identity-cookie\";\n\nexport function readAdHubAnonymousId(\n cookieHeader: string | null | undefined,\n projectKey: string,\n): string | null {\n return readAdHubAnonymousIdFromCookie(cookieHeader, projectKey);\n}\n"]}
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+
3
+ // src/utils.ts
4
+ var MAX_PARAM_LENGTH = 2048;
5
+ var MAX_ROUTE_LENGTH = 255;
6
+ var MAX_URL_LENGTH = 8192;
7
+ var MAX_UTM_KEYS = 50;
8
+ var MAX_VALUES_PER_PARAM = 10;
9
+ 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;
10
+ var MAX_PROFILE_ID_LENGTH = 255;
11
+ var PROFILE_ID_CONTROL_PATTERN = /[\p{Cc}\p{Cf}]/u;
12
+ function nowIso() {
13
+ return (/* @__PURE__ */ new Date()).toISOString();
14
+ }
15
+ function randomId(prefix) {
16
+ const uuid = globalThis.crypto?.randomUUID?.();
17
+ if (uuid) return `${prefix}_${uuid}`;
18
+ const random = Math.random().toString(36).slice(2);
19
+ return `${prefix}_${Date.now().toString(36)}${random}`;
20
+ }
21
+ function truncate(value) {
22
+ return value.slice(0, MAX_PARAM_LENGTH);
23
+ }
24
+ function unique(values) {
25
+ return [...new Set(values.filter(Boolean).map(truncate))];
26
+ }
27
+ function valuesFor(searchParams, wantedKey) {
28
+ const values = [];
29
+ for (const [key, value] of searchParams.entries()) {
30
+ if (key.toLowerCase() === wantedKey) values.push(value);
31
+ }
32
+ return unique(values).slice(0, MAX_VALUES_PER_PARAM);
33
+ }
34
+ function isUuid(value) {
35
+ return UUID_PATTERN.test(value);
36
+ }
37
+ function normalizeProfileId(value) {
38
+ const normalized = value.trim();
39
+ if (!normalized || [...normalized].length > MAX_PROFILE_ID_LENGTH || PROFILE_ID_CONTROL_PATTERN.test(normalized)) {
40
+ return null;
41
+ }
42
+ return normalized;
43
+ }
44
+ function safePageUrl(input) {
45
+ try {
46
+ const url = new URL(input);
47
+ return `${url.origin}${url.pathname}`.slice(0, MAX_URL_LENGTH);
48
+ } catch {
49
+ return "";
50
+ }
51
+ }
52
+ function safeReferrer(input) {
53
+ if (!input) return null;
54
+ const safe = safePageUrl(input);
55
+ return safe || null;
56
+ }
57
+ function captureTouchpoint(location, referrer, capturedAt = nowIso()) {
58
+ const url = new URL(location.href);
59
+ const clickIds = {
60
+ gclid: valuesFor(url.searchParams, "gclid"),
61
+ gbraid: valuesFor(url.searchParams, "gbraid"),
62
+ wbraid: valuesFor(url.searchParams, "wbraid")
63
+ };
64
+ const utm = {};
65
+ for (const key of [...new Set([...url.searchParams.keys()].map((key2) => key2.toLowerCase()))].filter((candidate) => candidate.startsWith("utm_")).slice(0, MAX_UTM_KEYS)) {
66
+ utm[key] = valuesFor(url.searchParams, key);
67
+ }
68
+ return {
69
+ ahRoute: valuesFor(url.searchParams, "ah_route")[0]?.slice(0, MAX_ROUTE_LENGTH) ?? null,
70
+ clickIds,
71
+ utm,
72
+ landingUrl: safePageUrl(url.href),
73
+ referrer: safeReferrer(referrer),
74
+ // Browsers do not know Google's server-side click timestamp. This is the
75
+ // first-party observation time and is the upper bound available to the SDK.
76
+ clickTime: capturedAt
77
+ };
78
+ }
79
+
80
+ // src/testing.ts
81
+ var CLICK_ID_TYPES = /* @__PURE__ */ new Set(["gclid", "gbraid", "wbraid"]);
82
+ function envelope(projectKey, anonymousId, type, data, sentAt) {
83
+ return {
84
+ schemaVersion: "1.0",
85
+ type,
86
+ requestId: randomId("req_test"),
87
+ sentAt,
88
+ projectKey,
89
+ anonymousId,
90
+ data
91
+ };
92
+ }
93
+ function createAttributionTestEnvelopes(input) {
94
+ const projectKey = input.projectKey.trim();
95
+ const attributionRouteKey = input.attributionRouteKey.trim();
96
+ const clickId = input.clickId.trim();
97
+ const profileId = normalizeProfileId(input.profileId);
98
+ if (!isUuid(projectKey)) {
99
+ throw new Error("Attribution test requires a UUID project identifier.");
100
+ }
101
+ if (!isUuid(attributionRouteKey)) {
102
+ throw new Error("Attribution test requires a UUID attribution route identifier.");
103
+ }
104
+ if (!profileId) {
105
+ throw new Error(
106
+ "Attribution test profileId must be 1-255 characters without control characters."
107
+ );
108
+ }
109
+ if (!CLICK_ID_TYPES.has(input.clickIdType) || !clickId || clickId.length > 2048 || /\s/.test(clickId)) {
110
+ throw new Error("Attribution test requires one valid Google click ID.");
111
+ }
112
+ const capturedAt = input.capturedAt ?? nowIso();
113
+ const testUrl = new URL(input.pageUrl);
114
+ const trackingKeys = /* @__PURE__ */ new Set(["ah_route", "gclid", "gbraid", "wbraid"]);
115
+ for (const key of [...testUrl.searchParams.keys()]) {
116
+ if (trackingKeys.has(key.toLowerCase())) testUrl.searchParams.delete(key);
117
+ }
118
+ testUrl.searchParams.set("ah_route", attributionRouteKey);
119
+ testUrl.searchParams.set(input.clickIdType, clickId);
120
+ const captured = captureTouchpoint(
121
+ { href: testUrl.toString() },
122
+ input.referrer ?? "",
123
+ capturedAt
124
+ );
125
+ const anonymousId = randomId("anon_test");
126
+ const sessionId = randomId("sess_test");
127
+ const touchpointData = {
128
+ ...captured,
129
+ sessionId,
130
+ locale: input.locale ?? null,
131
+ timezone: input.timezone ?? null
132
+ };
133
+ const identityData = {
134
+ profile: {
135
+ profileId,
136
+ properties: { source: "adhub_attribution_test" }
137
+ },
138
+ identifiedAt: capturedAt,
139
+ pageUrl: safePageUrl(input.pageUrl)
140
+ };
141
+ return {
142
+ touchpoint: envelope(projectKey, anonymousId, "touchpoint.capture", touchpointData, capturedAt),
143
+ identity: envelope(projectKey, anonymousId, "profile.identify", identityData, capturedAt)
144
+ };
145
+ }
146
+
147
+ exports.createAttributionTestEnvelopes = createAttributionTestEnvelopes;
148
+ //# sourceMappingURL=testing.cjs.map
149
+ //# sourceMappingURL=testing.cjs.map