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