@preprio/toolkit 0.1.0-beta.1 → 0.1.0-beta.4

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,399 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/nuxt/index.ts
21
+ var nuxt_exports = {};
22
+ __export(nuxt_exports, {
23
+ PREPR_CONTEXT_KEY: () => PREPR_CONTEXT_KEY,
24
+ PreprError: () => PreprError,
25
+ extractAccessToken: () => extractAccessToken,
26
+ getActiveSegment: () => getActiveSegment,
27
+ getActiveVariant: () => getActiveVariant,
28
+ getPreprHeaders: () => getPreprHeaders,
29
+ getPreprHeadersFromEvent: () => getPreprHeadersFromEvent,
30
+ getPreprUUID: () => getPreprUUID,
31
+ getToolbarProps: () => getToolbarProps,
32
+ handlePreprRequest: () => handlePreprRequest,
33
+ validatePreprToken: () => validatePreprToken
34
+ });
35
+ module.exports = __toCommonJS(nuxt_exports);
36
+
37
+ // src/version.ts
38
+ var VERSION = "0.1.0-beta.4";
39
+
40
+ // src/core/constants.ts
41
+ var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
42
+ var COOKIE_SEGMENT = "Prepr-Segments";
43
+ var COOKIE_VARIANT = "Prepr-ABtesting";
44
+ var COOKIE_UID = "__prepr_uid";
45
+ var COOKIE_HUBSPOT = "hubspotutk";
46
+ var PARAM_SEGMENT = "prepr_preview_segment";
47
+ var PARAM_VARIANT = "prepr_preview_ab";
48
+ var PARAM_HIDE_BAR = "prepr_hide_bar";
49
+ var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
50
+
51
+ // src/core/middleware.ts
52
+ var UTM_PARAMS = [
53
+ "utm_source",
54
+ "utm_medium",
55
+ "utm_term",
56
+ "utm_content",
57
+ "utm_campaign"
58
+ ];
59
+ function serializeCookie(cookie) {
60
+ const parts = [
61
+ `${cookie.name}=${encodeURIComponent(cookie.value)}`,
62
+ `Max-Age=${cookie.maxAge}`,
63
+ `Path=${cookie.path}`
64
+ ];
65
+ if (cookie.sameSite) {
66
+ parts.push(`SameSite=${cookie.sameSite}`);
67
+ }
68
+ if (cookie.secure) {
69
+ parts.push("Secure");
70
+ }
71
+ return parts.join("; ");
72
+ }
73
+ function parseCookies(request) {
74
+ const cookies = /* @__PURE__ */ new Map();
75
+ const header = request.headers.get("cookie");
76
+ if (!header) return cookies;
77
+ for (const part of header.split(";")) {
78
+ const eq = part.indexOf("=");
79
+ if (eq === -1) continue;
80
+ const name = part.slice(0, eq).trim();
81
+ const value = part.slice(eq + 1).trim();
82
+ if (!name) continue;
83
+ cookies.set(name, decodeURIComponent(value));
84
+ }
85
+ return cookies;
86
+ }
87
+ function processPreprRequest(request, opts) {
88
+ const requestHeaders = new Headers(request.headers);
89
+ const responseCookies = [];
90
+ const requestCookies = parseCookies(request);
91
+ const url = new URL(request.url);
92
+ const searchParams = url.searchParams;
93
+ const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
94
+ const isSecure = forwardedProto ? forwardedProto === "https" : url.protocol === "https:";
95
+ const crossSite = isSecure ? { sameSite: "None", secure: true } : {};
96
+ for (const key of UTM_PARAMS) {
97
+ const value = searchParams.get(key);
98
+ if (value !== null) {
99
+ requestHeaders.set(`Prepr-Context-${key}`, value);
100
+ }
101
+ }
102
+ const referer = request.headers.get("referer");
103
+ if (referer) {
104
+ requestHeaders.set("Prepr-Context-initial_referral", referer);
105
+ }
106
+ const userAgent = request.headers.get("user-agent");
107
+ if (userAgent) {
108
+ requestHeaders.set("Prepr-User-Agent", userAgent);
109
+ }
110
+ requestHeaders.set("Prepr-Package", `@preprio/toolkit@${opts?.version ?? VERSION}`);
111
+ const ip = request.headers.get("Cf-Connecting-Ip") ?? request.headers.get("x-real-ip");
112
+ if (ip) {
113
+ requestHeaders.set("Prepr-Visitor-IP", ip);
114
+ }
115
+ const hutkCookie = requestCookies.get(COOKIE_HUBSPOT);
116
+ if (hutkCookie) {
117
+ requestHeaders.set("Prepr-Hubspot-Id", hutkCookie);
118
+ }
119
+ let uid = requestCookies.get(COOKIE_UID);
120
+ if (!uid) {
121
+ uid = crypto.randomUUID();
122
+ responseCookies.push({
123
+ name: COOKIE_UID,
124
+ value: uid,
125
+ maxAge: ONE_YEAR_SECONDS,
126
+ path: "/"
127
+ });
128
+ requestHeaders.set("Prepr-Customer-Id-Created", "true");
129
+ }
130
+ requestHeaders.set("Prepr-Customer-Id", uid);
131
+ if (!opts?.preview) {
132
+ return { requestHeaders, responseCookies };
133
+ }
134
+ const hasPreviewParams = searchParams.has(PARAM_SEGMENT) || searchParams.has(PARAM_VARIANT);
135
+ if (!hasPreviewParams) {
136
+ const previewModeCookie = requestCookies.get(COOKIE_PREVIEW_MODE);
137
+ const previewModeEnabled = previewModeCookie !== "false";
138
+ if (!previewModeEnabled) {
139
+ return { requestHeaders, responseCookies };
140
+ }
141
+ }
142
+ requestHeaders.set("Prepr-Preview-Bar", "true");
143
+ const isLivePreview = searchParams.get(PARAM_HIDE_BAR) === "true";
144
+ if (!isLivePreview && !requestCookies.has(COOKIE_PREVIEW_MODE)) {
145
+ responseCookies.push({
146
+ name: COOKIE_PREVIEW_MODE,
147
+ value: "true",
148
+ maxAge: ONE_YEAR_SECONDS,
149
+ path: "/",
150
+ ...crossSite
151
+ });
152
+ }
153
+ if (!isLivePreview) {
154
+ const segmentCookie = requestCookies.get(COOKIE_SEGMENT);
155
+ if (segmentCookie) {
156
+ requestHeaders.set("Prepr-Segments", segmentCookie);
157
+ }
158
+ const abCookie = requestCookies.get(COOKIE_VARIANT);
159
+ if (abCookie) {
160
+ requestHeaders.set("Prepr-ABtesting", abCookie);
161
+ }
162
+ }
163
+ const previewAb = searchParams.get(PARAM_VARIANT);
164
+ if (previewAb !== null) {
165
+ requestHeaders.set("Prepr-ABtesting", previewAb);
166
+ if (!isLivePreview) {
167
+ responseCookies.push({
168
+ name: COOKIE_VARIANT,
169
+ value: previewAb,
170
+ maxAge: ONE_YEAR_SECONDS,
171
+ path: "/",
172
+ ...crossSite
173
+ });
174
+ }
175
+ }
176
+ const previewSegment = searchParams.get(PARAM_SEGMENT);
177
+ if (previewSegment !== null) {
178
+ requestHeaders.set("Prepr-Segments", previewSegment);
179
+ if (!isLivePreview) {
180
+ responseCookies.push({
181
+ name: COOKIE_SEGMENT,
182
+ value: previewSegment,
183
+ maxAge: ONE_YEAR_SECONDS,
184
+ path: "/",
185
+ ...crossSite
186
+ });
187
+ }
188
+ }
189
+ return { requestHeaders, responseCookies };
190
+ }
191
+
192
+ // src/nuxt/middleware.ts
193
+ var PREPR_CONTEXT_KEY = "prepr";
194
+ function handlePreprRequest(event, options) {
195
+ const req = event.node.req;
196
+ const host = typeof req.headers.host === "string" ? req.headers.host : "localhost";
197
+ const request = new Request(`http://${host}${req.url ?? "/"}`);
198
+ for (const [key, value] of Object.entries(req.headers)) {
199
+ if (typeof value === "string") {
200
+ request.headers.set(key, value);
201
+ } else if (Array.isArray(value)) {
202
+ request.headers.set(key, value.join(", "));
203
+ }
204
+ }
205
+ const { requestHeaders, responseCookies } = processPreprRequest(request, options);
206
+ requestHeaders.forEach((value, key) => {
207
+ req.headers[key.toLowerCase()] = value;
208
+ });
209
+ event.context[PREPR_CONTEXT_KEY] = requestHeaders;
210
+ for (const cookie of responseCookies) {
211
+ event.node.res.appendHeader("Set-Cookie", serializeCookie(cookie));
212
+ }
213
+ }
214
+ function getPreprHeadersFromEvent(event) {
215
+ const headers = event.context[PREPR_CONTEXT_KEY];
216
+ return headers instanceof Headers ? headers : new Headers();
217
+ }
218
+
219
+ // src/core/server.ts
220
+ var PreprError = class extends Error {
221
+ constructor(message, code, context, originalError) {
222
+ super(message);
223
+ this.code = code;
224
+ this.context = context;
225
+ this.originalError = originalError;
226
+ this.name = "PreprError";
227
+ }
228
+ };
229
+ function getPreprUUIDFromHeaders(headers) {
230
+ return headers.get("prepr-customer-id");
231
+ }
232
+ function getActiveSegmentFromHeaders(headers) {
233
+ return headers.get("Prepr-Segments");
234
+ }
235
+ function getActiveVariantFromHeaders(headers) {
236
+ return headers.get("Prepr-ABtesting");
237
+ }
238
+ var PREPR_HEADER_KEYS = [
239
+ "prepr-customer-id",
240
+ "Prepr-Segments",
241
+ "Prepr-ABtesting",
242
+ "Prepr-Preview-Bar",
243
+ "Prepr-Context-utm_source",
244
+ "Prepr-Context-utm_medium",
245
+ "Prepr-Context-utm_term",
246
+ "Prepr-Context-utm_content",
247
+ "Prepr-Context-utm_campaign",
248
+ "Prepr-Context-initial_referral",
249
+ "Prepr-Visitor-IP",
250
+ "Prepr-Hubspot-Id",
251
+ "Prepr-Customer-Id-Created",
252
+ "Prepr-User-Agent"
253
+ ];
254
+ function getPreprHeadersFromHeaders(headers) {
255
+ const preprHeaders = {};
256
+ const copy = (key) => {
257
+ const value = headers.get(key);
258
+ if (value !== null) {
259
+ preprHeaders[key] = value;
260
+ }
261
+ };
262
+ for (const key of PREPR_HEADER_KEYS) {
263
+ copy(key);
264
+ }
265
+ return preprHeaders;
266
+ }
267
+ function validatePreprToken(token) {
268
+ if (!token) {
269
+ throw new PreprError("Token is required", "MISSING_TOKEN", "validatePreprToken");
270
+ }
271
+ if (!token.startsWith("https://")) {
272
+ throw new PreprError(
273
+ "Token must be a valid HTTPS URL",
274
+ "INVALID_TOKEN",
275
+ "validatePreprToken"
276
+ );
277
+ }
278
+ }
279
+ function extractAccessToken(graphqlUrl) {
280
+ let url;
281
+ try {
282
+ url = new URL(graphqlUrl);
283
+ } catch (error) {
284
+ throw new PreprError(
285
+ "Token must be a valid URL",
286
+ "INVALID_TOKEN",
287
+ "extractAccessToken",
288
+ error instanceof Error ? error : new Error(String(error))
289
+ );
290
+ }
291
+ if (url.hostname !== "graphql.prepr.io") {
292
+ throw new PreprError(
293
+ "Token must be a graphql.prepr.io URL",
294
+ "INVALID_TOKEN",
295
+ "extractAccessToken"
296
+ );
297
+ }
298
+ const pathParts = url.pathname.split("/");
299
+ const token = pathParts[pathParts.length - 1];
300
+ if (!token) {
301
+ throw new PreprError(
302
+ "Token URL is missing an access token segment",
303
+ "INVALID_TOKEN",
304
+ "extractAccessToken"
305
+ );
306
+ }
307
+ return token;
308
+ }
309
+ async function getPreprEnvironmentSegments(token) {
310
+ validatePreprToken(token);
311
+ try {
312
+ const response = await fetch(token, {
313
+ headers: {
314
+ "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
315
+ "Content-Type": "application/json"
316
+ },
317
+ method: "POST",
318
+ body: JSON.stringify({
319
+ query: `{
320
+ _Segments {
321
+ _id
322
+ name
323
+ }
324
+ }`
325
+ })
326
+ });
327
+ if (!response.ok) {
328
+ throw new PreprError(
329
+ `HTTP ${response.status}: ${response.statusText}`,
330
+ "HTTP_ERROR",
331
+ "getPreprEnvironmentSegments"
332
+ );
333
+ }
334
+ const json = await response.json();
335
+ if (!json || !json.data || !json.data._Segments) {
336
+ throw new PreprError(
337
+ "Invalid response format from Prepr API",
338
+ "INVALID_RESPONSE",
339
+ "getPreprEnvironmentSegments"
340
+ );
341
+ }
342
+ return json.data._Segments;
343
+ } catch (error) {
344
+ if (error instanceof PreprError) {
345
+ throw error;
346
+ }
347
+ throw new PreprError(
348
+ "Failed to fetch segments from Prepr API",
349
+ "FETCH_ERROR",
350
+ "getPreprEnvironmentSegments",
351
+ error instanceof Error ? error : new Error(String(error))
352
+ );
353
+ }
354
+ }
355
+ async function getToolbarPropsFromHeaders(headers, token) {
356
+ let segments = [];
357
+ try {
358
+ segments = await getPreprEnvironmentSegments(token);
359
+ } catch {
360
+ segments = [];
361
+ }
362
+ return {
363
+ activeSegment: getActiveSegmentFromHeaders(headers),
364
+ activeVariant: getActiveVariantFromHeaders(headers),
365
+ segments,
366
+ data: segments
367
+ };
368
+ }
369
+
370
+ // src/nuxt/server.ts
371
+ function getPreprUUID(headers) {
372
+ return getPreprUUIDFromHeaders(headers);
373
+ }
374
+ function getActiveSegment(headers) {
375
+ return getActiveSegmentFromHeaders(headers);
376
+ }
377
+ function getActiveVariant(headers) {
378
+ return getActiveVariantFromHeaders(headers);
379
+ }
380
+ function getPreprHeaders(headers) {
381
+ return getPreprHeadersFromHeaders(headers);
382
+ }
383
+ async function getToolbarProps(headers, token) {
384
+ return getToolbarPropsFromHeaders(headers, token);
385
+ }
386
+ // Annotate the CommonJS export names for ESM import in node:
387
+ 0 && (module.exports = {
388
+ PREPR_CONTEXT_KEY,
389
+ PreprError,
390
+ extractAccessToken,
391
+ getActiveSegment,
392
+ getActiveVariant,
393
+ getPreprHeaders,
394
+ getPreprHeadersFromEvent,
395
+ getPreprUUID,
396
+ getToolbarProps,
397
+ handlePreprRequest,
398
+ validatePreprToken
399
+ });
@@ -0,0 +1,120 @@
1
+ interface PreprMiddlewareOptions {
2
+ /** Enable preview-mode headers (segment/AB overrides, preview bar). */
3
+ preview?: boolean;
4
+ /** Override the version reported in Prepr-Package (mainly for tests). */
5
+ version?: string;
6
+ }
7
+
8
+ /**
9
+ * Structural stand-in for h3's `H3Event`, so this package needs no build-time
10
+ * dependency on `h3`/`nuxt`. Only the fields `handlePreprRequest` uses.
11
+ *
12
+ * `node` ties this to Nitro's Node.js preset (the Nuxt default). Edge presets
13
+ * expose no raw Node request/response to fold headers back onto.
14
+ */
15
+ interface H3EventLike {
16
+ node: {
17
+ req: {
18
+ url?: string;
19
+ headers: Record<string, string | string[] | undefined>;
20
+ };
21
+ res: {
22
+ /** Node's `ServerResponse.appendHeader` (Node >= 18.3). */
23
+ appendHeader(name: string, value: string): unknown;
24
+ };
25
+ };
26
+ /** Request-scoped bag shared with route handlers and Vue via `useRequestEvent`. */
27
+ context: Record<string, unknown>;
28
+ }
29
+ /** Key under which `handlePreprRequest` mirrors the forwarded Prepr `Headers`. */
30
+ declare const PREPR_CONTEXT_KEY = "prepr";
31
+ /**
32
+ * Nuxt server middleware entry point — call it inside `defineEventHandler` in
33
+ * `server/middleware/prepr.ts`:
34
+ *
35
+ * ```ts
36
+ * export default defineEventHandler(event => {
37
+ * handlePreprRequest(event, { preview: import.meta.dev });
38
+ * });
39
+ * ```
40
+ *
41
+ * The computed Prepr headers are folded back onto the raw Node request
42
+ * (lowercased, as Node stores them), which is what `useRequestHeaders()` and
43
+ * downstream handlers read. The same `Headers` are mirrored onto
44
+ * `event.context.prepr` for callers who prefer an explicit read
45
+ * (`getPreprHeadersFromEvent`). Cookies are appended to the response.
46
+ */
47
+ declare function handlePreprRequest(event: H3EventLike, options?: PreprMiddlewareOptions): void;
48
+ /**
49
+ * Personalization headers to forward to your GraphQL fetch, from the h3 event.
50
+ * Empty `Headers` if `handlePreprRequest` did not run, so the result is always
51
+ * safe to spread.
52
+ */
53
+ declare function getPreprHeadersFromEvent(event: Pick<H3EventLike, 'context'>): Headers;
54
+
55
+ interface PreprSegment {
56
+ readonly _id: string;
57
+ readonly name: string;
58
+ }
59
+ interface PreprToolbarProps {
60
+ readonly activeSegment: string | null;
61
+ readonly activeVariant: string | null;
62
+ /** Available segments to personalize on. */
63
+ readonly segments?: readonly PreprSegment[];
64
+ /** @deprecated Alias for `segments`. */
65
+ readonly data?: readonly PreprSegment[];
66
+ }
67
+ type PreprVariant = 'A' | 'B';
68
+ interface PreprHeaders {
69
+ readonly 'prepr-customer-id'?: string;
70
+ readonly 'Prepr-Segments'?: string;
71
+ readonly 'Prepr-ABtesting'?: PreprVariant;
72
+ readonly 'Prepr-Preview-Bar'?: 'true';
73
+ readonly 'Prepr-Context-utm_source'?: string;
74
+ readonly 'Prepr-Context-utm_medium'?: string;
75
+ readonly 'Prepr-Context-utm_term'?: string;
76
+ readonly 'Prepr-Context-utm_content'?: string;
77
+ readonly 'Prepr-Context-utm_campaign'?: string;
78
+ readonly 'Prepr-Context-initial_referral'?: string;
79
+ readonly 'Prepr-Visitor-IP'?: string;
80
+ readonly 'Prepr-Hubspot-Id'?: string;
81
+ readonly 'Prepr-Customer-Id-Created'?: 'true';
82
+ readonly 'Prepr-User-Agent'?: string;
83
+ }
84
+ type PreprErrorCode = 'INVALID_TOKEN' | 'MISSING_TOKEN' | 'HTTP_ERROR' | 'FETCH_ERROR' | 'INVALID_RESPONSE' | 'CONTEXT_ERROR';
85
+
86
+ /** Returns the Prepr Customer ID from the request headers. */
87
+ declare function getPreprUUID(headers: Headers): string | null;
88
+ /** Returns the active segment from the request headers. */
89
+ declare function getActiveSegment(headers: Headers): string | null;
90
+ /** Returns the active A/B testing variant from the request headers. */
91
+ declare function getActiveVariant(headers: Headers): string | null;
92
+ /** Returns all Prepr headers from the request headers. */
93
+ declare function getPreprHeaders(headers: Headers): PreprHeaders;
94
+ /**
95
+ * Props needed to mount `PreprToolbar.vue`, from the request headers plus a
96
+ * Prepr GraphQL token. Ungated — gate on preview mode yourself (e.g.
97
+ * `import.meta.dev`).
98
+ */
99
+ declare function getToolbarProps(headers: Headers, token: string): Promise<PreprToolbarProps>;
100
+
101
+ /** Error thrown by the token helpers and the segments fetch. */
102
+ declare class PreprError extends Error {
103
+ readonly code: PreprErrorCode;
104
+ readonly context?: string | undefined;
105
+ readonly originalError?: Error | undefined;
106
+ constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
107
+ }
108
+ /**
109
+ * Asserts `token` is the full `https://graphql.prepr.io/<token>` URL.
110
+ * @throws PreprError if the token is missing or not an HTTPS URL.
111
+ */
112
+ declare function validatePreprToken(token: string): void;
113
+ /**
114
+ * Pulls the access token out of a GraphQL URL: `https://graphql.prepr.io/abc123`
115
+ * -> `abc123`.
116
+ * @throws PreprError if the URL is not a valid `graphql.prepr.io` URL.
117
+ */
118
+ declare function extractAccessToken(graphqlUrl: string): string;
119
+
120
+ export { type H3EventLike, PREPR_CONTEXT_KEY, PreprError, type PreprMiddlewareOptions, extractAccessToken, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprHeadersFromEvent, getPreprUUID, getToolbarProps, handlePreprRequest, validatePreprToken };
@@ -0,0 +1,120 @@
1
+ interface PreprMiddlewareOptions {
2
+ /** Enable preview-mode headers (segment/AB overrides, preview bar). */
3
+ preview?: boolean;
4
+ /** Override the version reported in Prepr-Package (mainly for tests). */
5
+ version?: string;
6
+ }
7
+
8
+ /**
9
+ * Structural stand-in for h3's `H3Event`, so this package needs no build-time
10
+ * dependency on `h3`/`nuxt`. Only the fields `handlePreprRequest` uses.
11
+ *
12
+ * `node` ties this to Nitro's Node.js preset (the Nuxt default). Edge presets
13
+ * expose no raw Node request/response to fold headers back onto.
14
+ */
15
+ interface H3EventLike {
16
+ node: {
17
+ req: {
18
+ url?: string;
19
+ headers: Record<string, string | string[] | undefined>;
20
+ };
21
+ res: {
22
+ /** Node's `ServerResponse.appendHeader` (Node >= 18.3). */
23
+ appendHeader(name: string, value: string): unknown;
24
+ };
25
+ };
26
+ /** Request-scoped bag shared with route handlers and Vue via `useRequestEvent`. */
27
+ context: Record<string, unknown>;
28
+ }
29
+ /** Key under which `handlePreprRequest` mirrors the forwarded Prepr `Headers`. */
30
+ declare const PREPR_CONTEXT_KEY = "prepr";
31
+ /**
32
+ * Nuxt server middleware entry point — call it inside `defineEventHandler` in
33
+ * `server/middleware/prepr.ts`:
34
+ *
35
+ * ```ts
36
+ * export default defineEventHandler(event => {
37
+ * handlePreprRequest(event, { preview: import.meta.dev });
38
+ * });
39
+ * ```
40
+ *
41
+ * The computed Prepr headers are folded back onto the raw Node request
42
+ * (lowercased, as Node stores them), which is what `useRequestHeaders()` and
43
+ * downstream handlers read. The same `Headers` are mirrored onto
44
+ * `event.context.prepr` for callers who prefer an explicit read
45
+ * (`getPreprHeadersFromEvent`). Cookies are appended to the response.
46
+ */
47
+ declare function handlePreprRequest(event: H3EventLike, options?: PreprMiddlewareOptions): void;
48
+ /**
49
+ * Personalization headers to forward to your GraphQL fetch, from the h3 event.
50
+ * Empty `Headers` if `handlePreprRequest` did not run, so the result is always
51
+ * safe to spread.
52
+ */
53
+ declare function getPreprHeadersFromEvent(event: Pick<H3EventLike, 'context'>): Headers;
54
+
55
+ interface PreprSegment {
56
+ readonly _id: string;
57
+ readonly name: string;
58
+ }
59
+ interface PreprToolbarProps {
60
+ readonly activeSegment: string | null;
61
+ readonly activeVariant: string | null;
62
+ /** Available segments to personalize on. */
63
+ readonly segments?: readonly PreprSegment[];
64
+ /** @deprecated Alias for `segments`. */
65
+ readonly data?: readonly PreprSegment[];
66
+ }
67
+ type PreprVariant = 'A' | 'B';
68
+ interface PreprHeaders {
69
+ readonly 'prepr-customer-id'?: string;
70
+ readonly 'Prepr-Segments'?: string;
71
+ readonly 'Prepr-ABtesting'?: PreprVariant;
72
+ readonly 'Prepr-Preview-Bar'?: 'true';
73
+ readonly 'Prepr-Context-utm_source'?: string;
74
+ readonly 'Prepr-Context-utm_medium'?: string;
75
+ readonly 'Prepr-Context-utm_term'?: string;
76
+ readonly 'Prepr-Context-utm_content'?: string;
77
+ readonly 'Prepr-Context-utm_campaign'?: string;
78
+ readonly 'Prepr-Context-initial_referral'?: string;
79
+ readonly 'Prepr-Visitor-IP'?: string;
80
+ readonly 'Prepr-Hubspot-Id'?: string;
81
+ readonly 'Prepr-Customer-Id-Created'?: 'true';
82
+ readonly 'Prepr-User-Agent'?: string;
83
+ }
84
+ type PreprErrorCode = 'INVALID_TOKEN' | 'MISSING_TOKEN' | 'HTTP_ERROR' | 'FETCH_ERROR' | 'INVALID_RESPONSE' | 'CONTEXT_ERROR';
85
+
86
+ /** Returns the Prepr Customer ID from the request headers. */
87
+ declare function getPreprUUID(headers: Headers): string | null;
88
+ /** Returns the active segment from the request headers. */
89
+ declare function getActiveSegment(headers: Headers): string | null;
90
+ /** Returns the active A/B testing variant from the request headers. */
91
+ declare function getActiveVariant(headers: Headers): string | null;
92
+ /** Returns all Prepr headers from the request headers. */
93
+ declare function getPreprHeaders(headers: Headers): PreprHeaders;
94
+ /**
95
+ * Props needed to mount `PreprToolbar.vue`, from the request headers plus a
96
+ * Prepr GraphQL token. Ungated — gate on preview mode yourself (e.g.
97
+ * `import.meta.dev`).
98
+ */
99
+ declare function getToolbarProps(headers: Headers, token: string): Promise<PreprToolbarProps>;
100
+
101
+ /** Error thrown by the token helpers and the segments fetch. */
102
+ declare class PreprError extends Error {
103
+ readonly code: PreprErrorCode;
104
+ readonly context?: string | undefined;
105
+ readonly originalError?: Error | undefined;
106
+ constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
107
+ }
108
+ /**
109
+ * Asserts `token` is the full `https://graphql.prepr.io/<token>` URL.
110
+ * @throws PreprError if the token is missing or not an HTTPS URL.
111
+ */
112
+ declare function validatePreprToken(token: string): void;
113
+ /**
114
+ * Pulls the access token out of a GraphQL URL: `https://graphql.prepr.io/abc123`
115
+ * -> `abc123`.
116
+ * @throws PreprError if the URL is not a valid `graphql.prepr.io` URL.
117
+ */
118
+ declare function extractAccessToken(graphqlUrl: string): string;
119
+
120
+ export { type H3EventLike, PREPR_CONTEXT_KEY, PreprError, type PreprMiddlewareOptions, extractAccessToken, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprHeadersFromEvent, getPreprUUID, getToolbarProps, handlePreprRequest, validatePreprToken };