@preprio/toolkit 0.5.0-rc.2 → 0.6.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +308 -27
  2. package/dist/astro/chunk-3UVUDDNY.js +173 -0
  3. package/dist/astro/graphql.cjs +983 -0
  4. package/dist/astro/graphql.d.cts +231 -0
  5. package/dist/astro/graphql.d.ts +231 -0
  6. package/dist/astro/graphql.js +893 -0
  7. package/dist/astro/index-XT_z-RYT.d.cts +130 -0
  8. package/dist/astro/index-XT_z-RYT.d.ts +130 -0
  9. package/dist/astro/index.cjs +14 -1
  10. package/dist/astro/index.d.cts +1 -120
  11. package/dist/astro/index.d.ts +1 -120
  12. package/dist/astro/index.js +15 -153
  13. package/dist/{chunk-FLPNN3CV.js → chunk-BJ2LBLWO.js} +71 -276
  14. package/dist/chunk-DGZA7KX7.js +172 -0
  15. package/dist/chunk-YR7P4IWE.js +187 -0
  16. package/dist/graphql.cjs +894 -0
  17. package/dist/graphql.d.cts +231 -0
  18. package/dist/graphql.d.ts +231 -0
  19. package/dist/graphql.js +787 -0
  20. package/dist/index.cjs +76 -119
  21. package/dist/index.d.cts +12 -64
  22. package/dist/index.d.ts +12 -64
  23. package/dist/index.js +23 -167
  24. package/dist/nextjs/chunk-U4HXENF7.js +231 -0
  25. package/dist/nextjs/components.cjs +190 -122
  26. package/dist/nextjs/components.d.cts +33 -2
  27. package/dist/nextjs/components.d.ts +33 -2
  28. package/dist/nextjs/components.js +132 -4
  29. package/dist/nextjs/graphql.cjs +1315 -0
  30. package/dist/nextjs/graphql.d.cts +361 -0
  31. package/dist/nextjs/graphql.d.ts +361 -0
  32. package/dist/nextjs/graphql.js +1218 -0
  33. package/dist/nextjs/index.cjs +126 -6
  34. package/dist/nextjs/index.d.cts +53 -147
  35. package/dist/nextjs/index.d.ts +53 -147
  36. package/dist/nextjs/index.js +113 -203
  37. package/dist/nextjs/server-CjpELYvq.d.cts +156 -0
  38. package/dist/nextjs/server-CjpELYvq.d.ts +156 -0
  39. package/dist/nuxt/chunk-P6ENNAEE.js +417 -0
  40. package/dist/nuxt/graphql.cjs +990 -0
  41. package/dist/nuxt/graphql.d.cts +228 -0
  42. package/dist/nuxt/graphql.d.ts +228 -0
  43. package/dist/nuxt/graphql.js +894 -0
  44. package/dist/nuxt/index.cjs +14 -1
  45. package/dist/nuxt/index.d.cts +3 -148
  46. package/dist/nuxt/index.d.ts +3 -148
  47. package/dist/nuxt/index.js +15 -391
  48. package/dist/nuxt/server-8v6OHbsw.d.cts +158 -0
  49. package/dist/nuxt/server-8v6OHbsw.d.ts +158 -0
  50. package/dist/pixel-DwW7cXJm.d.cts +49 -0
  51. package/dist/pixel-DwW7cXJm.d.ts +49 -0
  52. package/dist/react/components.cjs +88 -120
  53. package/dist/react/components.d.cts +2 -8
  54. package/dist/react/components.d.ts +2 -8
  55. package/dist/react/components.js +88 -120
  56. package/dist/server-Brr1UgtW.d.ts +59 -0
  57. package/dist/server-DJuS3YU0.d.cts +59 -0
  58. package/dist/sveltekit/chunk-FSARVMG5.js +413 -0
  59. package/dist/sveltekit/graphql.cjs +996 -0
  60. package/dist/sveltekit/graphql.d.cts +233 -0
  61. package/dist/sveltekit/graphql.d.ts +233 -0
  62. package/dist/sveltekit/graphql.js +900 -0
  63. package/dist/sveltekit/index.cjs +14 -1
  64. package/dist/sveltekit/index.d.cts +3 -88
  65. package/dist/sveltekit/index.d.ts +3 -88
  66. package/dist/sveltekit/index.js +15 -387
  67. package/dist/sveltekit/server-CO847mEV.d.cts +98 -0
  68. package/dist/sveltekit/server-CO847mEV.d.ts +98 -0
  69. package/dist/{pixel-B3oQNbZ3.d.cts → types-BYH9XqmN.d.cts} +4 -58
  70. package/dist/{pixel-B3oQNbZ3.d.ts → types-BYH9XqmN.d.ts} +4 -58
  71. package/package.json +31 -1
