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