@preprio/toolkit 0.6.0-alpha.8 → 1.0.0-rc.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.
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-ATPB7GEC.js → chunk-33GWVTRJ.js} +1 -1
  7. package/dist/chunk-A2J7R4LR.js +256 -0
  8. package/dist/{chunk-T7ESBVBI.js → chunk-DSJ22P6J.js} +6 -1
  9. package/dist/chunk-KM2GME62.js +1255 -0
  10. package/dist/chunk-UTKH7DOI.js +58 -0
  11. package/dist/chunk-V7MCHPE7.js +85 -0
  12. package/dist/{chunk-2QGUP7VQ.js → chunk-WBMN4L7G.js} +1680 -579
  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 -729
  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 -274
  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-R2YPGDVU.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-OY7OKO6Q.js +0 -499
  83. package/dist/chunk-S5RWVMDJ.js +0 -148
  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-O2SBSBDG.js +0 -549
  93. package/dist/nextjs/graphql.cjs +0 -1811
  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 -1397
  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-SX3MSVPK.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-UOASSHZO.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,985 +0,0 @@
1
- import {
2
- PreprError,
3
- getPreprHeadersFromEvent,
4
- getPreprHeadersFromHeaders,
5
- isPersonalizedResponse,
6
- validatePreprToken
7
- } from "./chunk-SX3MSVPK.js";
8
-
9
- // src/core/variants/constants.ts
10
- var PREPR_CONTEXT_ALIAS = "_preprContext";
11
- var PREPR_TYPE_ALIAS = "_preprType";
12
- var PREPR_DEFAULT_VARIANT = "ALL_OTHER_USERS";
13
-
14
- // src/core/variants/ast.ts
15
- import { parse } from "graphql/language/parser.js";
16
- var name = (value) => ({ kind: "Name", value });
17
- function selectionSet(selections) {
18
- return { kind: "SelectionSet", selections };
19
- }
20
- function contextField(withKey) {
21
- const fields = ["kind", "group_id", "variant_id"];
22
- if (withKey) fields.push("variant_key");
23
- return {
24
- kind: "Field",
25
- alias: name(PREPR_CONTEXT_ALIAS),
26
- name: name("_context"),
27
- selectionSet: selectionSet(
28
- fields.map(
29
- (field) => ({ kind: "Field", name: name(field) })
30
- )
31
- )
32
- };
33
- }
34
- function typenameField() {
35
- return {
36
- kind: "Field",
37
- alias: name(PREPR_TYPE_ALIAS),
38
- name: name("__typename")
39
- };
40
- }
41
- function inlineFragment(typeName, selections) {
42
- return {
43
- kind: "InlineFragment",
44
- typeCondition: { kind: "NamedType", name: name(typeName) },
45
- selectionSet: selectionSet(selections)
46
- };
47
- }
48
- function contextSelections(typeName, schema, onlyTypes, withType = true) {
49
- const fields = () => withType ? [contextField(true), typenameField()] : [contextField(false)];
50
- const type = schema.types[typeName];
51
- if (!type) return [];
52
- if (type.possibleTypes.length > 0) {
53
- return type.possibleTypes.filter(
54
- (member) => schema.types[member]?.hasContext && (!onlyTypes || onlyTypes.has(member))
55
- ).map((member) => inlineFragment(member, fields()));
56
- }
57
- return type.hasContext ? fields() : [];
58
- }
59
- function withoutPersonalizeArg(args = []) {
60
- return args.filter((arg) => arg.name.value !== "personalize");
61
- }
62
- function documentOf(document2) {
63
- if (typeof document2 === "string") return parse(document2);
64
- if (document2 instanceof String) return parse(document2.toString());
65
- return document2;
66
- }
67
- function collectVariables(node, used) {
68
- if (!node || typeof node !== "object") return;
69
- if (Array.isArray(node)) {
70
- for (const item of node) collectVariables(item, used);
71
- return;
72
- }
73
- const value = node;
74
- if (value.kind === "Variable") {
75
- used.add(value.name.value);
76
- return;
77
- }
78
- for (const key of Object.keys(value)) {
79
- if (key !== "loc") collectVariables(value[key], used);
80
- }
81
- }
82
-
83
- // src/core/variants/decision-document.ts
84
- function decisionSelectionSet(set, typeName, path, ctx) {
85
- const selections = [];
86
- for (const selection of set.selections) {
87
- if (selection.kind === "FragmentSpread") {
88
- const fragment = ctx.fragments[selection.name.value];
89
- if (!fragment) continue;
90
- const pruned = decisionSelectionSet(
91
- fragment.selectionSet,
92
- fragment.typeCondition.name.value,
93
- path,
94
- ctx
95
- );
96
- if (!pruned) continue;
97
- if (fragment.typeCondition.name.value === typeName) {
98
- selections.push(...pruned.selections);
99
- } else {
100
- selections.push(
101
- inlineFragment(fragment.typeCondition.name.value, [
102
- ...pruned.selections
103
- ])
104
- );
105
- }
106
- continue;
107
- }
108
- if (selection.kind === "InlineFragment") {
109
- const condition = selection.typeCondition?.name.value ?? typeName;
110
- const pruned = decisionSelectionSet(
111
- selection.selectionSet,
112
- condition,
113
- path,
114
- ctx
115
- );
116
- if (!pruned) continue;
117
- if (condition === typeName && !selection.directives?.length) {
118
- selections.push(...pruned.selections);
119
- } else {
120
- selections.push({ ...selection, selectionSet: pruned });
121
- }
122
- continue;
123
- }
124
- if (!selection.selectionSet) continue;
125
- const field = ctx.schema.types[typeName]?.fields[selection.name.value];
126
- if (!field) continue;
127
- const key = selection.alias?.value ?? selection.name.value;
128
- const fieldPath = path ? `${path}.${key}` : key;
129
- if (ctx.paths && !ctx.paths.prefixes.has(fieldPath)) continue;
130
- const child = decisionSelectionSet(
131
- selection.selectionSet,
132
- field.type,
133
- fieldPath,
134
- ctx
135
- );
136
- const groupTypes = ctx.paths?.groups.get(fieldPath);
137
- const holdsGroups = field.personalizable && (!ctx.paths || groupTypes !== void 0);
138
- if (holdsGroups) {
139
- selections.push({
140
- ...selection,
141
- arguments: withoutPersonalizeArg(selection.arguments),
142
- selectionSet: selectionSet([
143
- ...ctx.topLevelOnly ? [] : child?.selections ?? [],
144
- ...contextSelections(
145
- field.type,
146
- ctx.schema,
147
- groupTypes && !groupTypes.has("*") ? groupTypes : void 0,
148
- false
149
- )
150
- ])
151
- });
152
- } else if (child) {
153
- selections.push({
154
- ...selection,
155
- arguments: field.personalizable ? withoutPersonalizeArg(selection.arguments) : selection.arguments,
156
- selectionSet: child
157
- });
158
- }
159
- }
160
- return selections.length > 0 ? selectionSet(selections) : null;
161
- }
162
- function toDecisionDocument(document2, schema, groupPaths, options) {
163
- const doc = documentOf(document2);
164
- const fragments = {};
165
- for (const definition of doc.definitions) {
166
- if (definition.kind === "FragmentDefinition") {
167
- fragments[definition.name.value] = definition;
168
- }
169
- }
170
- const operation = doc.definitions.find(
171
- (definition) => definition.kind === "OperationDefinition"
172
- );
173
- if (!operation) return null;
174
- let paths;
175
- if (groupPaths) {
176
- const prefixes = /* @__PURE__ */ new Set();
177
- for (const groupPath of groupPaths.keys()) {
178
- const parts = groupPath.split(".");
179
- for (let i = 1; i <= parts.length; i++) {
180
- prefixes.add(parts.slice(0, i).join("."));
181
- }
182
- }
183
- paths = { groups: groupPaths, prefixes };
184
- }
185
- const pruned = decisionSelectionSet(
186
- operation.selectionSet,
187
- schema.queryType,
188
- "",
189
- { schema, fragments, paths, topLevelOnly: options?.topLevelOnly }
190
- );
191
- if (!pruned) return null;
192
- const used = /* @__PURE__ */ new Set();
193
- collectVariables(pruned, used);
194
- collectVariables(operation.directives, used);
195
- const shared = sharedContextFragment(schema);
196
- return {
197
- kind: "Document",
198
- definitions: [
199
- ...shared ? [shared.definition] : [],
200
- {
201
- ...operation,
202
- name: operation.name && name(`${operation.name.value}Decision`),
203
- variableDefinitions: (operation.variableDefinitions ?? []).filter(
204
- (definition) => used.has(definition.variable.name.value)
205
- ),
206
- selectionSet: shared ? shared.apply(pruned) : pruned
207
- }
208
- ]
209
- };
210
- }
211
- function sharedContextFragment(schema) {
212
- const contextTypes = new Set(
213
- Object.values(schema.types).flatMap(
214
- (type) => type.hasContext ? [type.fields._context.type] : []
215
- )
216
- );
217
- if (contextTypes.size !== 1) return null;
218
- const [contextType] = contextTypes;
219
- const fragmentName = "c";
220
- const definition = {
221
- kind: "FragmentDefinition",
222
- name: name(fragmentName),
223
- typeCondition: { kind: "NamedType", name: name(contextType) },
224
- selectionSet: selectionSet(
225
- ["kind", "group_id", "variant_id"].map(
226
- (field) => ({ kind: "Field", name: name(field) })
227
- )
228
- )
229
- };
230
- const spread = {
231
- kind: "FragmentSpread",
232
- name: name(fragmentName)
233
- };
234
- const apply = (set) => selectionSet(
235
- set.selections.map((selection) => {
236
- if (selection.kind === "Field" && selection.alias?.value === PREPR_CONTEXT_ALIAS) {
237
- return { ...selection, selectionSet: selectionSet([spread]) };
238
- }
239
- return "selectionSet" in selection && selection.selectionSet ? {
240
- ...selection,
241
- selectionSet: apply(selection.selectionSet)
242
- } : selection;
243
- })
244
- );
245
- return { definition, apply };
246
- }
247
-
248
- // src/core/variants/probe-document.ts
249
- function probeSelectionSet(set, fragments) {
250
- const selections = [
251
- { kind: "Field", name: name("__typename") }
252
- ];
253
- for (const selection of set.selections) {
254
- if (selection.kind === "Field") {
255
- if (!selection.selectionSet) continue;
256
- selections.push({
257
- ...selection,
258
- selectionSet: probeSelectionSet(selection.selectionSet, fragments)
259
- });
260
- continue;
261
- }
262
- const fragment = selection.kind === "InlineFragment" ? selection : fragments[selection.name.value];
263
- if (!fragment) continue;
264
- const child = probeSelectionSet(fragment.selectionSet, fragments);
265
- if (child.selections.length === 1) continue;
266
- selections.push({
267
- kind: "InlineFragment",
268
- typeCondition: fragment.typeCondition,
269
- directives: selection.directives,
270
- selectionSet: child
271
- });
272
- }
273
- return selectionSet(selections);
274
- }
275
- function toAbProbeDocument(document2) {
276
- const doc = documentOf(document2);
277
- const fragments = {};
278
- for (const definition of doc.definitions) {
279
- if (definition.kind === "FragmentDefinition") {
280
- fragments[definition.name.value] = definition;
281
- }
282
- }
283
- const operation = doc.definitions.find(
284
- (definition) => definition.kind === "OperationDefinition"
285
- );
286
- if (!operation) return null;
287
- const probe = probeSelectionSet(operation.selectionSet, fragments);
288
- const used = /* @__PURE__ */ new Set();
289
- collectVariables(probe, used);
290
- collectVariables(operation.directives, used);
291
- return {
292
- kind: "Document",
293
- definitions: [
294
- {
295
- ...operation,
296
- name: operation.name && name(`${operation.name.value}AbCheck`),
297
- variableDefinitions: (operation.variableDefinitions ?? []).filter(
298
- (definition) => used.has(definition.variable.name.value)
299
- ),
300
- selectionSet: probe
301
- }
302
- ]
303
- };
304
- }
305
-
306
- // src/core/variants/resolve.ts
307
- function personalizationPaths(data) {
308
- const paths = /* @__PURE__ */ new Map();
309
- const walk = (value, path) => {
310
- if (Array.isArray(value)) {
311
- for (const item of value) {
312
- if (contextOf(item)?.kind === "PERSONALIZATION") {
313
- const record = item;
314
- const type = record[PREPR_TYPE_ALIAS] ?? record.__typename;
315
- const types = paths.get(path) ?? /* @__PURE__ */ new Set();
316
- types.add(typeof type === "string" ? type : "*");
317
- paths.set(path, types);
318
- }
319
- walk(item, path);
320
- }
321
- return;
322
- }
323
- if (!value || typeof value !== "object") return;
324
- for (const [key, child] of Object.entries(value)) {
325
- if (key !== PREPR_CONTEXT_ALIAS && key !== PREPR_TYPE_ALIAS)
326
- walk(child, path ? `${path}.${key}` : key);
327
- }
328
- };
329
- walk(data, "");
330
- return paths;
331
- }
332
- function contextOf(item) {
333
- if (!item || typeof item !== "object") return null;
334
- const context = item[PREPR_CONTEXT_ALIAS];
335
- const ctx = context;
336
- return ctx?.kind && ctx.group_id ? ctx : null;
337
- }
338
- function decisionsFrom(data) {
339
- const decisions = /* @__PURE__ */ new Map();
340
- const walk = (value) => {
341
- if (Array.isArray(value)) return value.forEach(walk);
342
- if (!value || typeof value !== "object") return;
343
- const ctx = contextOf(value);
344
- if (ctx?.group_id && ctx.variant_id) {
345
- const ids = decisions.get(ctx.group_id) ?? [];
346
- if (!ids.includes(ctx.variant_id)) ids.push(ctx.variant_id);
347
- decisions.set(ctx.group_id, ids);
348
- }
349
- Object.values(value).forEach(walk);
350
- };
351
- walk(data);
352
- return decisions;
353
- }
354
- function chosenVariants(ctx, options) {
355
- const decided = options.decisions?.get(ctx.group_id);
356
- if (ctx.kind === "AB_TEST") {
357
- return options.bucket ? [options.bucket] : decided ?? ["A"];
358
- }
359
- return decided ?? [PREPR_DEFAULT_VARIANT];
360
- }
361
- function resolveVariants(data, options = {}) {
362
- const resolve = (value) => {
363
- if (Array.isArray(value)) {
364
- return value.filter((item) => {
365
- const ctx = contextOf(item);
366
- return !ctx || chosenVariants(ctx, options).includes(ctx.variant_id ?? "");
367
- }).map(resolve);
368
- }
369
- if (!value || typeof value !== "object") return value;
370
- const out = {};
371
- for (const [key, child] of Object.entries(value)) out[key] = resolve(child);
372
- return out;
373
- };
374
- return resolve(data);
375
- }
376
-
377
- // src/core/variants/schema.ts
378
- var PREPR_SCHEMA_QUERY = `query PreprPersonalizationSchema {
379
- __schema {
380
- queryType { name }
381
- types {
382
- name
383
- possibleTypes { name }
384
- fields {
385
- name
386
- args { name }
387
- type { name ofType { name ofType { name ofType { name ofType { name } } } } }
388
- }
389
- }
390
- }
391
- }`;
392
- function namedType(ref) {
393
- let current = ref;
394
- while (current && !current.name) current = current.ofType;
395
- return current?.name ?? "";
396
- }
397
- function toSchemaInfo(introspection) {
398
- const types = {};
399
- for (const type of introspection.__schema.types) {
400
- if (type.name.startsWith("__")) continue;
401
- const fields = {};
402
- for (const field of type.fields ?? []) {
403
- fields[field.name] = {
404
- type: namedType(field.type),
405
- personalizable: field.args.some((arg) => arg.name === "personalize")
406
- };
407
- }
408
- types[type.name] = {
409
- fields,
410
- possibleTypes: (type.possibleTypes ?? []).map((t) => t.name),
411
- hasContext: "_context" in fields
412
- };
413
- }
414
- return { queryType: introspection.__schema.queryType.name, types };
415
- }
416
-
417
- // src/core/variants/stack.ts
418
- function containsKind(value, kind) {
419
- if (Array.isArray(value))
420
- return value.some((item) => containsKind(item, kind));
421
- if (!value || typeof value !== "object") return false;
422
- if (contextOf(value)?.kind === kind) return true;
423
- return Object.values(value).some((child) => containsKind(child, kind));
424
- }
425
- function splitStack(items) {
426
- const blocks = [];
427
- let position = 0;
428
- const positionsOf = (block) => block.key.startsWith("group:") ? 1 : block.items.length;
429
- items.forEach((item, index) => {
430
- const ctx = contextOf(item);
431
- const groupKey = ctx ? `group:${ctx.group_id}` : null;
432
- const personalized = containsKind(item, "PERSONALIZATION");
433
- const abTest = containsKind(item, "AB_TEST");
434
- const last = blocks.at(-1);
435
- const plain = !groupKey && !personalized && !abTest;
436
- if (groupKey && last?.key === groupKey) {
437
- last.personalized || (last.personalized = personalized);
438
- last.abTest || (last.abTest = abTest);
439
- last.items.push(item);
440
- } else if (plain && last && !last.personalized && !last.abTest) {
441
- last.items.push(item);
442
- } else {
443
- const last2 = blocks.at(-1);
444
- if (last2) position = last2.index + positionsOf(last2);
445
- blocks.push({
446
- key: groupKey ?? `items:${index}`,
447
- items: [item],
448
- index: position,
449
- personalized,
450
- abTest
451
- });
452
- }
453
- });
454
- return blocks;
455
- }
456
-
457
- // src/core/variants/tracking.ts
458
- function preprVariantProps(item) {
459
- const key = contextOf(item)?.variant_key;
460
- return key ? { "data-prepr-variant-key": key } : {};
461
- }
462
-
463
- // src/core/variants/variants-document.ts
464
- function variantsSelectionSet(set, typeName, schema) {
465
- const selections = set.selections.map((selection) => {
466
- if (selection.kind === "InlineFragment") {
467
- return {
468
- ...selection,
469
- selectionSet: variantsSelectionSet(
470
- selection.selectionSet,
471
- selection.typeCondition?.name.value ?? typeName,
472
- schema
473
- )
474
- };
475
- }
476
- if (selection.kind !== "Field" || !selection.selectionSet) return selection;
477
- const field = schema.types[typeName]?.fields[selection.name.value];
478
- if (!field) return selection;
479
- const child = variantsSelectionSet(
480
- selection.selectionSet,
481
- field.type,
482
- schema
483
- );
484
- if (!field.personalizable) return { ...selection, selectionSet: child };
485
- return {
486
- ...selection,
487
- arguments: [
488
- ...withoutPersonalizeArg(selection.arguments),
489
- {
490
- kind: "Argument",
491
- name: name("personalize"),
492
- value: { kind: "BooleanValue", value: false }
493
- }
494
- ],
495
- selectionSet: selectionSet([
496
- ...child.selections,
497
- ...contextSelections(field.type, schema)
498
- ])
499
- };
500
- });
501
- return { ...set, selections };
502
- }
503
- function toVariantsDocument(document2, schema) {
504
- const doc = documentOf(document2);
505
- return {
506
- ...doc,
507
- definitions: doc.definitions.map((definition) => {
508
- if (definition.kind === "OperationDefinition") {
509
- return {
510
- ...definition,
511
- selectionSet: variantsSelectionSet(
512
- definition.selectionSet,
513
- schema.queryType,
514
- schema
515
- )
516
- };
517
- }
518
- if (definition.kind === "FragmentDefinition") {
519
- return {
520
- ...definition,
521
- selectionSet: variantsSelectionSet(
522
- definition.selectionSet,
523
- definition.typeCondition.name.value,
524
- schema
525
- )
526
- };
527
- }
528
- return definition;
529
- })
530
- };
531
- }
532
-
533
- // src/core/graphql/document.ts
534
- import { print } from "graphql/language/printer.js";
535
- import { stripIgnoredCharacters } from "graphql/utilities/stripIgnoredCharacters.js";
536
- var printed = /* @__PURE__ */ new WeakMap();
537
- function isDocumentNode(value) {
538
- return typeof value === "object" && value !== null && value.kind === "Document" && Array.isArray(value.definitions);
539
- }
540
- function invalidDocument(originalError) {
541
- return new PreprError(
542
- "Expected a GraphQL query string, TypedDocumentString or DocumentNode",
543
- "INVALID_DOCUMENT",
544
- "createPreprClient",
545
- originalError
546
- );
547
- }
548
- var minified = /* @__PURE__ */ new Map();
549
- var MINIFIED_CACHE_LIMIT = 500;
550
- function minify(query) {
551
- const cached = minified.get(query);
552
- if (cached !== void 0) return cached;
553
- let result = query;
554
- try {
555
- result = stripIgnoredCharacters(query);
556
- } catch {
557
- }
558
- if (minified.size < MINIFIED_CACHE_LIMIT) minified.set(query, result);
559
- return result;
560
- }
561
- function resolveQuery(document2) {
562
- if (typeof document2 === "string") return minify(document2);
563
- if (document2 instanceof String) return minify(document2.toString());
564
- if (!isDocumentNode(document2)) throw invalidDocument();
565
- let query = printed.get(document2);
566
- if (query === void 0) {
567
- try {
568
- query = minify(print(document2));
569
- } catch (error) {
570
- throw invalidDocument(error instanceof Error ? error : void 0);
571
- }
572
- printed.set(document2, query);
573
- }
574
- return query;
575
- }
576
-
577
- // src/core/variants/queries.ts
578
- function toVariantsQuery(document2, schema) {
579
- return resolveQuery(toVariantsDocument(document2, schema));
580
- }
581
- function toDecisionQuery(document2, schema, options = {}) {
582
- const paths = options.from === void 0 ? void 0 : personalizationPaths(options.from);
583
- if (paths && paths.size === 0) return null;
584
- const decision = toDecisionDocument(document2, schema, paths, {
585
- topLevelOnly: !paths && options.topLevelOnly
586
- });
587
- return decision ? resolveQuery(decision) : null;
588
- }
589
-
590
- // src/core/graphql/transport.ts
591
- import { VERCEL_STEGA_REGEX } from "@vercel/stega";
592
-
593
- // src/core/stega/clean.ts
594
- import { vercelStegaClean, vercelStegaDecode } from "@vercel/stega";
595
-
596
- // src/core/utils.ts
597
- var DebugLogger = class {
598
- constructor(options) {
599
- this.options = {
600
- prefix: "[Prepr]",
601
- ...options
602
- };
603
- }
604
- // A local `enabled` wins; otherwise defer to the global logger so scoped
605
- // loggers created before initDebugLogger() still pick up the setting.
606
- isEnabled() {
607
- if (this.options.enabled !== void 0) {
608
- return this.options.enabled;
609
- }
610
- return globalDebugLogger?.options?.enabled ?? false;
611
- }
612
- log(message, ...args) {
613
- if (!this.isEnabled()) return;
614
- const prefix = this.options.prefix;
615
- console.log(`${prefix} ${message}`, ...args);
616
- }
617
- warn(message, ...args) {
618
- if (!this.isEnabled()) return;
619
- const prefix = this.options.prefix;
620
- console.warn(`${prefix} ${message}`, ...args);
621
- }
622
- error(message, ...args) {
623
- if (!this.isEnabled()) return;
624
- const prefix = this.options.prefix;
625
- console.error(`${prefix} ${message}`, ...args);
626
- }
627
- };
628
- var globalDebugLogger = null;
629
- function createScopedLogger(scopeName) {
630
- return new DebugLogger({
631
- prefix: `[Prepr][${scopeName}]`
632
- });
633
- }
634
-
635
- // src/core/stega/clean.ts
636
- var debug = createScopedLogger("stega:clean");
637
- function stegaClean(text) {
638
- if (!text) return text;
639
- return vercelStegaClean(text);
640
- }
641
-
642
- // src/core/graphql/transport.ts
643
- var OPERATION_NAME = /\b(?:query|mutation|subscription)\s+([_A-Za-z][_0-9A-Za-z]*)/;
644
- var STEGA_RAW = new RegExp(
645
- VERCEL_STEGA_REGEX.source,
646
- VERCEL_STEGA_REGEX.flags.replace("g", "")
647
- );
648
- var STEGA_ESCAPED = /\\u(?:200[bcd]|206[0-3]|feff|d834)/i;
649
- var URL_KEY = /(url|slug|link|href)$/i;
650
- var FASTLY_QUERY_MAX = 96 * 1024;
651
- function base64(text) {
652
- const bytes = new TextEncoder().encode(text);
653
- let binary = "";
654
- for (let i = 0; i < bytes.length; i += 32768) {
655
- binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
656
- }
657
- return btoa(binary);
658
- }
659
- function cacheInit(init, noStore) {
660
- const result = { ...init };
661
- if (noStore) {
662
- result.cache = "no-store";
663
- delete result.next;
664
- }
665
- return result;
666
- }
667
- function isFrameworkSignal(error) {
668
- return typeof error === "object" && error !== null && typeof error.digest === "string";
669
- }
670
- function mergePreprHeaders(base, extra) {
671
- const merged = new Headers(base);
672
- new Headers(extra).forEach((value, key) => {
673
- merged.set(key, value);
674
- });
675
- return merged;
676
- }
677
- function cleanEveryString(_key, value) {
678
- return typeof value === "string" ? stegaClean(value) : value;
679
- }
680
- function cleanUrlStrings(key, value) {
681
- return typeof value === "string" && URL_KEY.test(key) ? stegaClean(value) : value;
682
- }
683
- function parseBody(text, stega) {
684
- if (stega === "none" || !(STEGA_RAW.test(text) || STEGA_ESCAPED.test(text))) {
685
- return JSON.parse(text);
686
- }
687
- return JSON.parse(text, stega === "all" ? cleanEveryString : cleanUrlStrings);
688
- }
689
- function createTransport(options) {
690
- const { url, preview = false } = options;
691
- const stega = options.stega ?? (preview ? "urls" : "all");
692
- const clientHeaders = new Headers(options.headers);
693
- return async (document2, variables, queryOptions = {}) => {
694
- const query = resolveQuery(document2);
695
- const operation = OPERATION_NAME.exec(query)?.[1] ?? "anonymous";
696
- const headers = new Headers(clientHeaders);
697
- for (const layer of [queryOptions.init?.headers, queryOptions.headers]) {
698
- new Headers(layer).forEach((value, key) => {
699
- headers.set(key, value);
700
- });
701
- }
702
- headers.set("Content-Type", "application/json");
703
- const perRequestHeaders = queryOptions.headers !== void 0 || queryOptions.init?.headers !== void 0;
704
- const payload = JSON.stringify({ query, variables });
705
- const fastly = options.fastlyQuery ? base64(payload) : null;
706
- const viaGet = fastly !== null && fastly.length <= FASTLY_QUERY_MAX;
707
- if (viaGet) headers.set("Fastly-Query", fastly);
708
- const init = {
709
- ...cacheInit(queryOptions.init, preview || perRequestHeaders),
710
- method: viaGet ? "GET" : "POST",
711
- headers,
712
- body: viaGet ? void 0 : payload
713
- };
714
- const fetchImpl = queryOptions.fetch ?? options.fetch;
715
- let response;
716
- try {
717
- response = await (fetchImpl ? fetchImpl(url, init) : fetch(url, init));
718
- } catch (error) {
719
- if (isFrameworkSignal(error)) throw error;
720
- throw new PreprError(
721
- `Prepr GraphQL request failed for ${operation}`,
722
- "FETCH_ERROR",
723
- operation,
724
- error instanceof Error ? error : void 0
725
- );
726
- }
727
- if (!response.ok) {
728
- throw new PreprError(
729
- `Prepr GraphQL HTTP ${response.status} for ${operation}${response.status === 412 ? " (Prepr rejects queries longer than 27,500 characters)" : ""}`,
730
- "HTTP_ERROR",
731
- operation
732
- );
733
- }
734
- let body;
735
- try {
736
- body = parseBody(await response.text(), stega);
737
- } catch (error) {
738
- throw new PreprError(
739
- `Prepr GraphQL response for ${operation} is not valid JSON`,
740
- "INVALID_RESPONSE",
741
- operation,
742
- error instanceof Error ? error : void 0
743
- );
744
- }
745
- if (typeof body !== "object" || body === null) {
746
- throw new PreprError(
747
- `Prepr GraphQL response for ${operation} is not an object`,
748
- "INVALID_RESPONSE",
749
- operation
750
- );
751
- }
752
- const { data, errors } = body;
753
- if (Array.isArray(errors) && errors.length > 0) {
754
- const messages = errors.map((e) => String(e?.message ?? "Unknown error")).join("; ");
755
- throw new PreprError(
756
- `Prepr GraphQL errors for ${operation}: ${messages}`,
757
- "GRAPHQL_ERROR",
758
- operation
759
- );
760
- }
761
- if (data === null || data === void 0) {
762
- throw new PreprError(
763
- `Prepr GraphQL response for ${operation} has no data`,
764
- "INVALID_RESPONSE",
765
- operation
766
- );
767
- }
768
- return { data, personalized: isPersonalizedResponse(response) };
769
- };
770
- }
771
-
772
- // src/core/graphql/probe.ts
773
- var AB_TEST_VARY = /\bPrepr-ABTesting/i;
774
- var SEGMENTS_VARY = /\bPrepr-Segments/i;
775
- var AB_CHECK_TTL_MS = 6e4;
776
- var AB_CHECK_MAX_ENTRIES = 1e3;
777
- function createVaryProbe(run, options) {
778
- const abProbes = /* @__PURE__ */ new Map();
779
- const abChecks = /* @__PURE__ */ new Map();
780
- return (document2, variables) => {
781
- const key = JSON.stringify(variables ?? null);
782
- let answers = abChecks.get(document2);
783
- if (!answers) {
784
- answers = /* @__PURE__ */ new Map();
785
- abChecks.set(document2, answers);
786
- }
787
- const cached = answers.get(key);
788
- if (cached && Date.now() - cached.at < AB_CHECK_TTL_MS) return cached.value;
789
- const value = (async () => {
790
- let probe = abProbes.get(document2);
791
- if (probe === void 0) {
792
- probe = toAbProbeDocument(document2);
793
- abProbes.set(document2, probe);
794
- }
795
- if (!probe) return "";
796
- let vary = "";
797
- const send = options.fetch ?? fetch;
798
- await run(probe, variables, {
799
- fetch: async (input, init) => {
800
- const response = await send(input, init);
801
- vary = response.headers.get("vary") ?? "";
802
- return response;
803
- }
804
- });
805
- return vary;
806
- })().catch((error) => {
807
- if (isFrameworkSignal(error)) throw error;
808
- answers.delete(key);
809
- return null;
810
- });
811
- if (answers.size >= AB_CHECK_MAX_ENTRIES) {
812
- answers.delete(answers.keys().next().value);
813
- }
814
- answers.set(key, { value, at: Date.now() });
815
- return value;
816
- };
817
- }
818
-
819
- // src/core/graphql/client.ts
820
- var clientSchemas = /* @__PURE__ */ new WeakMap();
821
- function isParseableUrl(url) {
822
- try {
823
- new URL(url);
824
- return true;
825
- } catch {
826
- return false;
827
- }
828
- }
829
- function assertPreprUrl(url, source) {
830
- validatePreprToken(url);
831
- if (!isParseableUrl(url)) {
832
- throw new PreprError(
833
- "Prepr GraphQL URL is not a valid URL",
834
- "INVALID_TOKEN",
835
- source
836
- );
837
- }
838
- }
839
- function createPreprClient(options) {
840
- assertPreprUrl(options.url, "createPreprClient");
841
- const run = createTransport(options);
842
- const probeVary = createVaryProbe(run, options);
843
- let schema;
844
- const loadSchema = () => schema ?? (schema = run(
845
- PREPR_SCHEMA_QUERY,
846
- void 0,
847
- { init: options.schemaInit }
848
- ).then(
849
- (result) => toSchemaInfo(result.data),
850
- (error) => {
851
- schema = void 0;
852
- throw error;
853
- }
854
- ));
855
- const variantsDocuments = /* @__PURE__ */ new Map();
856
- const decisionDocuments = /* @__PURE__ */ new Map();
857
- const client = {
858
- async query(document2, variables, queryOptions = {}) {
859
- const { variants, ...rest } = queryOptions;
860
- if (!variants) return run(document2, variables, rest);
861
- let derived = variantsDocuments.get(document2);
862
- if (!derived) {
863
- derived = toVariantsDocument(document2, await loadSchema());
864
- variantsDocuments.set(document2, derived);
865
- }
866
- return run(derived, variables, rest);
867
- },
868
- async decide(document2, variables, queryOptions = {}) {
869
- const { from, ...rest } = queryOptions;
870
- const paths = from === void 0 ? void 0 : personalizationPaths(from);
871
- if (paths && paths.size === 0) return /* @__PURE__ */ new Map();
872
- const signature = paths ? [...paths].map(([path, types]) => `${path}:${[...types].sort().join(",")}`).sort().join("|") : "*";
873
- let byPaths = decisionDocuments.get(document2);
874
- if (!byPaths) {
875
- byPaths = /* @__PURE__ */ new Map();
876
- decisionDocuments.set(document2, byPaths);
877
- }
878
- let derived = byPaths.get(signature);
879
- if (derived === void 0) {
880
- derived = toDecisionDocument(document2, await loadSchema(), paths);
881
- byPaths.set(signature, derived);
882
- }
883
- if (!derived) return /* @__PURE__ */ new Map();
884
- const { data } = await run(derived, variables, rest);
885
- return decisionsFrom(data);
886
- },
887
- hasAbTests: (document2, variables) => probeVary(document2, variables).then(
888
- (vary) => vary === null || AB_TEST_VARY.test(vary)
889
- ),
890
- hasSegments: (document2, variables) => probeVary(document2, variables).then(
891
- (vary) => vary === null || SEGMENTS_VARY.test(vary)
892
- )
893
- };
894
- clientSchemas.set(client, loadSchema);
895
- return client;
896
- }
897
-
898
- // src/core/graphql/event-client.ts
899
- function createEventClient(options, adapter) {
900
- const client = createPreprClient(options);
901
- return {
902
- async query(document2, variables, queryOptions = {}) {
903
- const { personalize, event, ...rest } = queryOptions;
904
- if (personalize && event === void 0) {
905
- throw new PreprError(
906
- "personalize: true requires the request event",
907
- "CONTEXT_ERROR",
908
- "createPreprClient"
909
- );
910
- }
911
- const fetchImpl = rest.fetch ?? (event === void 0 ? void 0 : adapter.fetch?.(event));
912
- const headers = personalize ? mergePreprHeaders(
913
- getPreprHeadersFromHeaders(adapter.headers(event)),
914
- rest.headers
915
- ) : rest.headers;
916
- return client.query(document2, variables, {
917
- ...rest,
918
- headers,
919
- fetch: fetchImpl
920
- });
921
- },
922
- async decide(document2, variables, queryOptions) {
923
- const { event, ...rest } = queryOptions;
924
- if (event === void 0) {
925
- throw new PreprError(
926
- "decide requires the request event",
927
- "CONTEXT_ERROR",
928
- "createPreprClient"
929
- );
930
- }
931
- return client.decide(document2, variables, {
932
- ...rest,
933
- headers: mergePreprHeaders(
934
- getPreprHeadersFromHeaders(adapter.headers(event)),
935
- rest.headers
936
- ),
937
- fetch: rest.fetch ?? adapter.fetch?.(event)
938
- });
939
- }
940
- };
941
- }
942
-
943
- // src/core/graphql/schema-loader.ts
944
- var schemas = /* @__PURE__ */ new Map();
945
- async function loadPreprSchema(url, options = {}) {
946
- assertPreprUrl(url, "loadPreprSchema");
947
- let schema = schemas.get(url);
948
- if (!schema) {
949
- const run = createTransport({ url, fetch: options.fetch, stega: "none" });
950
- schema = run(
951
- PREPR_SCHEMA_QUERY
952
- ).then((result) => toSchemaInfo(result.data)).catch((error) => {
953
- schemas.delete(url);
954
- if (error instanceof PreprError) throw error;
955
- throw new PreprError(
956
- "Prepr schema response is not an introspection result",
957
- "INVALID_RESPONSE",
958
- "loadPreprSchema",
959
- error instanceof Error ? error : void 0
960
- );
961
- });
962
- schemas.set(url, schema);
963
- }
964
- return schema;
965
- }
966
-
967
- // src/nuxt/graphql.ts
968
- function createPreprClient2(options) {
969
- return createEventClient(options, {
970
- headers: getPreprHeadersFromEvent
971
- });
972
- }
973
- export {
974
- PREPR_DEFAULT_VARIANT,
975
- PreprError,
976
- createPreprClient2 as createPreprClient,
977
- decisionsFrom,
978
- isPersonalizedResponse,
979
- loadPreprSchema,
980
- preprVariantProps,
981
- resolveVariants,
982
- splitStack,
983
- toDecisionQuery,
984
- toVariantsQuery
985
- };