@@ -0,0 +1,172 @@
1
+ // src/version.ts
2
+ var VERSION = "0.6.0-alpha.0";
3
+
4
+ // src/core/features.ts
5
+ function isEnabled(config) {
6
+ if (typeof config === "boolean") return config;
7
+ return config?.enabled ?? true;
8
+ }
9
+ function resolveFeatures(features) {
10
+ return {
11
+ segments: isEnabled(features?.segments),
12
+ abTesting: isEnabled(features?.abTesting),
13
+ editMode: isEnabled(features?.editMode)
14
+ };
15
+ }
16
+ var ALL_FEATURES_ENABLED = Object.freeze({
17
+ segments: true,
18
+ abTesting: true,
19
+ editMode: true
20
+ });
21
+
22
+ // src/core/stega/clean.ts
23
+ import { vercelStegaClean, vercelStegaDecode } from "@vercel/stega";
24
+
25
+ // src/core/utils.ts
26
+ var trustedParentOrigin = null;
27
+ function setTrustedParentOrigin(origin) {
28
+ trustedParentOrigin = origin;
29
+ }
30
+ function sendPreprEvent(event, data, options) {
31
+ if (typeof window !== "undefined") {
32
+ const message = {
33
+ name: "prepr_preview_bar",
34
+ event,
35
+ ...data
36
+ };
37
+ window.dispatchEvent(
38
+ new CustomEvent("prepr_preview_bar", { detail: message })
39
+ );
40
+ if (window.parent && window.parent !== window) {
41
+ if (trustedParentOrigin) {
42
+ window.parent.postMessage(message, trustedParentOrigin);
43
+ } else if (options?.allowUntrustedTarget) {
44
+ window.parent.postMessage(message, "*");
45
+ }
46
+ }
47
+ }
48
+ }
49
+ var DebugLogger = class {
50
+ constructor(options) {
51
+ this.options = {
52
+ prefix: "[Prepr]",
53
+ ...options
54
+ };
55
+ }
56
+ // A local `enabled` wins; otherwise defer to the global logger so scoped
57
+ // loggers created before initDebugLogger() still pick up the setting.
58
+ isEnabled() {
59
+ if (this.options.enabled !== void 0) {
60
+ return this.options.enabled;
61
+ }
62
+ return globalDebugLogger?.options?.enabled ?? false;
63
+ }
64
+ log(message, ...args) {
65
+ if (!this.isEnabled()) return;
66
+ const prefix = this.options.prefix;
67
+ console.log(`${prefix} ${message}`, ...args);
68
+ }
69
+ warn(message, ...args) {
70
+ if (!this.isEnabled()) return;
71
+ const prefix = this.options.prefix;
72
+ console.warn(`${prefix} ${message}`, ...args);
73
+ }
74
+ error(message, ...args) {
75
+ if (!this.isEnabled()) return;
76
+ const prefix = this.options.prefix;
77
+ console.error(`${prefix} ${message}`, ...args);
78
+ }
79
+ };
80
+ var globalDebugLogger = null;
81
+ function initDebugLogger(enabled = false) {
82
+ globalDebugLogger = new DebugLogger({ enabled });
83
+ }
84
+ function createScopedLogger(scopeName) {
85
+ return new DebugLogger({
86
+ prefix: `[Prepr][${scopeName}]`
87
+ });
88
+ }
89
+ function throttle(func, delay) {
90
+ let timeoutId = null;
91
+ let lastExecTime = 0;
92
+ const throttledFunc = ((...args) => {
93
+ const currentTime = Date.now();
94
+ const timeSinceLastExec = currentTime - lastExecTime;
95
+ if (timeSinceLastExec >= delay) {
96
+ func(...args);
97
+ lastExecTime = currentTime;
98
+ } else {
99
+ if (timeoutId) {
100
+ clearTimeout(timeoutId);
101
+ }
102
+ timeoutId = setTimeout(() => {
103
+ func(...args);
104
+ lastExecTime = Date.now();
105
+ timeoutId = null;
106
+ }, delay - timeSinceLastExec);
107
+ }
108
+ });
109
+ throttledFunc.cancel = () => {
110
+ if (timeoutId) {
111
+ clearTimeout(timeoutId);
112
+ timeoutId = null;
113
+ }
114
+ };
115
+ return throttledFunc;
116
+ }
117
+ function createElementCache(query, ttl = 1e3) {
118
+ let cache = null;
119
+ let lastCacheTime = 0;
120
+ return () => {
121
+ const now = Date.now();
122
+ if (!cache || now - lastCacheTime > ttl) {
123
+ cache = document.querySelectorAll(query);
124
+ lastCacheTime = now;
125
+ }
126
+ return cache;
127
+ };
128
+ }
129
+
130
+ // src/core/stega/clean.ts
131
+ var debug = createScopedLogger("stega:clean");
132
+ function stegaClean(text) {
133
+ if (!text) return text;
134
+ return vercelStegaClean(text);
135
+ }
136
+ function decodeStega(str) {
137
+ if (!str) return null;
138
+ try {
139
+ const decoded = vercelStegaDecode(str);
140
+ if (decoded?.href) {
141
+ return decoded;
142
+ }
143
+ } catch (error) {
144
+ debug.log("error decoding stega data", error);
145
+ const match = str.match(/{"origin.*?}/);
146
+ if (match) {
147
+ try {
148
+ const decodedMatch = vercelStegaDecode(match[0]);
149
+ if (decodedMatch?.href) {
150
+ return decodedMatch;
151
+ }
152
+ } catch (innerError) {
153
+ debug.log("error decoding stega regex match", innerError);
154
+ }
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+
160
+ export {
161
+ VERSION,
162
+ resolveFeatures,
163
+ ALL_FEATURES_ENABLED,
164
+ setTrustedParentOrigin,
165
+ sendPreprEvent,
166
+ initDebugLogger,
167
+ createScopedLogger,
168
+ throttle,
169
+ createElementCache,
170
+ stegaClean,
171
+ decodeStega
172
+ };
@@ -0,0 +1,187 @@
1
+ import {
2
+ VERSION,
3
+ resolveFeatures
4
+ } from "./chunk-DGZA7KX7.js";
5
+
6
+ // src/core/personalization.ts
7
+ var PERSONALIZED_VARY = /\bPrepr-(Segments|ABTesting)/i;
8
+ function isPersonalizedResponse(source) {
9
+ const headers = "headers" in source ? source.headers : source;
10
+ return PERSONALIZED_VARY.test(headers.get("vary") ?? "");
11
+ }
12
+
13
+ // src/core/server.ts
14
+ var PreprError = class extends Error {
15
+ constructor(message, code, context, originalError) {
16
+ super(message);
17
+ this.code = code;
18
+ this.context = context;
19
+ this.originalError = originalError;
20
+ this.name = "PreprError";
21
+ }
22
+ };
23
+ function getPreprUUIDFromHeaders(headers) {
24
+ return headers.get("prepr-customer-id");
25
+ }
26
+ function getActiveSegmentFromHeaders(headers) {
27
+ return headers.get("Prepr-Segments");
28
+ }
29
+ function getActiveVariantFromHeaders(headers) {
30
+ return headers.get("Prepr-ABtesting");
31
+ }
32
+ var PREPR_HEADER_KEYS = [
33
+ "prepr-customer-id",
34
+ "Prepr-Segments",
35
+ "Prepr-ABtesting",
36
+ "Prepr-Preview-Bar",
37
+ "Prepr-Context-utm_source",
38
+ "Prepr-Context-utm_medium",
39
+ "Prepr-Context-utm_term",
40
+ "Prepr-Context-utm_content",
41
+ "Prepr-Context-utm_campaign",
42
+ "Prepr-Context-initial_referral",
43
+ "Prepr-Visitor-IP",
44
+ "Prepr-Hubspot-Id",
45
+ "Prepr-Customer-Id-Created",
46
+ "User-Agent",
47
+ "Prepr-Package"
48
+ ];
49
+ function getPreprHeadersFromHeaders(headers) {
50
+ const preprHeaders = {};
51
+ const copy = (key) => {
52
+ const value = headers.get(key);
53
+ if (value !== null) {
54
+ preprHeaders[key] = value;
55
+ }
56
+ };
57
+ for (const key of PREPR_HEADER_KEYS) {
58
+ copy(key);
59
+ }
60
+ return preprHeaders;
61
+ }
62
+ function validatePreprToken(token) {
63
+ if (!token) {
64
+ throw new PreprError(
65
+ "Token is required",
66
+ "MISSING_TOKEN",
67
+ "validatePreprToken"
68
+ );
69
+ }
70
+ if (!token.startsWith("https://")) {
71
+ throw new PreprError(
72
+ "Token must be a valid HTTPS URL",
73
+ "INVALID_TOKEN",
74
+ "validatePreprToken"
75
+ );
76
+ }
77
+ }
78
+ function extractAccessToken(graphqlUrl) {
79
+ let url;
80
+ try {
81
+ url = new URL(graphqlUrl);
82
+ } catch (error) {
83
+ throw new PreprError(
84
+ "Token must be a valid URL",
85
+ "INVALID_TOKEN",
86
+ "extractAccessToken",
87
+ error instanceof Error ? error : new Error(String(error))
88
+ );
89
+ }
90
+ if (url.hostname !== "graphql.prepr.io") {
91
+ throw new PreprError(
92
+ "Token must be a graphql.prepr.io URL",
93
+ "INVALID_TOKEN",
94
+ "extractAccessToken"
95
+ );
96
+ }
97
+ const pathParts = url.pathname.split("/");
98
+ const token = pathParts[pathParts.length - 1];
99
+ if (!token) {
100
+ throw new PreprError(
101
+ "Token URL is missing an access token segment",
102
+ "INVALID_TOKEN",
103
+ "extractAccessToken"
104
+ );
105
+ }
106
+ return token;
107
+ }
108
+ async function getPreprEnvironmentSegments(token) {
109
+ validatePreprToken(token);
110
+ try {
111
+ const response = await fetch(token, {
112
+ headers: {
113
+ "Prepr-Package": `@preprio/toolkit@${VERSION}`,
114
+ // Duplicates the version in Prepr-Package. It keeps the User-Agent
115
+ // format used by `@preprio/prepr-nextjs`, for Prepr API consumers that
116
+ // still identify the toolbar by that string.
117
+ "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
118
+ "Content-Type": "application/json"
119
+ },
120
+ method: "POST",
121
+ body: JSON.stringify({
122
+ query: `{
123
+ _Segments {
124
+ _id
125
+ name
126
+ }
127
+ }`
128
+ })
129
+ });
130
+ if (!response.ok) {
131
+ throw new PreprError(
132
+ `HTTP ${response.status}: ${response.statusText}`,
133
+ "HTTP_ERROR",
134
+ "getPreprEnvironmentSegments"
135
+ );
136
+ }
137
+ const json = await response.json();
138
+ if (!json || !json.data || !json.data._Segments) {
139
+ throw new PreprError(
140
+ "Invalid response format from Prepr API",
141
+ "INVALID_RESPONSE",
142
+ "getPreprEnvironmentSegments"
143
+ );
144
+ }
145
+ return json.data._Segments;
146
+ } catch (error) {
147
+ if (error instanceof PreprError) {
148
+ throw error;
149
+ }
150
+ throw new PreprError(
151
+ "Failed to fetch segments from Prepr API",
152
+ "FETCH_ERROR",
153
+ "getPreprEnvironmentSegments",
154
+ error instanceof Error ? error : new Error(String(error))
155
+ );
156
+ }
157
+ }
158
+ async function getToolbarPropsFromHeaders(headers, token, features) {
159
+ const resolved = resolveFeatures(features);
160
+ let segments = [];
161
+ if (resolved.segments) {
162
+ try {
163
+ segments = await getPreprEnvironmentSegments(token);
164
+ } catch {
165
+ segments = [];
166
+ }
167
+ }
168
+ return {
169
+ activeSegment: resolved.segments ? getActiveSegmentFromHeaders(headers) : null,
170
+ activeVariant: resolved.abTesting ? getActiveVariantFromHeaders(headers) : null,
171
+ segments,
172
+ data: segments
173
+ };
174
+ }
175
+
176
+ export {
177
+ isPersonalizedResponse,
178
+ PreprError,
179
+ getPreprUUIDFromHeaders,
180
+ getActiveSegmentFromHeaders,
181
+ getActiveVariantFromHeaders,
182
+ getPreprHeadersFromHeaders,
183
+ validatePreprToken,
184
+ extractAccessToken,
185
+ getPreprEnvironmentSegments,
186
+ getToolbarPropsFromHeaders
187
+ };