@preprio/toolkit 0.6.0-alpha.9 → 1.0.0-rc.2

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.
Files changed (116) hide show
  1. package/README.md +111 -1363
  2. package/dist/astro/index.cjs +1555 -182
  3. package/dist/astro/index.d.cts +201 -1
  4. package/dist/astro/index.d.ts +201 -1
  5. package/dist/astro/index.js +1557 -29
  6. package/dist/chunk-A2J7R4LR.js +256 -0
  7. package/dist/{chunk-5QIWVDP2.js → chunk-DBKZWOXA.js} +1 -1
  8. package/dist/{chunk-WQBKQG4R.js → chunk-EWXBE3JD.js} +6 -1
  9. package/dist/chunk-KM2GME62.js +1255 -0
  10. package/dist/{chunk-J66UOCK6.js → chunk-LJA5K4KM.js} +1680 -579
  11. package/dist/chunk-UTKH7DOI.js +58 -0
  12. package/dist/chunk-V7MCHPE7.js +85 -0
  13. package/dist/chunk-Y7JWV7WV.js +374 -0
  14. package/dist/codegen/index.cjs +82 -0
  15. package/dist/codegen/index.d.cts +70 -0
  16. package/dist/codegen/index.d.ts +70 -0
  17. package/dist/codegen/index.js +64 -0
  18. package/dist/index.cjs +3729 -553
  19. package/dist/index.d.cts +403 -19
  20. package/dist/index.d.ts +403 -19
  21. package/dist/index.js +345 -24
  22. package/dist/live-preview-HCBNBC6C.js +19 -0
  23. package/dist/nextjs/components.cjs +1872 -754
  24. package/dist/nextjs/components.d.cts +5 -51
  25. package/dist/nextjs/components.d.ts +5 -51
  26. package/dist/nextjs/components.js +8 -299
  27. package/dist/nextjs/index.cjs +1228 -181
  28. package/dist/nextjs/index.d.cts +247 -92
  29. package/dist/nextjs/index.d.ts +247 -92
  30. package/dist/nextjs/index.js +1629 -111
  31. package/dist/nextjs/live-action.cjs +298 -0
  32. package/dist/nextjs/live-action.d.cts +12 -0
  33. package/dist/nextjs/live-action.d.ts +12 -0
  34. package/dist/nextjs/live-action.js +68 -0
  35. package/dist/nextjs/live.cjs +2010 -0
  36. package/dist/nextjs/live.d.cts +54 -0
  37. package/dist/nextjs/live.d.ts +54 -0
  38. package/dist/nextjs/live.js +287 -0
  39. package/dist/nuxt/chunk-5RBZPRQN.js +350 -0
  40. package/dist/nuxt/chunk-LUKVPOJ2.js +32 -0
  41. package/dist/nuxt/index.cjs +15 -16
  42. package/dist/nuxt/index.d.cts +167 -6
  43. package/dist/nuxt/index.d.ts +167 -6
  44. package/dist/nuxt/index.js +402 -15
  45. package/dist/nuxt/live-preview-KO4IKWTX.js +1234 -0
  46. package/dist/nuxt/live.cjs +1928 -0
  47. package/dist/nuxt/live.d.cts +45 -0
  48. package/dist/nuxt/live.d.ts +45 -0
  49. package/dist/nuxt/live.js +216 -0
  50. package/dist/{types-BYH9XqmN.d.cts → pixel-DqU7NvgW.d.cts} +102 -5
  51. package/dist/{types-BYH9XqmN.d.ts → pixel-DqU7NvgW.d.ts} +102 -5
  52. package/dist/react/components.cjs +1865 -480
  53. package/dist/react/components.d.cts +43 -8
  54. package/dist/react/components.d.ts +43 -8
  55. package/dist/react/components.js +1865 -480
  56. package/dist/sveltekit/chunk-5RBZPRQN.js +350 -0
  57. package/dist/sveltekit/chunk-LUKVPOJ2.js +32 -0
  58. package/dist/sveltekit/index.cjs +15 -16
  59. package/dist/sveltekit/index.d.cts +111 -10
  60. package/dist/sveltekit/index.d.ts +111 -10
  61. package/dist/sveltekit/index.js +398 -15
  62. package/dist/sveltekit/live-preview-KO4IKWTX.js +1234 -0
  63. package/dist/sveltekit/live.cjs +1940 -0
  64. package/dist/sveltekit/live.d.cts +61 -0
  65. package/dist/sveltekit/live.d.ts +61 -0
  66. package/dist/sveltekit/live.js +220 -0
  67. package/package.json +132 -71
  68. package/src/astro/PreprToolbar.astro +7 -1
  69. package/src/astro/PreprTrackingPixel.astro +2 -4
  70. package/src/nuxt/PreprToolbar.vue +12 -1
  71. package/src/nuxt/PreprTrackingPixel.vue +2 -4
  72. package/src/sveltekit/PreprToolbar.svelte +17 -2
  73. package/src/sveltekit/PreprTrackingPixel.svelte +2 -4
  74. package/dist/astro/chunk-UN4JADNU.js +0 -173
  75. package/dist/astro/graphql.cjs +0 -1078
  76. package/dist/astro/graphql.d.cts +0 -300
  77. package/dist/astro/graphql.d.ts +0 -300
  78. package/dist/astro/graphql.js +0 -984
  79. package/dist/astro/index-XT_z-RYT.d.cts +0 -130
  80. package/dist/astro/index-XT_z-RYT.d.ts +0 -130
  81. package/dist/chunk-3NCEVJJ3.js +0 -10
  82. package/dist/chunk-S5RWVMDJ.js +0 -148
  83. package/dist/chunk-XL4Y7FGW.js +0 -499
  84. package/dist/graphql/codegen.cjs +0 -557
  85. package/dist/graphql/codegen.d.cts +0 -23
  86. package/dist/graphql/codegen.d.ts +0 -23
  87. package/dist/graphql/codegen.js +0 -99
  88. package/dist/graphql.cjs +0 -1020
  89. package/dist/graphql.d.cts +0 -335
  90. package/dist/graphql.d.ts +0 -335
  91. package/dist/graphql.js +0 -448
  92. package/dist/nextjs/chunk-CMV6ZP6E.js +0 -549
  93. package/dist/nextjs/graphql.cjs +0 -1836
  94. package/dist/nextjs/graphql.d.cts +0 -498
  95. package/dist/nextjs/graphql.d.ts +0 -498
  96. package/dist/nextjs/graphql.js +0 -1422
  97. package/dist/nextjs/server-BL-sqZvu.d.cts +0 -156
  98. package/dist/nextjs/server-BL-sqZvu.d.ts +0 -156
  99. package/dist/nuxt/chunk-XWOABVMW.js +0 -417
  100. package/dist/nuxt/graphql.cjs +0 -1085
  101. package/dist/nuxt/graphql.d.cts +0 -297
  102. package/dist/nuxt/graphql.d.ts +0 -297
  103. package/dist/nuxt/graphql.js +0 -985
  104. package/dist/nuxt/server-8v6OHbsw.d.cts +0 -158
  105. package/dist/nuxt/server-8v6OHbsw.d.ts +0 -158
  106. package/dist/pixel-DwW7cXJm.d.cts +0 -49
  107. package/dist/pixel-DwW7cXJm.d.ts +0 -49
  108. package/dist/server-Brr1UgtW.d.ts +0 -59
  109. package/dist/server-DJuS3YU0.d.cts +0 -59
  110. package/dist/sveltekit/chunk-3S5RA6G5.js +0 -413
  111. package/dist/sveltekit/graphql.cjs +0 -1091
  112. package/dist/sveltekit/graphql.d.cts +0 -302
  113. package/dist/sveltekit/graphql.d.ts +0 -302
  114. package/dist/sveltekit/graphql.js +0 -991
  115. package/dist/sveltekit/server-CO847mEV.d.cts +0 -98
  116. package/dist/sveltekit/server-CO847mEV.d.ts +0 -98
@@ -1,5 +1,144 @@
1
- import { P as PreprHeaders, b as PreprFeatures, c as PreprToolbarProps } from './server-8v6OHbsw.js';
2
- export { H as H3EventLike, d as PREPR_CONTEXT_KEY, a as PreprError, e as PreprMiddlewareOptions, f as extractAccessToken, g as getPreprHeadersFromEvent, h as handlePreprRequest, i as isPersonalizedResponse, v as validatePreprToken } from './server-8v6OHbsw.js';
1
+ /** A segment from Prepr, as listed in the toolbar's segment picker. */
2
+ interface PreprSegment {
3
+ readonly _id: string;
4
+ readonly name: string;
5
+ }
6
+ /**
7
+ * Per-feature config. `false` is shorthand for `{ enabled: false }`; the object
8
+ * form leaves room for per-feature options later without a breaking change.
9
+ */
10
+ type PreprFeatureConfig = boolean | {
11
+ enabled?: boolean;
12
+ };
13
+ /** Toolkit features a consumer can turn off. Omitted keys stay enabled. */
14
+ interface PreprFeatures {
15
+ /** Segment picker, `Prepr-Segments` header and its cookie/query param. */
16
+ segments?: PreprFeatureConfig;
17
+ /** A/B variant switch, `Prepr-ABtesting` header and its cookie/query param. */
18
+ abTesting?: PreprFeatureConfig;
19
+ /**
20
+ * The site's own click-to-edit: the toolbar's Edit mode control, the stega
21
+ * tooltip/overlay and the close-edit pill.
22
+ *
23
+ * NOT a security control, and NOT the Prepr editor's live preview. When the
24
+ * site is framed by the editor, `prepr:initVE` still activates edit mode —
25
+ * that is the CMS operating inside its own iframe, not an affordance offered
26
+ * to visitors. See iframe-bridge.ts.
27
+ */
28
+ editMode?: PreprFeatureConfig;
29
+ }
30
+ /**
31
+ * The data the toolbar shows. `getToolbarProps` builds it on the server from
32
+ * the request headers.
33
+ */
34
+ interface PreprToolbarProps {
35
+ /**
36
+ * Server-resolved active segment. Optional: omit it with `segments`
37
+ * disabled, where there is nothing to resolve. When enabled and omitted,
38
+ * the persisted cookie is used.
39
+ */
40
+ readonly activeSegment?: string | null;
41
+ /**
42
+ * Server-resolved active A/B variant. Optional: omit it with `abTesting`
43
+ * disabled, where there is nothing to resolve. When enabled and omitted,
44
+ * the persisted cookie is used.
45
+ */
46
+ readonly activeVariant?: string | null;
47
+ /** Available segments to personalize on. */
48
+ readonly segments?: readonly PreprSegment[];
49
+ /** @deprecated Alias for `segments`. */
50
+ readonly data?: readonly PreprSegment[];
51
+ }
52
+ /** The two sides of an A/B test. */
53
+ type PreprVariant = 'A' | 'B';
54
+ /**
55
+ * The headers to send with a Prepr GraphQL request so the API personalizes
56
+ * the response for this visitor. `getPreprHeaders` returns them; spread them
57
+ * into the request's `headers`.
58
+ */
59
+ interface PreprHeaders {
60
+ readonly 'prepr-customer-id'?: string;
61
+ readonly 'Prepr-Segments'?: string;
62
+ readonly 'Prepr-ABtesting'?: PreprVariant;
63
+ readonly 'Prepr-Preview-Bar'?: 'true';
64
+ readonly 'Prepr-Context-utm_source'?: string;
65
+ readonly 'Prepr-Context-utm_medium'?: string;
66
+ readonly 'Prepr-Context-utm_term'?: string;
67
+ readonly 'Prepr-Context-utm_content'?: string;
68
+ readonly 'Prepr-Context-utm_campaign'?: string;
69
+ readonly 'Prepr-Context-initial_referral'?: string;
70
+ readonly 'Prepr-Visitor-IP'?: string;
71
+ readonly 'Prepr-Hubspot-Id'?: string;
72
+ readonly 'Prepr-Customer-Id-Created'?: 'true';
73
+ /** The visitor's browser User-Agent, used by the API for device detection. */
74
+ readonly 'User-Agent'?: string;
75
+ /** @deprecated Never populated; the visitor's value is under `User-Agent`. */
76
+ readonly 'Prepr-User-Agent'?: string;
77
+ readonly 'Prepr-Package'?: string;
78
+ }
79
+ /** Why a `PreprError` was thrown; read it from `error.code`. */
80
+ type PreprErrorCode = 'INVALID_TOKEN' | 'MISSING_TOKEN' | 'HTTP_ERROR' | 'FETCH_ERROR' | 'INVALID_RESPONSE' | 'CONTEXT_ERROR';
81
+
82
+ /** Options for the Prepr middleware of every framework. */
83
+ interface PreprMiddlewareOptions {
84
+ /** Enable preview-mode headers (segment/AB overrides, preview bar). */
85
+ preview?: boolean;
86
+ /**
87
+ * Disable features app-wide. Pass the same object you give the toolbar: a
88
+ * disabled feature injects no header and persists no cookie, whatever the
89
+ * request carries.
90
+ */
91
+ features?: PreprFeatures;
92
+ /** Override the version reported in Prepr-Package (mainly for tests). */
93
+ version?: string;
94
+ }
95
+
96
+ /**
97
+ * Structural stand-in for h3's `H3Event`, so this package needs no build-time
98
+ * dependency on `h3`/`nuxt`. Only the fields `handlePreprRequest` uses.
99
+ *
100
+ * `node` ties this to Nitro's Node.js preset (the Nuxt default). Edge presets
101
+ * expose no raw Node request/response to fold headers back onto.
102
+ */
103
+ interface H3EventLike {
104
+ node: {
105
+ req: {
106
+ url?: string;
107
+ headers: Record<string, string | string[] | undefined>;
108
+ };
109
+ res: {
110
+ /** Node's `ServerResponse.appendHeader` (Node >= 18.3). */
111
+ appendHeader(name: string, value: string): unknown;
112
+ };
113
+ };
114
+ /** Request-scoped bag shared with route handlers and Vue via `useRequestEvent`. */
115
+ context: Record<string, unknown>;
116
+ }
117
+ /** Key under which `handlePreprRequest` mirrors the forwarded Prepr `Headers`. */
118
+ declare const PREPR_CONTEXT_KEY = "prepr";
119
+ /**
120
+ * Nuxt server middleware entry point — call it inside `defineEventHandler` in
121
+ * `server/middleware/prepr.ts`:
122
+ *
123
+ * ```ts
124
+ * export default defineEventHandler(event => {
125
+ * handlePreprRequest(event, { preview: import.meta.dev });
126
+ * });
127
+ * ```
128
+ *
129
+ * The computed Prepr headers are folded back onto the raw Node request
130
+ * (lowercased, as Node stores them), which is what `useRequestHeaders()` and
131
+ * downstream handlers read. The same `Headers` are mirrored onto
132
+ * `event.context.prepr` for callers who prefer an explicit read
133
+ * (`getPreprHeadersFromEvent`). Cookies are appended to the response.
134
+ */
135
+ declare function handlePreprRequest(event: H3EventLike, options?: PreprMiddlewareOptions): void;
136
+ /**
137
+ * Personalization headers to forward to your GraphQL fetch, from the h3 event.
138
+ * Empty `Headers` if `handlePreprRequest` did not run, so the result is always
139
+ * safe to spread.
140
+ */
141
+ declare function getPreprHeadersFromEvent(event: Pick<H3EventLike, 'context'>): Headers;
3
142
 
4
143
  /** Returns the Prepr Customer ID from the request headers. */
5
144
  declare function getPreprUUID(headers: Headers): string | null;
@@ -10,10 +149,32 @@ declare function getActiveVariant(headers: Headers): string | null;
10
149
  /** Returns all Prepr headers from the request headers. */
11
150
  declare function getPreprHeaders(headers: Headers): PreprHeaders;
12
151
  /**
13
- * Props needed to mount `PreprToolbar.vue`, from the request headers plus a
14
- * Prepr GraphQL token. Ungated — gate on preview mode yourself (e.g.
15
- * `import.meta.dev`).
152
+ * Props needed to mount the `PreprToolbar` component, from the request
153
+ * headers plus a Prepr GraphQL token.
154
+ *
155
+ * Ungated: call it only when your app is in preview mode. Resolve that however
156
+ * your deployment already does — the toolkit reads no environment variables of
157
+ * its own.
16
158
  */
17
159
  declare function getToolbarProps(headers: Headers, token: string, features?: PreprFeatures): Promise<PreprToolbarProps>;
18
160
 
19
- export { getActiveSegment, getActiveVariant, getPreprHeaders, getPreprUUID, getToolbarProps };
161
+ /** Error thrown by the token helpers and the segments fetch. */
162
+ declare class PreprError extends Error {
163
+ readonly code: PreprErrorCode;
164
+ readonly context?: string | undefined;
165
+ readonly originalError?: Error | undefined;
166
+ constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
167
+ }
168
+ /**
169
+ * Asserts `token` is the full `https://graphql.prepr.io/<token>` URL.
170
+ * @throws PreprError if the token is missing or not an HTTPS URL.
171
+ */
172
+ declare function validatePreprToken(token: string): void;
173
+ /**
174
+ * Pulls the access token out of a GraphQL URL: `https://graphql.prepr.io/abc123`
175
+ * -> `abc123`.
176
+ * @throws PreprError if the URL is not a valid `graphql.prepr.io` URL.
177
+ */
178
+ declare function extractAccessToken(graphqlUrl: string): string;
179
+
180
+ export { type H3EventLike, PREPR_CONTEXT_KEY, PreprError, type PreprMiddlewareOptions, extractAccessToken, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprHeadersFromEvent, getPreprUUID, getToolbarProps, handlePreprRequest, validatePreprToken };
@@ -1,19 +1,407 @@
1
1
  import {
2
- PREPR_CONTEXT_KEY,
3
- PreprError,
4
- extractAccessToken,
5
- getActiveSegmentFromHeaders,
6
- getActiveVariantFromHeaders,
7
- getPreprHeadersFromEvent,
8
- getPreprHeadersFromHeaders,
9
- getPreprUUIDFromHeaders,
10
- getToolbarPropsFromHeaders,
11
- handlePreprRequest,
12
- isPersonalizedResponse,
13
- validatePreprToken
14
- } from "./chunk-XWOABVMW.js";
2
+ COOKIE_HUBSPOT,
3
+ COOKIE_PREVIEW_MODE,
4
+ COOKIE_SEGMENT,
5
+ COOKIE_UID,
6
+ COOKIE_VARIANT,
7
+ ONE_YEAR_SECONDS,
8
+ PARAM_HIDE_BAR,
9
+ PARAM_SEGMENT,
10
+ PARAM_VARIANT
11
+ } from "./chunk-LUKVPOJ2.js";
12
+
13
+ // src/version.ts
14
+ var VERSION = "1.0.0-rc.2";
15
+
16
+ // src/core/features.ts
17
+ function isEnabled(config) {
18
+ if (typeof config === "boolean") return config;
19
+ return config?.enabled ?? true;
20
+ }
21
+ function resolveFeatures(features) {
22
+ return {
23
+ segments: isEnabled(features?.segments),
24
+ abTesting: isEnabled(features?.abTesting),
25
+ editMode: isEnabled(features?.editMode)
26
+ };
27
+ }
28
+ var ALL_FEATURES_ENABLED = Object.freeze({
29
+ segments: true,
30
+ abTesting: true,
31
+ editMode: true
32
+ });
33
+
34
+ // src/core/middleware.ts
35
+ var UTM_PARAMS = [
36
+ "utm_source",
37
+ "utm_medium",
38
+ "utm_term",
39
+ "utm_content",
40
+ "utm_campaign"
41
+ ];
42
+ var MAX_HEADER_VALUE_LENGTH = 2048;
43
+ function randomUUID() {
44
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
45
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
46
+ bytes[6] = bytes[6] & 15 | 64;
47
+ bytes[8] = bytes[8] & 63 | 128;
48
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
49
+ ""
50
+ );
51
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
52
+ }
53
+ function sanitizeHeaderValue(value) {
54
+ const stripped = value.replace(/[\u0000-\u001f\u007f]/g, "");
55
+ return stripped.length > MAX_HEADER_VALUE_LENGTH ? stripped.slice(0, MAX_HEADER_VALUE_LENGTH) : stripped;
56
+ }
57
+ function serializeCookie(cookie) {
58
+ const parts = [
59
+ `${cookie.name}=${encodeURIComponent(cookie.value)}`,
60
+ `Max-Age=${cookie.maxAge}`,
61
+ `Path=${cookie.path}`
62
+ ];
63
+ if (cookie.sameSite) {
64
+ parts.push(`SameSite=${cookie.sameSite}`);
65
+ }
66
+ if (cookie.secure) {
67
+ parts.push("Secure");
68
+ }
69
+ return parts.join("; ");
70
+ }
71
+ function parseCookies(request) {
72
+ const cookies = /* @__PURE__ */ new Map();
73
+ const header = request.headers.get("cookie");
74
+ if (!header) return cookies;
75
+ for (const part of header.split(";")) {
76
+ const eq = part.indexOf("=");
77
+ if (eq === -1) continue;
78
+ const name = part.slice(0, eq).trim();
79
+ const value = part.slice(eq + 1).trim();
80
+ if (!name) continue;
81
+ try {
82
+ cookies.set(name, decodeURIComponent(value));
83
+ } catch {
84
+ cookies.set(name, value);
85
+ }
86
+ }
87
+ return cookies;
88
+ }
89
+ function processFrameworkRequest(request, opts, framework) {
90
+ const requestHeaders = new Headers(request.headers);
91
+ const responseCookies = [];
92
+ const inboundPreprHeaders = [];
93
+ requestHeaders.forEach((_value, key) => {
94
+ if (key.toLowerCase().startsWith("prepr-")) {
95
+ inboundPreprHeaders.push(key);
96
+ }
97
+ });
98
+ for (const key of inboundPreprHeaders) {
99
+ requestHeaders.delete(key);
100
+ }
101
+ const requestCookies = parseCookies(request);
102
+ const url = new URL(request.url);
103
+ const searchParams = url.searchParams;
104
+ const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
105
+ const isSecure = forwardedProto ? forwardedProto === "https" : url.protocol === "https:";
106
+ const crossSite = isSecure ? { sameSite: "None", secure: true } : {};
107
+ for (const key of UTM_PARAMS) {
108
+ const value = searchParams.get(key);
109
+ if (value !== null) {
110
+ requestHeaders.set(`Prepr-Context-${key}`, sanitizeHeaderValue(value));
111
+ }
112
+ }
113
+ const referer = request.headers.get("referer");
114
+ if (referer) {
115
+ requestHeaders.set(
116
+ "Prepr-Context-initial_referral",
117
+ sanitizeHeaderValue(referer)
118
+ );
119
+ }
120
+ const userAgent = request.headers.get("user-agent");
121
+ if (userAgent) {
122
+ requestHeaders.set("User-Agent", sanitizeHeaderValue(userAgent));
123
+ }
124
+ const packageParts = [`@preprio/toolkit@${opts?.version ?? VERSION}`];
125
+ if (framework) packageParts.push(`framework=${framework}`);
126
+ packageParts.push(`preview=${opts?.preview ? "true" : "false"}`);
127
+ requestHeaders.set("Prepr-Package", packageParts.join("; "));
128
+ const ip = request.headers.get("Cf-Connecting-Ip") ?? request.headers.get("x-real-ip");
129
+ if (ip) {
130
+ requestHeaders.set("Prepr-Visitor-IP", sanitizeHeaderValue(ip));
131
+ }
132
+ const hutkCookie = requestCookies.get(COOKIE_HUBSPOT);
133
+ if (hutkCookie) {
134
+ requestHeaders.set("Prepr-Hubspot-Id", sanitizeHeaderValue(hutkCookie));
135
+ }
136
+ let uid = sanitizeHeaderValue(requestCookies.get(COOKIE_UID) ?? "");
137
+ if (!uid) {
138
+ uid = randomUUID();
139
+ responseCookies.push({
140
+ name: COOKIE_UID,
141
+ value: uid,
142
+ maxAge: ONE_YEAR_SECONDS,
143
+ path: "/"
144
+ });
145
+ requestHeaders.set("Prepr-Customer-Id-Created", "true");
146
+ }
147
+ requestHeaders.set("Prepr-Customer-Id", uid);
148
+ if (!opts?.preview) {
149
+ return { requestHeaders, responseCookies };
150
+ }
151
+ const features = resolveFeatures(opts?.features);
152
+ const hasPreviewParams = features.segments && searchParams.has(PARAM_SEGMENT) || features.abTesting && searchParams.has(PARAM_VARIANT);
153
+ if (!hasPreviewParams) {
154
+ const previewModeCookie = requestCookies.get(COOKIE_PREVIEW_MODE);
155
+ const previewModeEnabled = previewModeCookie !== "false";
156
+ if (!previewModeEnabled) {
157
+ return { requestHeaders, responseCookies };
158
+ }
159
+ }
160
+ requestHeaders.set("Prepr-Preview-Bar", "true");
161
+ const isLivePreview = searchParams.get(PARAM_HIDE_BAR) === "true";
162
+ if (!isLivePreview && !requestCookies.has(COOKIE_PREVIEW_MODE)) {
163
+ responseCookies.push({
164
+ name: COOKIE_PREVIEW_MODE,
165
+ value: "true",
166
+ maxAge: ONE_YEAR_SECONDS,
167
+ path: "/",
168
+ ...crossSite
169
+ });
170
+ }
171
+ if (!isLivePreview) {
172
+ const segmentCookie = features.segments ? requestCookies.get(COOKIE_SEGMENT) : void 0;
173
+ if (segmentCookie) {
174
+ requestHeaders.set("Prepr-Segments", sanitizeHeaderValue(segmentCookie));
175
+ }
176
+ const abCookie = features.abTesting ? requestCookies.get(COOKIE_VARIANT) : void 0;
177
+ if (abCookie) {
178
+ requestHeaders.set("Prepr-ABtesting", sanitizeHeaderValue(abCookie));
179
+ }
180
+ }
181
+ const previewAb = features.abTesting ? searchParams.get(PARAM_VARIANT) : null;
182
+ if (previewAb !== null) {
183
+ requestHeaders.set("Prepr-ABtesting", sanitizeHeaderValue(previewAb));
184
+ if (!isLivePreview) {
185
+ responseCookies.push({
186
+ name: COOKIE_VARIANT,
187
+ value: previewAb,
188
+ maxAge: ONE_YEAR_SECONDS,
189
+ path: "/",
190
+ ...crossSite
191
+ });
192
+ }
193
+ }
194
+ const previewSegment = features.segments ? searchParams.get(PARAM_SEGMENT) : null;
195
+ if (previewSegment !== null) {
196
+ requestHeaders.set("Prepr-Segments", sanitizeHeaderValue(previewSegment));
197
+ if (!isLivePreview) {
198
+ responseCookies.push({
199
+ name: COOKIE_SEGMENT,
200
+ value: previewSegment,
201
+ maxAge: ONE_YEAR_SECONDS,
202
+ path: "/",
203
+ ...crossSite
204
+ });
205
+ }
206
+ }
207
+ return { requestHeaders, responseCookies };
208
+ }
209
+
210
+ // src/nuxt/middleware.ts
211
+ var PREPR_CONTEXT_KEY = "prepr";
212
+ function handlePreprRequest(event, options) {
213
+ const req = event.node.req;
214
+ const host = typeof req.headers.host === "string" ? req.headers.host : "localhost";
215
+ const request = new Request(`http://${host}${req.url ?? "/"}`);
216
+ for (const [key, value] of Object.entries(req.headers)) {
217
+ if (typeof value === "string") {
218
+ request.headers.set(key, value);
219
+ } else if (Array.isArray(value)) {
220
+ request.headers.set(key, value.join(", "));
221
+ }
222
+ }
223
+ const { requestHeaders, responseCookies } = processFrameworkRequest(
224
+ request,
225
+ options,
226
+ "nuxt"
227
+ );
228
+ requestHeaders.forEach((value, key) => {
229
+ req.headers[key.toLowerCase()] = value;
230
+ });
231
+ event.context[PREPR_CONTEXT_KEY] = requestHeaders;
232
+ for (const cookie of responseCookies) {
233
+ event.node.res.appendHeader("Set-Cookie", serializeCookie(cookie));
234
+ }
235
+ }
236
+ function getPreprHeadersFromEvent(event) {
237
+ const headers = event.context[PREPR_CONTEXT_KEY];
238
+ return headers instanceof Headers ? headers : new Headers();
239
+ }
240
+
241
+ // src/core/server.ts
242
+ var PreprError = class extends Error {
243
+ constructor(message, code, context, originalError) {
244
+ super(message);
245
+ this.code = code;
246
+ this.context = context;
247
+ this.originalError = originalError;
248
+ this.name = "PreprError";
249
+ }
250
+ };
251
+ function getPreprUUIDFromHeaders(headers) {
252
+ return headers.get("prepr-customer-id");
253
+ }
254
+ function getActiveSegmentFromHeaders(headers) {
255
+ return headers.get("Prepr-Segments");
256
+ }
257
+ function getActiveVariantFromHeaders(headers) {
258
+ return headers.get("Prepr-ABtesting");
259
+ }
260
+ var PREPR_HEADER_KEYS = [
261
+ "prepr-customer-id",
262
+ "Prepr-Segments",
263
+ "Prepr-ABtesting",
264
+ "Prepr-Preview-Bar",
265
+ "Prepr-Context-utm_source",
266
+ "Prepr-Context-utm_medium",
267
+ "Prepr-Context-utm_term",
268
+ "Prepr-Context-utm_content",
269
+ "Prepr-Context-utm_campaign",
270
+ "Prepr-Context-initial_referral",
271
+ "Prepr-Visitor-IP",
272
+ "Prepr-Hubspot-Id",
273
+ "Prepr-Customer-Id-Created",
274
+ "User-Agent",
275
+ "Prepr-Package"
276
+ ];
277
+ function getPreprHeadersFromHeaders(headers) {
278
+ const preprHeaders = {};
279
+ const copy = (key) => {
280
+ const value = headers.get(key);
281
+ if (value !== null) {
282
+ preprHeaders[key] = value;
283
+ }
284
+ };
285
+ for (const key of PREPR_HEADER_KEYS) {
286
+ copy(key);
287
+ }
288
+ return preprHeaders;
289
+ }
290
+ function validatePreprToken(token) {
291
+ if (!token) {
292
+ throw new PreprError(
293
+ "Token is required",
294
+ "MISSING_TOKEN",
295
+ "validatePreprToken"
296
+ );
297
+ }
298
+ if (!token.startsWith("https://")) {
299
+ throw new PreprError(
300
+ "Token must be a valid HTTPS URL",
301
+ "INVALID_TOKEN",
302
+ "validatePreprToken"
303
+ );
304
+ }
305
+ }
306
+ function extractAccessToken(graphqlUrl) {
307
+ let url;
308
+ try {
309
+ url = new URL(graphqlUrl);
310
+ } catch (error) {
311
+ throw new PreprError(
312
+ "Token must be a valid URL",
313
+ "INVALID_TOKEN",
314
+ "extractAccessToken",
315
+ error instanceof Error ? error : new Error(String(error))
316
+ );
317
+ }
318
+ if (url.hostname !== "graphql.prepr.io") {
319
+ throw new PreprError(
320
+ "Token must be a graphql.prepr.io URL",
321
+ "INVALID_TOKEN",
322
+ "extractAccessToken"
323
+ );
324
+ }
325
+ const pathParts = url.pathname.split("/");
326
+ const token = pathParts[pathParts.length - 1];
327
+ if (!token) {
328
+ throw new PreprError(
329
+ "Token URL is missing an access token segment",
330
+ "INVALID_TOKEN",
331
+ "extractAccessToken"
332
+ );
333
+ }
334
+ return token;
335
+ }
336
+ async function getPreprEnvironmentSegments(token) {
337
+ validatePreprToken(token);
338
+ try {
339
+ const response = await fetch(token, {
340
+ headers: {
341
+ "Prepr-Package": `@preprio/toolkit@${VERSION}`,
342
+ // Duplicates the version in Prepr-Package. It keeps the User-Agent
343
+ // format used by `@preprio/prepr-nextjs`, for Prepr API consumers that
344
+ // still identify the toolbar by that string.
345
+ "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
346
+ "Content-Type": "application/json"
347
+ },
348
+ method: "POST",
349
+ body: JSON.stringify({
350
+ query: `{
351
+ _Segments {
352
+ _id
353
+ name
354
+ }
355
+ }`
356
+ })
357
+ });
358
+ if (!response.ok) {
359
+ throw new PreprError(
360
+ `HTTP ${response.status}: ${response.statusText}`,
361
+ "HTTP_ERROR",
362
+ "getPreprEnvironmentSegments"
363
+ );
364
+ }
365
+ const json = await response.json();
366
+ if (!json || !json.data || !json.data._Segments) {
367
+ throw new PreprError(
368
+ "Invalid response format from Prepr API",
369
+ "INVALID_RESPONSE",
370
+ "getPreprEnvironmentSegments"
371
+ );
372
+ }
373
+ return json.data._Segments;
374
+ } catch (error) {
375
+ if (error instanceof PreprError) {
376
+ throw error;
377
+ }
378
+ throw new PreprError(
379
+ "Failed to fetch segments from Prepr API",
380
+ "FETCH_ERROR",
381
+ "getPreprEnvironmentSegments",
382
+ error instanceof Error ? error : new Error(String(error))
383
+ );
384
+ }
385
+ }
386
+ async function getToolbarPropsFromHeaders(headers, token, features) {
387
+ const resolved = resolveFeatures(features);
388
+ let segments = [];
389
+ if (resolved.segments) {
390
+ try {
391
+ segments = await getPreprEnvironmentSegments(token);
392
+ } catch {
393
+ segments = [];
394
+ }
395
+ }
396
+ return {
397
+ activeSegment: resolved.segments ? getActiveSegmentFromHeaders(headers) : null,
398
+ activeVariant: resolved.abTesting ? getActiveVariantFromHeaders(headers) : null,
399
+ segments,
400
+ data: segments
401
+ };
402
+ }
15
403
 
16
- // src/nuxt/server.ts
404
+ // src/core/request-helpers.ts
17
405
  function getPreprUUID(headers) {
18
406
  return getPreprUUIDFromHeaders(headers);
19
407
  }
@@ -40,6 +428,5 @@ export {
40
428
  getPreprUUID,
41
429
  getToolbarProps,
42
430
  handlePreprRequest,
43
- isPersonalizedResponse,
44
431
  validatePreprToken
45
432
  };