@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,13 +1,5 @@
1
- import {
2
- VERSION,
3
- getActiveSegmentFromHeaders,
4
- getActiveVariantFromHeaders,
5
- getPreprHeadersFromHeaders,
6
- getPreprUUIDFromHeaders,
7
- getToolbarPropsFromHeaders,
8
- isPersonalizedResponse,
9
- resolveFeatures
10
- } from "./chunk-R2YPGDVU.js";
1
+ // src/version.ts
2
+ var VERSION = "1.0.0-rc.1";
11
3
 
12
4
  // src/core/constants.ts
13
5
  var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
@@ -19,6 +11,27 @@ var PARAM_SEGMENT = "prepr_preview_segment";
19
11
  var PARAM_VARIANT = "prepr_preview_ab";
20
12
  var PARAM_HIDE_BAR = "prepr_hide_bar";
21
13
  var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
14
+ var HEADER_LIVE_RENDER = "x-prepr-live";
15
+ var ATTR_ENCODED = "data-prepr-encoded";
16
+ var ENCODED_SELECTOR = `[${ATTR_ENCODED}]`;
17
+
18
+ // src/core/features.ts
19
+ function isEnabled(config) {
20
+ if (typeof config === "boolean") return config;
21
+ return config?.enabled ?? true;
22
+ }
23
+ function resolveFeatures(features) {
24
+ return {
25
+ segments: isEnabled(features?.segments),
26
+ abTesting: isEnabled(features?.abTesting),
27
+ editMode: isEnabled(features?.editMode)
28
+ };
29
+ }
30
+ var ALL_FEATURES_ENABLED = Object.freeze({
31
+ segments: true,
32
+ abTesting: true,
33
+ editMode: true
34
+ });
22
35
 
23
36
  // src/core/middleware.ts
24
37
  var UTM_PARAMS = [
@@ -29,6 +42,16 @@ var UTM_PARAMS = [
29
42
  "utm_campaign"
30
43
  ];
31
44
  var MAX_HEADER_VALUE_LENGTH = 2048;
45
+ function randomUUID() {
46
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
47
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
48
+ bytes[6] = bytes[6] & 15 | 64;
49
+ bytes[8] = bytes[8] & 63 | 128;
50
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
51
+ ""
52
+ );
53
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
54
+ }
32
55
  function sanitizeHeaderValue(value) {
33
56
  const stripped = value.replace(/[\u0000-\u001f\u007f]/g, "");
34
57
  return stripped.length > MAX_HEADER_VALUE_LENGTH ? stripped.slice(0, MAX_HEADER_VALUE_LENGTH) : stripped;
@@ -114,7 +137,7 @@ function processFrameworkRequest(request, opts, framework) {
114
137
  }
115
138
  let uid = sanitizeHeaderValue(requestCookies.get(COOKIE_UID) ?? "");
116
139
  if (!uid) {
117
- uid = crypto.randomUUID();
140
+ uid = randomUUID();
118
141
  responseCookies.push({
119
142
  name: COOKIE_UID,
120
143
  value: uid,
@@ -183,29 +206,1496 @@ function processFrameworkRequest(request, opts, framework) {
183
206
  });
184
207
  }
185
208
  }
186
- if (requestHeaders.has("Prepr-Segments")) {
187
- requestHeaders.delete("Prepr-Customer-Id");
188
- requestHeaders.delete("Prepr-Customer-Id-Created");
189
- }
190
209
  return { requestHeaders, responseCookies };
191
210
  }
192
211
 
193
- // src/astro/index.ts
194
- async function onPreprRequest(context, next, options) {
195
- const { requestHeaders, responseCookies } = processFrameworkRequest(
196
- context.request,
197
- options,
198
- "astro"
212
+ // src/core/live-preview/guards.ts
213
+ function isScalar(value) {
214
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
215
+ }
216
+ function isObject(value) {
217
+ return value !== null && typeof value === "object" && !Array.isArray(value);
218
+ }
219
+
220
+ // src/core/live-preview/entry-edit-links.ts
221
+ import {
222
+ vercelStegaCombine,
223
+ vercelStegaDecode,
224
+ vercelStegaSplit
225
+ } from "@vercel/stega";
226
+
227
+ // src/core/live-preview/validate.ts
228
+ var MAX_DEPTH = 3;
229
+ var MAX_ENTRIES = 50;
230
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
231
+ var SAFE_URL = /^https?:\/\//i;
232
+ var URL_KEY = /^(?:url|href|src|link)$|(?:_url|Url)$/;
233
+ var URL_IGNORED_ANYWHERE = /[\t\n\r]/g;
234
+ var SCRIPT_SCHEME = /^(?:javascript|vbscript|data):/i;
235
+ function isSafeLinkValue(value) {
236
+ const stripped = value.replace(URL_IGNORED_ANYWHERE, "");
237
+ let start = 0;
238
+ while (start < stripped.length && stripped.charCodeAt(start) <= 32) start++;
239
+ return !SCRIPT_SCHEME.test(stripped.slice(start));
240
+ }
241
+ function isUrlKey(key) {
242
+ return URL_KEY.test(key);
243
+ }
244
+ function isSafeKeyValue(key, value) {
245
+ if (typeof value !== "string") return true;
246
+ if (key === "url") return SAFE_URL.test(value);
247
+ return !isUrlKey(key) || isSafeLinkValue(value);
248
+ }
249
+ function isLiveValue(v, depth = 0) {
250
+ if (v === null || isScalar(v)) return true;
251
+ if (depth >= MAX_DEPTH) return false;
252
+ if (Array.isArray(v)) {
253
+ return depth === 0 && v.length <= MAX_ENTRIES && v.every((entry) => isPlainRecord(entry) && isLiveValue(entry, depth + 1));
254
+ }
255
+ if (!isPlainRecord(v)) return false;
256
+ const keys = Object.keys(v);
257
+ if (keys.length > MAX_ENTRIES) return false;
258
+ return keys.every((key) => {
259
+ if (FORBIDDEN_KEYS.has(key)) return false;
260
+ const value = v[key];
261
+ if (!isSafeKeyValue(key, value)) return false;
262
+ return !Array.isArray(value) && isLiveValue(value, depth + 1);
263
+ });
264
+ }
265
+ function isLiveFieldChange(field, value) {
266
+ if (!isLiveValue(value)) return false;
267
+ const name = field.slice(field.lastIndexOf(".") + 1);
268
+ return typeof value !== "string" || !isUrlKey(name) || isSafeLinkValue(value);
269
+ }
270
+ var MAX_LIST_ENTRIES = 200;
271
+ function parseListEntries(value) {
272
+ if (!Array.isArray(value) || value.length > MAX_LIST_ENTRIES) return null;
273
+ const list = [];
274
+ for (const raw of value) {
275
+ if (!isPlainRecord(raw) || typeof raw._id !== "string" || !raw._id) {
276
+ return null;
277
+ }
278
+ const entry = { _id: raw._id };
279
+ if (typeof raw.__typename === "string") entry.__typename = raw.__typename;
280
+ if (typeof raw.body === "string") entry.body = raw.body;
281
+ if (typeof raw.format === "string" || raw.format === null) {
282
+ entry.format = raw.format;
283
+ }
284
+ if (typeof raw.typeName === "string" && raw.typeName.length <= 200) {
285
+ entry.typeName = raw.typeName;
286
+ }
287
+ if (raw.fields !== void 0) {
288
+ if (!isPlainRecord(raw.fields) || !isFieldValue(raw.fields, 0)) {
289
+ return null;
290
+ }
291
+ entry.fields = raw.fields;
292
+ }
293
+ list.push(entry);
294
+ }
295
+ return list;
296
+ }
297
+ function isPlainRecord(v) {
298
+ return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
299
+ }
300
+ var MAX_FIELD_DEPTH = 6;
301
+ var MAX_FIELD_KEYS = 100;
302
+ function isFieldValue(v, depth) {
303
+ if (v === null || isScalar(v)) return true;
304
+ if (depth >= MAX_FIELD_DEPTH) return false;
305
+ if (Array.isArray(v)) {
306
+ return v.length <= MAX_ENTRIES && v.every(
307
+ (entry) => isScalar(entry) || isPlainRecord(entry) && isFieldValue(entry, depth + 1)
308
+ );
309
+ }
310
+ if (!isPlainRecord(v)) return false;
311
+ const keys = Object.keys(v);
312
+ if (keys.length > MAX_FIELD_KEYS) return false;
313
+ return keys.every((key) => {
314
+ if (FORBIDDEN_KEYS.has(key)) return false;
315
+ const value = v[key];
316
+ if (!isSafeKeyValue(key, value)) return false;
317
+ return isFieldValue(value, depth + 1);
318
+ });
319
+ }
320
+ var MAX_EDIT_LENGTH = 1e3;
321
+ function parseEditTarget(raw) {
322
+ if (!isPlainRecord(raw)) return void 0;
323
+ const { item, field } = raw;
324
+ if (typeof item !== "string" || !item || item.length > MAX_EDIT_LENGTH) {
325
+ return void 0;
326
+ }
327
+ if (typeof field !== "string" || !field || field.length > MAX_EDIT_LENGTH) {
328
+ return void 0;
329
+ }
330
+ return { item, field };
331
+ }
332
+
333
+ // src/core/live-preview/entry-edit-links.ts
334
+ var EDIT_PATH = /\/content\/edit\/[^/?#]+/;
335
+ function editLinks(result, entry) {
336
+ const edit = entry.fields?.__edit;
337
+ if (!isPlainRecord(edit) || typeof edit.item !== "string") return null;
338
+ return editLinksFor(result, edit.item);
339
+ }
340
+ var ITEM_ID = /^[A-Za-z0-9_-]+$/;
341
+ function editLinksFor(result, item) {
342
+ if (!ITEM_ID.test(item)) return null;
343
+ const template = findEditLink(result);
344
+ if (!template) return null;
345
+ return {
346
+ encode(text, field) {
347
+ if (vercelStegaSplit(text).encoded) return text;
348
+ let href;
349
+ try {
350
+ href = new URL(template.href);
351
+ } catch {
352
+ return text;
353
+ }
354
+ href.pathname = href.pathname.replace(
355
+ EDIT_PATH,
356
+ () => `/content/edit/${item}`
357
+ );
358
+ href.searchParams.set("field", field);
359
+ const link = href.toString().replace(/%2E/gi, ".").replace(/%2F/gi, "/");
360
+ return vercelStegaCombine(text, { origin: template.origin, href: link });
361
+ }
362
+ };
363
+ }
364
+ var linkCache = /* @__PURE__ */ new WeakMap();
365
+ function findEditLink(root) {
366
+ if (root === null || typeof root !== "object") return null;
367
+ if (linkCache.has(root)) return linkCache.get(root) ?? null;
368
+ let found = null;
369
+ const seen = /* @__PURE__ */ new WeakSet();
370
+ const walk2 = (node) => {
371
+ if (found) return;
372
+ if (typeof node === "string") {
373
+ if (!vercelStegaSplit(node).encoded) return;
374
+ try {
375
+ const decoded = vercelStegaDecode(node);
376
+ if (typeof decoded?.origin === "string" && typeof decoded.href === "string" && EDIT_PATH.test(decoded.href)) {
377
+ found = { origin: decoded.origin, href: decoded.href };
378
+ }
379
+ } catch {
380
+ }
381
+ return;
382
+ }
383
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
384
+ seen.add(node);
385
+ for (const value of Object.values(node)) walk2(value);
386
+ };
387
+ walk2(root);
388
+ linkCache.set(root, found);
389
+ return found;
390
+ }
391
+
392
+ // src/core/live-preview/patch-log.ts
393
+ var MAX_LOG_ENTRIES = 500;
394
+ var MAX_LOG_SOURCE_LENGTH = 1e6;
395
+ function parsePatchLog(raw) {
396
+ let value = raw;
397
+ if (typeof value === "string") {
398
+ if (!value || value.length > MAX_LOG_SOURCE_LENGTH) return [];
399
+ try {
400
+ value = JSON.parse(value);
401
+ } catch {
402
+ return [];
403
+ }
404
+ }
405
+ if (!Array.isArray(value)) return [];
406
+ const log = [];
407
+ for (const entry of value.slice(-MAX_LOG_ENTRIES)) {
408
+ if (!isPlainRecord(entry)) continue;
409
+ const { type, itemId, field } = entry;
410
+ if (typeof itemId !== "string" || !itemId) continue;
411
+ if (typeof field !== "string" || !field) continue;
412
+ if (type === "field" && isLiveFieldChange(field, entry.value)) {
413
+ const edit = parseEditTarget(entry.edit);
414
+ log.push(
415
+ edit ? { type, itemId, field, value: entry.value, edit } : { type, itemId, field, value: entry.value }
416
+ );
417
+ } else if (type === "list") {
418
+ const entries = parseListEntries(entry.entries);
419
+ if (entries) log.push({ type, itemId, field, entries });
420
+ }
421
+ }
422
+ return log;
423
+ }
424
+
425
+ // src/core/live-preview/normalize-query.ts
426
+ import { vercelStegaSplit as vercelStegaSplit3 } from "@vercel/stega";
427
+
428
+ // src/core/shared-state.ts
429
+ var KEY = /* @__PURE__ */ Symbol.for("@preprio/toolkit:shared-state");
430
+ function initialState() {
431
+ return {
432
+ trustedParentOrigin: null,
433
+ debugEnabled: void 0,
434
+ strictMode: false,
435
+ liveAnnouncedStrict: void 0
436
+ };
437
+ }
438
+ function sharedState() {
439
+ const scope = globalThis;
440
+ return scope[KEY] ?? (scope[KEY] = initialState());
441
+ }
442
+
443
+ // src/core/utils.ts
444
+ var DebugLogger = class {
445
+ constructor(options) {
446
+ this.options = {
447
+ prefix: "[Prepr]",
448
+ ...options
449
+ };
450
+ }
451
+ // A local `enabled` wins; otherwise defer to the shared flag so scoped
452
+ // loggers created before initDebugLogger() still pick up the setting.
453
+ isEnabled() {
454
+ if (this.options.enabled !== void 0) {
455
+ return this.options.enabled;
456
+ }
457
+ return sharedState().debugEnabled ?? false;
458
+ }
459
+ log(message, ...args) {
460
+ if (!this.isEnabled()) return;
461
+ const prefix = this.options.prefix;
462
+ console.log(`${prefix} ${message}`, ...args);
463
+ }
464
+ warn(message, ...args) {
465
+ if (!this.isEnabled()) return;
466
+ const prefix = this.options.prefix;
467
+ console.warn(`${prefix} ${message}`, ...args);
468
+ }
469
+ };
470
+ function createScopedLogger(scopeName) {
471
+ return new DebugLogger({
472
+ prefix: `[Prepr][${scopeName}]`
473
+ });
474
+ }
475
+
476
+ // src/core/live-preview/field-name.ts
477
+ var UPPERCASE_BOUNDARY = /(.)(?=[A-Z])/g;
478
+ function graphqlFieldName(apiId) {
479
+ return apiId.replace(UPPERCASE_BOUNDARY, "$1_").toLowerCase();
480
+ }
481
+ var TEXT_BODY_FIELDS = [
482
+ { name: "body", plain: false },
483
+ { name: "html", plain: false },
484
+ { name: "text", plain: true }
485
+ ];
486
+ var TAG_PATTERN = /<[^>]+>/g;
487
+ function plainTextFromHtml(html) {
488
+ return html.replace(TAG_PATTERN, "");
489
+ }
490
+ function isTextEntry(record) {
491
+ const typename = record.__typename;
492
+ if (typeof typename === "string") return typename === "Text";
493
+ return "html" in record || "text" in record && "format" in record;
494
+ }
495
+
496
+ // src/core/live-preview/index-snapshot.ts
497
+ var debug = createScopedLogger("live-preview");
498
+ function indexSnapshot(data) {
499
+ const index = /* @__PURE__ */ new Map();
500
+ const visited = /* @__PURE__ */ new WeakSet();
501
+ const path = [];
502
+ function walk2(node) {
503
+ if (node === null || typeof node !== "object") return;
504
+ if (visited.has(node)) return;
505
+ visited.add(node);
506
+ if (Array.isArray(node)) {
507
+ for (let i = 0; i < node.length; i++) {
508
+ path.push(i);
509
+ walk2(node[i]);
510
+ path.pop();
511
+ }
512
+ return;
513
+ }
514
+ const record = node;
515
+ if (typeof record._id === "string") {
516
+ const paths = index.get(record._id);
517
+ if (paths) paths.push([...path]);
518
+ else index.set(record._id, [[...path]]);
519
+ } else if (typeof record.__typename === "string") {
520
+ debug.log("item without _id will not live-update", {
521
+ __typename: record.__typename
522
+ });
523
+ }
524
+ for (const key in record) {
525
+ if (!Object.prototype.hasOwnProperty.call(record, key)) continue;
526
+ path.push(key);
527
+ walk2(record[key]);
528
+ path.pop();
529
+ }
530
+ }
531
+ walk2(data);
532
+ return index;
533
+ }
534
+
535
+ // src/core/live-preview/patch.ts
536
+ import { vercelStegaSplit as vercelStegaSplit2 } from "@vercel/stega";
537
+ var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
538
+ function mergeObject(current, incoming) {
539
+ let changed = false;
540
+ const next = { ...current };
541
+ for (const key of Object.keys(current)) {
542
+ if (!(key in incoming) || incoming[key] === void 0) continue;
543
+ const value = isObject(current[key]) && isObject(incoming[key]) ? mergeObject(current[key], incoming[key]) : incoming[key];
544
+ if (value !== current[key]) {
545
+ next[key] = value;
546
+ changed = true;
547
+ }
548
+ }
549
+ return changed ? next : current;
550
+ }
551
+ function shapeLike(template, incoming) {
552
+ const out = {};
553
+ for (const key of Object.keys(template)) {
554
+ const value = incoming[key];
555
+ out[key] = value === void 0 ? null : isObject(template[key]) && isObject(value) ? shapeLike(template[key], value) : value;
556
+ }
557
+ return out;
558
+ }
559
+ function isAsset(value) {
560
+ return isObject(value) && (typeof value.url === "string" || value.__typename === "Asset");
561
+ }
562
+ function hasId(list, entry) {
563
+ return entry._id !== void 0 && list.some((c) => isObject(c) && c._id === entry._id);
564
+ }
565
+ function isAssetValue(value) {
566
+ return Array.isArray(value) ? value.length > 0 && value.every(isAsset) : isAsset(value);
567
+ }
568
+ function keepRemovedAssets(current, next) {
569
+ const listed = /* @__PURE__ */ new Set();
570
+ for (const entry of next) {
571
+ if (isObject(entry) && entry._id !== void 0) listed.add(entry._id);
572
+ }
573
+ let out = next;
574
+ current.forEach((entry, position) => {
575
+ if (!isObject(entry) || entry._id === void 0) return;
576
+ if (listed.has(entry._id)) return;
577
+ if (out === next) out = [...next];
578
+ out.splice(Math.min(position, out.length), 0, entry);
579
+ });
580
+ return out;
581
+ }
582
+ function mergeStructured(current, incoming) {
583
+ if (incoming === null || Array.isArray(incoming) && !incoming.length) {
584
+ if (isAssetValue(current)) return current;
585
+ if (Array.isArray(current)) return current.length ? [] : current;
586
+ return null;
587
+ }
588
+ const list = Array.isArray(incoming) ? incoming : [incoming];
589
+ if (current === null || current === void 0) return incoming;
590
+ if (Array.isArray(current)) {
591
+ const template = current.find(isObject);
592
+ const next = list.map((entry) => {
593
+ const match = current.find(
594
+ (c) => isObject(c) && c._id !== void 0 && c._id === entry._id
595
+ );
596
+ if (isObject(match)) return mergeObject(match, entry);
597
+ return isObject(template) ? shapeLike(template, entry) : entry;
598
+ });
599
+ if (!isAssetValue(current) || list.some((entry) => !hasId(current, entry))) {
600
+ return next;
601
+ }
602
+ const kept = keepRemovedAssets(current, next);
603
+ return kept.length === current.length && kept.every((entry, i) => entry === current[i]) ? current : kept;
604
+ }
605
+ if (isObject(current)) return mergeObject(current, list[0]);
606
+ return current;
607
+ }
608
+ function isPatchable(current) {
609
+ return current === null || typeof current === "string" || typeof current === "number" || typeof current === "boolean";
610
+ }
611
+ function cloneNode(node) {
612
+ return Array.isArray(node) ? [...node] : { ...node };
613
+ }
614
+ function writeAtPath(root, fullPath, value, markChanged = () => {
615
+ }) {
616
+ if (!fullPath.length) return root;
617
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
618
+ const last = fullPath.length - 1;
619
+ let node = root;
620
+ for (let i = 0; i < last; i++) {
621
+ if (node === null || typeof node !== "object") return root;
622
+ node = node[fullPath[i]];
623
+ }
624
+ if (node === null || typeof node !== "object") return root;
625
+ const container = node;
626
+ const key = fullPath[last];
627
+ if (!(key in container)) return root;
628
+ let next;
629
+ if (value === null || typeof value === "object") {
630
+ next = mergeStructured(container[key], value);
631
+ } else if (!isPatchable(container[key])) {
632
+ return root;
633
+ } else {
634
+ next = keepEditLink(container[key], value);
635
+ }
636
+ if (container[key] === next) return root;
637
+ const newRoot = cloneNode(root);
638
+ let cursor = newRoot;
639
+ for (let i = 0; i < last; i++) {
640
+ const child = cloneNode(cursor[fullPath[i]]);
641
+ cursor[fullPath[i]] = child;
642
+ cursor = child;
643
+ }
644
+ cursor[key] = next;
645
+ markChanged();
646
+ return newRoot;
647
+ }
648
+ function listKeysOf(entry) {
649
+ if (!isObject(entry)) return [];
650
+ const keys = [];
651
+ if (typeof entry._id === "string") keys.push(entry._id);
652
+ const first = Array.isArray(entry.items) ? entry.items[0] : null;
653
+ if (isObject(first) && typeof first._id === "string") {
654
+ keys.push(first._id);
655
+ }
656
+ return keys;
657
+ }
658
+ function buildText(entry, template) {
659
+ const body = typeof entry.body === "string" ? entry.body : "";
660
+ const full = {
661
+ __typename: "Text",
662
+ _id: entry._id,
663
+ body,
664
+ html: body,
665
+ text: plainTextFromHtml(body),
666
+ format: entry.format ?? null
667
+ };
668
+ if (!template) return full;
669
+ const out = {};
670
+ for (const key of Object.keys(template)) {
671
+ out[key] = key in full ? full[key] : null;
672
+ }
673
+ return out;
674
+ }
675
+ function syncList(current, entries, build) {
676
+ if (current === null || current === void 0) {
677
+ const built = syncList([], entries, build);
678
+ return built.length ? built : current;
679
+ }
680
+ if (!Array.isArray(current)) return current;
681
+ const byKey = /* @__PURE__ */ new Map();
682
+ const templates = /* @__PURE__ */ new Map();
683
+ for (const c of current) {
684
+ for (const key of listKeysOf(c)) byKey.set(key, c);
685
+ if (isObject(c) && typeof c.__typename === "string") {
686
+ if (!templates.has(c.__typename)) templates.set(c.__typename, c);
687
+ }
688
+ }
689
+ if (!entries.length) return current.length ? [] : current;
690
+ if (current.length && !byKey.size) return current;
691
+ if (current.length && !entries.some((e) => byKey.has(e._id))) return current;
692
+ const next = [];
693
+ for (const entry of entries) {
694
+ const existing = byKey.get(entry._id);
695
+ const built = existing === void 0 && entry.fields ? build?.(entry) : void 0;
696
+ if (existing !== void 0) {
697
+ next.push(existing);
698
+ } else if (built) {
699
+ next.push(built);
700
+ } else if (entry.__typename === "Text") {
701
+ next.push(buildText(entry, templates.get("Text")));
702
+ }
703
+ }
704
+ const same = next.length === current.length && next.every((n, i) => n === current[i]);
705
+ return same ? current : next;
706
+ }
707
+ function syncListAtPath(root, fullPath, entries, build) {
708
+ if (!fullPath.length) return root;
709
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
710
+ let node = root;
711
+ for (const key of fullPath) {
712
+ node = node !== null && typeof node === "object" ? node[key] : void 0;
713
+ }
714
+ const next = syncList(node, entries, build);
715
+ if (next === node) return root;
716
+ const newRoot = cloneNode(root);
717
+ let cursor = newRoot;
718
+ for (let i = 0; i < fullPath.length - 1; i++) {
719
+ const child = cloneNode(cursor[fullPath[i]]);
720
+ cursor[fullPath[i]] = child;
721
+ cursor = child;
722
+ }
723
+ cursor[fullPath[fullPath.length - 1]] = next;
724
+ return newRoot;
725
+ }
726
+ function keepEditLink(current, value) {
727
+ if (typeof current !== "string" || typeof value !== "string") return value;
728
+ const { encoded } = vercelStegaSplit2(current);
729
+ if (!encoded || vercelStegaSplit2(value).encoded) return value;
730
+ return value + encoded;
731
+ }
732
+
733
+ // src/core/live-preview/query-document.ts
734
+ var NAME_START = /[_A-Za-z]/;
735
+ var NAME_CONTINUE = /[_0-9A-Za-z]/;
736
+ var PUNCT = /* @__PURE__ */ new Set([
737
+ "!",
738
+ "$",
739
+ "&",
740
+ "(",
741
+ ")",
742
+ ":",
743
+ "=",
744
+ "@",
745
+ "[",
746
+ "]",
747
+ "{",
748
+ "|",
749
+ "}"
750
+ ]);
751
+ function tokenize(source) {
752
+ const tokens = [];
753
+ let i = 0;
754
+ const n = source.length;
755
+ while (i < n) {
756
+ const ch = source[i];
757
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "," || ch === "\uFEFF") {
758
+ i++;
759
+ } else if (ch === "#") {
760
+ while (i < n && source[i] !== "\n" && source[i] !== "\r") i++;
761
+ } else if (ch === "." && source.startsWith("...", i)) {
762
+ tokens.push({ type: "punct", value: "..." });
763
+ i += 3;
764
+ } else if (PUNCT.has(ch)) {
765
+ tokens.push({ type: "punct", value: ch });
766
+ i++;
767
+ } else if (NAME_START.test(ch)) {
768
+ const start = i;
769
+ while (i < n && NAME_CONTINUE.test(source[i])) i++;
770
+ tokens.push({ type: "name", value: source.slice(start, i) });
771
+ } else if (ch === '"') {
772
+ if (source.startsWith('"""', i)) {
773
+ i += 3;
774
+ while (i < n && !source.startsWith('"""', i)) {
775
+ i += source.startsWith('\\"""', i) ? 4 : 1;
776
+ }
777
+ if (i >= n) throw new SyntaxError("Unterminated block string");
778
+ i += 3;
779
+ } else {
780
+ i++;
781
+ while (i < n && source[i] !== '"') {
782
+ if (source[i] === "\n" || source[i] === "\r") {
783
+ throw new SyntaxError("Unterminated string");
784
+ }
785
+ i += source[i] === "\\" ? 2 : 1;
786
+ }
787
+ if (i >= n) throw new SyntaxError("Unterminated string");
788
+ i++;
789
+ }
790
+ tokens.push({ type: "value" });
791
+ } else if (ch === "-" || ch >= "0" && ch <= "9") {
792
+ i++;
793
+ while (i < n && /[0-9.eE+-]/.test(source[i])) i++;
794
+ tokens.push({ type: "value" });
795
+ } else {
796
+ throw new SyntaxError(`Unexpected character "${ch}"`);
797
+ }
798
+ }
799
+ return tokens;
800
+ }
801
+ function parseSource(source, operationName) {
802
+ const tokens = tokenize(source);
803
+ let pos = 0;
804
+ const peek = () => tokens[pos];
805
+ const isPunct = (value) => {
806
+ const t = tokens[pos];
807
+ return t?.type === "punct" && t.value === value;
808
+ };
809
+ const expectPunct = (value) => {
810
+ if (!isPunct(value)) throw new SyntaxError(`Expected "${value}"`);
811
+ pos++;
812
+ };
813
+ const expectName = () => {
814
+ const t = tokens[pos];
815
+ if (t?.type !== "name") throw new SyntaxError("Expected a name");
816
+ pos++;
817
+ return t.value;
818
+ };
819
+ const skipParens = () => {
820
+ expectPunct("(");
821
+ let depth = 1;
822
+ while (depth > 0) {
823
+ const t = tokens[pos++];
824
+ if (!t) throw new SyntaxError("Unbalanced parentheses");
825
+ if (t.type === "punct" && t.value === "(") depth++;
826
+ else if (t.type === "punct" && t.value === ")") depth--;
827
+ }
828
+ };
829
+ const skipDirectives = () => {
830
+ while (isPunct("@")) {
831
+ pos++;
832
+ expectName();
833
+ if (isPunct("(")) skipParens();
834
+ }
835
+ };
836
+ const parseSelectionSet = () => {
837
+ expectPunct("{");
838
+ const selections = [];
839
+ while (!isPunct("}")) {
840
+ if (!peek()) throw new SyntaxError("Unterminated selection set");
841
+ selections.push(parseSelection());
842
+ }
843
+ pos++;
844
+ return selections;
845
+ };
846
+ const parseSelection = () => {
847
+ if (isPunct("...")) {
848
+ pos++;
849
+ const t = peek();
850
+ if (t?.type === "name" && t.value !== "on") {
851
+ pos++;
852
+ skipDirectives();
853
+ return { kind: "spread", name: t.value };
854
+ }
855
+ let on = null;
856
+ if (t?.type === "name") {
857
+ pos++;
858
+ on = expectName();
859
+ }
860
+ skipDirectives();
861
+ return { kind: "inline", on, selections: parseSelectionSet() };
862
+ }
863
+ let name = expectName();
864
+ const key = name;
865
+ if (isPunct(":")) {
866
+ pos++;
867
+ name = expectName();
868
+ }
869
+ let hasArgs = false;
870
+ if (isPunct("(")) {
871
+ hasArgs = true;
872
+ skipParens();
873
+ }
874
+ skipDirectives();
875
+ const selections = isPunct("{") ? parseSelectionSet() : null;
876
+ return { kind: "field", name, key, hasArgs, selections };
877
+ };
878
+ const fragments = /* @__PURE__ */ new Map();
879
+ const operations = [];
880
+ while (pos < tokens.length) {
881
+ if (isPunct("{")) {
882
+ operations.push({ name: null, selections: parseSelectionSet() });
883
+ continue;
884
+ }
885
+ const keyword = expectName();
886
+ if (keyword === "fragment") {
887
+ const name = expectName();
888
+ if (expectName() !== "on") throw new SyntaxError('Expected "on"');
889
+ const on = expectName();
890
+ skipDirectives();
891
+ fragments.set(name, { on, selections: parseSelectionSet() });
892
+ } else if (keyword === "query" || keyword === "mutation" || keyword === "subscription") {
893
+ const t = peek();
894
+ let name = null;
895
+ if (t?.type === "name") name = expectName();
896
+ if (isPunct("(")) skipParens();
897
+ skipDirectives();
898
+ operations.push({ name, selections: parseSelectionSet() });
899
+ } else {
900
+ throw new SyntaxError(`Unexpected "${keyword}"`);
901
+ }
902
+ }
903
+ return { operation: pickOperation(operations, operationName), fragments };
904
+ }
905
+ function pickOperation(operations, operationName) {
906
+ const op = operationName ? operations.find((o) => o.name === operationName) : operations[0];
907
+ if (!op) throw new SyntaxError("The document has no operation");
908
+ return op.selections;
909
+ }
910
+ function fromAstSelections(set) {
911
+ return set.selections.map((s) => {
912
+ if (s.kind === "FragmentSpread")
913
+ return { kind: "spread", name: s.name.value };
914
+ if (s.kind === "InlineFragment") {
915
+ return {
916
+ kind: "inline",
917
+ on: s.typeCondition?.name.value ?? null,
918
+ selections: fromAstSelections(s.selectionSet)
919
+ };
920
+ }
921
+ const name = s.name.value;
922
+ return {
923
+ kind: "field",
924
+ name,
925
+ key: s.alias?.value ?? name,
926
+ hasArgs: Boolean(s.arguments?.length),
927
+ selections: s.selectionSet ? fromAstSelections(s.selectionSet) : null
928
+ };
929
+ });
930
+ }
931
+ function fromAst(doc, operationName) {
932
+ const fragments = /* @__PURE__ */ new Map();
933
+ const operations = [];
934
+ for (const def of doc.definitions ?? []) {
935
+ if (def.kind === "FragmentDefinition" && def.name && def.typeCondition && def.selectionSet) {
936
+ fragments.set(def.name.value, {
937
+ on: def.typeCondition.name.value,
938
+ selections: fromAstSelections(def.selectionSet)
939
+ });
940
+ } else if (def.kind === "OperationDefinition" && def.selectionSet) {
941
+ operations.push({
942
+ name: def.name?.value ?? null,
943
+ selections: fromAstSelections(def.selectionSet)
944
+ });
945
+ }
946
+ }
947
+ return { operation: pickOperation(operations, operationName), fragments };
948
+ }
949
+ var astCache = /* @__PURE__ */ new WeakMap();
950
+ var sourceCache = /* @__PURE__ */ new Map();
951
+ var SOURCE_CACHE_LIMIT = 200;
952
+ function readQueryDocument(query, operationName) {
953
+ const cacheKey = operationName ?? "";
954
+ if (typeof query === "object" && query !== null && query.kind === "Document") {
955
+ let byName = astCache.get(query);
956
+ if (!byName) astCache.set(query, byName = /* @__PURE__ */ new Map());
957
+ let parsed2 = byName.get(cacheKey);
958
+ if (!parsed2) {
959
+ parsed2 = fromAst(
960
+ query,
961
+ operationName
962
+ );
963
+ byName.set(cacheKey, parsed2);
964
+ }
965
+ return parsed2;
966
+ }
967
+ const source = String(query);
968
+ const sourceKey = `${cacheKey}
969
+ ${source}`;
970
+ let parsed = sourceCache.get(sourceKey);
971
+ if (!parsed) {
972
+ parsed = parseSource(source, operationName);
973
+ if (sourceCache.size >= SOURCE_CACHE_LIMIT) {
974
+ sourceCache.delete(sourceCache.keys().next().value);
975
+ }
976
+ sourceCache.set(sourceKey, parsed);
977
+ }
978
+ return parsed;
979
+ }
980
+ var fieldsCache = /* @__PURE__ */ new WeakMap();
981
+ function collectFields(selections, typename, doc, options = {}) {
982
+ const cacheKey = `${options.strict ? "s" : "l"}:${typename ?? ""}`;
983
+ let cached = fieldsCache.get(selections);
984
+ if (!cached) {
985
+ cached = /* @__PURE__ */ new Map();
986
+ fieldsCache.set(selections, cached);
987
+ }
988
+ const hit = cached.get(cacheKey);
989
+ if (hit) return hit;
990
+ const fields = resolveFields(selections, typename, doc, options);
991
+ cached.set(cacheKey, fields);
992
+ return fields;
993
+ }
994
+ function resolveFields(selections, typename, doc, options) {
995
+ const exact = /* @__PURE__ */ new Map();
996
+ const loose = /* @__PURE__ */ new Map();
997
+ const merged = /* @__PURE__ */ new Map();
998
+ const walkedMatched = /* @__PURE__ */ new Set();
999
+ const walkedLoose = /* @__PURE__ */ new Set();
1000
+ const add = (target, s) => {
1001
+ let field = target.get(s.key);
1002
+ if (!field) {
1003
+ field = { name: s.name, key: s.key, hasArgs: s.hasArgs, selections: [] };
1004
+ target.set(s.key, field);
1005
+ merged.set(field, /* @__PURE__ */ new Set());
1006
+ }
1007
+ const done = merged.get(field);
1008
+ if (s.selections && !done.has(s.selections)) {
1009
+ done.add(s.selections);
1010
+ field.selections = [...field.selections, ...s.selections];
1011
+ }
1012
+ };
1013
+ const applies = (on, list) => conditionMatches(on, typename) || typename !== void 0 && typeConditions(list, doc).includes(typename);
1014
+ const walk2 = (list, matched) => {
1015
+ for (const s of list) {
1016
+ if (s.kind === "field") {
1017
+ add(matched ? exact : loose, s);
1018
+ } else if (s.kind === "inline") {
1019
+ walk2(s.selections, matched && applies(s.on, s.selections));
1020
+ } else {
1021
+ const fragment = doc.fragments.get(s.name);
1022
+ if (!fragment) continue;
1023
+ const asMatched = matched && applies(fragment.on, fragment.selections);
1024
+ if (walkedMatched.has(fragment)) continue;
1025
+ if (!asMatched && walkedLoose.has(fragment)) continue;
1026
+ (asMatched ? walkedMatched : walkedLoose).add(fragment);
1027
+ walk2(fragment.selections, asMatched);
1028
+ }
1029
+ }
1030
+ };
1031
+ walk2(selections, true);
1032
+ if (!options.strict) {
1033
+ for (const [key, field] of loose) {
1034
+ if (!exact.has(key)) exact.set(key, field);
1035
+ }
1036
+ }
1037
+ return exact;
1038
+ }
1039
+ function conditionMatches(on, typename) {
1040
+ return on === null || typename === void 0 || on === typename;
1041
+ }
1042
+ var conditionsCache = /* @__PURE__ */ new WeakMap();
1043
+ function typeConditions(selections, doc) {
1044
+ const hit = conditionsCache.get(selections);
1045
+ if (hit) return hit;
1046
+ const names = /* @__PURE__ */ new Set();
1047
+ const seen = /* @__PURE__ */ new Set();
1048
+ const walk2 = (list) => {
1049
+ for (const s of list) {
1050
+ if (s.kind === "inline") {
1051
+ if (s.on) names.add(s.on);
1052
+ walk2(s.selections);
1053
+ } else if (s.kind === "spread") {
1054
+ const fragment = doc.fragments.get(s.name);
1055
+ if (!fragment || seen.has(fragment)) continue;
1056
+ seen.add(fragment);
1057
+ names.add(fragment.on);
1058
+ walk2(fragment.selections);
1059
+ }
1060
+ }
1061
+ };
1062
+ walk2(selections);
1063
+ const conditions = [...names];
1064
+ conditionsCache.set(selections, conditions);
1065
+ return conditions;
1066
+ }
1067
+
1068
+ // src/core/live-preview/normalize-query.ts
1069
+ var debug2 = createScopedLogger("live-preview:normalize");
1070
+ var INDEX_SEGMENT = /^\d+$/;
1071
+ var FORBIDDEN_SEGMENTS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
1072
+ var ENVELOPE_KEYS = /* @__PURE__ */ new Set(["data", "errors", "extensions"]);
1073
+ function normalizeQuery(query, result, options = {}) {
1074
+ return applyPatchLog(
1075
+ query,
1076
+ result,
1077
+ parsePatchLog(options.log),
1078
+ options.operationName
199
1079
  );
200
- requestHeaders.forEach((value, key) => {
201
- context.request.headers.set(key, value);
1080
+ }
1081
+ function applyPatchLog(query, result, log, operationName) {
1082
+ if (!log.length || result === null || typeof result !== "object") {
1083
+ return result;
1084
+ }
1085
+ if (isEnvelope(result)) {
1086
+ const data = applyPatchLog(query, result.data, log, operationName);
1087
+ return data === result.data ? result : { ...result, data };
1088
+ }
1089
+ let doc = null;
1090
+ try {
1091
+ doc = readQueryDocument(query, operationName);
1092
+ } catch (error) {
1093
+ debug2.log("could not read the query; applying fields by literal path", {
1094
+ error: String(error)
1095
+ });
1096
+ }
1097
+ let root = result;
1098
+ let index = null;
1099
+ for (const patch of log) {
1100
+ try {
1101
+ index ?? (index = indexSnapshot(root));
1102
+ const next = applyPatch(root, index, patch, doc, result);
1103
+ if (next !== root) {
1104
+ root = next;
1105
+ if (patch.type === "list" || !isScalarValue(patch.value)) {
1106
+ index = null;
1107
+ }
1108
+ }
1109
+ } catch (error) {
1110
+ debug2.log("could not apply a change", {
1111
+ itemId: patch.itemId,
1112
+ field: patch.field,
1113
+ error: String(error)
1114
+ });
1115
+ }
1116
+ }
1117
+ return root;
1118
+ }
1119
+ function isScalarValue(value) {
1120
+ return value === null || typeof value !== "object";
1121
+ }
1122
+ function applyPatch(root, index, patch, doc, result) {
1123
+ const ownerPaths = index.get(patch.itemId);
1124
+ if (!ownerPaths?.length) return root;
1125
+ const segments = patch.field.split(".");
1126
+ if (segments.some((s) => !s || FORBIDDEN_SEGMENTS2.has(s))) return root;
1127
+ const targets = [];
1128
+ const plain = /* @__PURE__ */ new Set();
1129
+ for (const ownerPath of ownerPaths) {
1130
+ if (doc) {
1131
+ const resolved = resolveTargets(root, doc, ownerPath, segments);
1132
+ root = resolved.root;
1133
+ targets.push(...resolved.targets);
1134
+ resolved.plain.forEach((target) => plain.add(target));
1135
+ } else {
1136
+ targets.push([...ownerPath, ...segments.map(toPathSegment)]);
1137
+ }
1138
+ }
1139
+ if (!targets.length) {
1140
+ debug2.log("no field in the query matches", {
1141
+ itemId: patch.itemId,
1142
+ field: patch.field
1143
+ });
1144
+ return root;
1145
+ }
1146
+ if (patch.type === "field") {
1147
+ for (const target of targets) {
1148
+ const pushed = plain.has(target) && typeof patch.value === "string" ? plainTextFromHtml(patch.value) : patch.value;
1149
+ let value = keepEditLink(readAtPath(root, target), pushed);
1150
+ if (patch.edit && typeof value === "string" && !vercelStegaSplit3(value).encoded) {
1151
+ value = editLinksFor(result, patch.edit.item)?.encode(
1152
+ value,
1153
+ patch.edit.field
1154
+ ) ?? value;
1155
+ }
1156
+ root = writeAtPath(root, target, value);
1157
+ }
1158
+ } else {
1159
+ for (const target of targets) {
1160
+ const selections = doc ? selectionsAt(root, doc, target) : null;
1161
+ const build = doc && selections ? (entry) => buildEntry(doc, selections, entry, {
1162
+ links: editLinks(result, entry),
1163
+ lists: listKeysIn(result)
1164
+ }) : void 0;
1165
+ root = syncListAtPath(root, target, patch.entries, build);
1166
+ }
1167
+ }
1168
+ return root;
1169
+ }
1170
+ function readAtPath(root, path) {
1171
+ let node = root;
1172
+ for (const step of path) {
1173
+ if (node === null || typeof node !== "object") return void 0;
1174
+ node = node[step];
1175
+ }
1176
+ return node;
1177
+ }
1178
+ function isEnvelope(value) {
1179
+ if (Array.isArray(value) || !("data" in value)) return false;
1180
+ return Object.keys(value).every((key) => ENVELOPE_KEYS.has(key));
1181
+ }
1182
+ function toPathSegment(segment) {
1183
+ return INDEX_SEGMENT.test(segment) ? Number(segment) : segment;
1184
+ }
1185
+ function typenameOf(node) {
1186
+ const typename = node.__typename;
1187
+ return typeof typename === "string" ? typename : void 0;
1188
+ }
1189
+ function selectionsAt(root, doc, path) {
1190
+ let node = root;
1191
+ let selections = doc.operation;
1192
+ for (const step of path) {
1193
+ if (Array.isArray(node)) {
1194
+ node = node[step];
1195
+ continue;
1196
+ }
1197
+ if (node === null || typeof node !== "object") return null;
1198
+ const field = collectFields(selections, typenameOf(node), doc).get(
1199
+ String(step)
1200
+ );
1201
+ if (!field) return null;
1202
+ selections = field.selections;
1203
+ node = node[String(step)];
1204
+ }
1205
+ return selections;
1206
+ }
1207
+ function resolveTargets(root, doc, ownerPath, segments) {
1208
+ let owner = root;
1209
+ for (const step of ownerPath) {
1210
+ owner = owner[step];
1211
+ }
1212
+ const selections = selectionsAt(root, doc, ownerPath);
1213
+ if (!selections) return { root, targets: [], plain: /* @__PURE__ */ new Set() };
1214
+ let current = root;
1215
+ const out = [];
1216
+ const plain = /* @__PURE__ */ new Set();
1217
+ const walk2 = (node, sel, i, path) => {
1218
+ if (i === segments.length) {
1219
+ out.push(path);
1220
+ return;
1221
+ }
1222
+ const segment = segments[i];
1223
+ if (Array.isArray(node)) {
1224
+ if (INDEX_SEGMENT.test(segment)) {
1225
+ const position = Number(segment);
1226
+ if (position < node.length) {
1227
+ walk2(node[position], sel, i + 1, [...path, position]);
1228
+ }
1229
+ } else if (segment === "items") {
1230
+ walk2(node, sel, i + 1, path);
1231
+ }
1232
+ return;
1233
+ }
1234
+ if (node === null || typeof node !== "object") return;
1235
+ const record = node;
1236
+ const wanted = graphqlFieldName(segment);
1237
+ const textBody = i === segments.length - 1 && segment === "body" && isTextEntry(record) ? TEXT_BODY_FIELDS : null;
1238
+ let matched = false;
1239
+ for (const field of collectFields(sel, typenameOf(node), doc).values()) {
1240
+ const alias = textBody?.find((f) => f.name === field.name);
1241
+ if (field.name !== segment && field.name !== wanted && !alias) continue;
1242
+ if (!Object.prototype.hasOwnProperty.call(record, field.key)) continue;
1243
+ matched = true;
1244
+ const fieldPath = [...path, field.key];
1245
+ if (alias?.plain) plain.add(fieldPath);
1246
+ let value = record[field.key];
1247
+ const next = segments[i + 1];
1248
+ if (value === null && field.selections.length && next !== void 0 && next !== "items" && !INDEX_SEGMENT.test(next)) {
1249
+ const typename = resolveTypename(
1250
+ doc,
1251
+ field.selections,
1252
+ void 0,
1253
+ void 0
1254
+ );
1255
+ if (typename !== void 0) {
1256
+ value = fillObject(doc, field.selections, typename, {}, void 0, {
1257
+ links: null,
1258
+ lists: listKeysIn(root)
1259
+ });
1260
+ current = writeAtPath(current, fieldPath, value);
1261
+ }
1262
+ }
1263
+ walk2(value, field.selections, i + 1, fieldPath);
1264
+ }
1265
+ if (!matched && segment === "items") walk2(node, sel, i + 1, path);
1266
+ };
1267
+ walk2(owner, selections, 0, ownerPath);
1268
+ return { root: current, targets: out, plain };
1269
+ }
1270
+ var NON_ALPHANUMERIC = /[^a-z0-9]/gi;
1271
+ var typeKey = (name) => name.replace(NON_ALPHANUMERIC, "").toLowerCase();
1272
+ function resolveTypename(doc, selections, typename, typeName) {
1273
+ const known = typeConditions(selections, doc);
1274
+ const explicit = typeof typename === "string" ? typename : void 0;
1275
+ if (!known.length) return explicit ?? null;
1276
+ if (explicit && known.includes(explicit)) return explicit;
1277
+ for (const candidate of [explicit, typeName]) {
1278
+ if (typeof candidate !== "string" || !candidate) continue;
1279
+ const match = known.find((name) => typeKey(name) === typeKey(candidate));
1280
+ if (match) return match;
1281
+ }
1282
+ const named = explicit !== void 0 || typeof typeName === "string";
1283
+ return known.length === 1 && !named ? known[0] : void 0;
1284
+ }
1285
+ function buildEntry(doc, selections, entry, ctx) {
1286
+ const typename = resolveTypename(
1287
+ doc,
1288
+ selections,
1289
+ entry.__typename,
1290
+ entry.typeName
1291
+ );
1292
+ if (typename === void 0) return void 0;
1293
+ return fillObject(
1294
+ doc,
1295
+ selections,
1296
+ typename,
1297
+ entry.fields ?? {},
1298
+ entry._id,
1299
+ ctx
1300
+ );
1301
+ }
1302
+ function fillObject(doc, selections, typename, values, id, ctx) {
1303
+ const out = {};
1304
+ const { links } = ctx;
1305
+ const lists = ctx.lists(typename);
1306
+ const edit = isPlainRecord(values.__edit) ? values.__edit : null;
1307
+ const apiIdOf = /* @__PURE__ */ new Map();
1308
+ for (const key of Object.keys(values)) {
1309
+ apiIdOf.set(key, key);
1310
+ const name = graphqlFieldName(key);
1311
+ if (!apiIdOf.has(name)) apiIdOf.set(name, key);
1312
+ }
1313
+ if (edit && isPlainRecord(edit.apiIds)) {
1314
+ for (const [name, apiId] of Object.entries(edit.apiIds)) {
1315
+ if (typeof apiId === "string") apiIdOf.set(name, apiId);
1316
+ }
1317
+ }
1318
+ const valueOf = (name) => {
1319
+ if (Object.prototype.hasOwnProperty.call(values, name)) return values[name];
1320
+ const key = apiIdOf.get(name);
1321
+ return key !== void 0 && key in values ? values[key] : void 0;
1322
+ };
1323
+ const editField = (name) => {
1324
+ if (!edit) return null;
1325
+ if (typeof edit.field === "string")
1326
+ return name === "body" ? edit.field : null;
1327
+ if (typeof edit.path !== "string") return null;
1328
+ const apiId = apiIdOf.get(name) ?? name;
1329
+ const text = Array.isArray(edit.text) ? edit.text : [];
1330
+ if (!text.includes(apiId) && !text.includes(name)) return null;
1331
+ return `${edit.path}.items.${apiId}`;
1332
+ };
1333
+ const fields = collectFields(selections, typename ?? void 0, doc, {
1334
+ strict: true
202
1335
  });
203
- const response = await next();
204
- for (const cookie of responseCookies) {
205
- response.headers.append("Set-Cookie", serializeCookie(cookie));
1336
+ for (const field of fields.values()) {
1337
+ if (field.name === "__typename") {
1338
+ out[field.key] = typename;
1339
+ } else if (field.name === "_id") {
1340
+ out[field.key] = typeof id === "string" ? id : values._id ?? null;
1341
+ } else if (field.selections.length) {
1342
+ const value = valueOf(field.name);
1343
+ out[field.key] = value == null && lists.has(field.key) ? [] : fillNested(doc, field.selections, value, ctx);
1344
+ } else {
1345
+ const value = valueOf(field.name);
1346
+ if (Array.isArray(value) && value.every(isScalar)) {
1347
+ out[field.key] = value;
1348
+ continue;
1349
+ }
1350
+ if (value == null && lists.has(field.key)) {
1351
+ out[field.key] = [];
1352
+ continue;
1353
+ }
1354
+ const scalar = value === void 0 || value !== null && typeof value === "object" ? null : value;
1355
+ const target = typeof scalar === "string" ? editField(field.name) : null;
1356
+ out[field.key] = target && links ? links.encode(scalar, target) : scalar;
1357
+ }
206
1358
  }
207
- return response;
1359
+ return out;
1360
+ }
1361
+ function fillNested(doc, selections, value, ctx) {
1362
+ const one = (item) => {
1363
+ if (!isPlainRecord(item)) return null;
1364
+ const typename = resolveTypename(
1365
+ doc,
1366
+ selections,
1367
+ item.__typename,
1368
+ item.typeName
1369
+ );
1370
+ if (typename === void 0) return null;
1371
+ return fillObject(doc, selections, typename, item, item._id, ctx);
1372
+ };
1373
+ if (Array.isArray(value)) return value.map(one).filter((v) => v !== null);
1374
+ return value === void 0 ? null : one(value);
1375
+ }
1376
+ var NO_KEYS = /* @__PURE__ */ new Set();
1377
+ var listKeysCache = /* @__PURE__ */ new WeakMap();
1378
+ function listKeysIn(result) {
1379
+ return (typename) => {
1380
+ if (!typename || result === null || typeof result !== "object") {
1381
+ return NO_KEYS;
1382
+ }
1383
+ let byType = listKeysCache.get(result);
1384
+ if (!byType) {
1385
+ byType = /* @__PURE__ */ new Map();
1386
+ const seen = /* @__PURE__ */ new WeakSet();
1387
+ const walk2 = (node) => {
1388
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
1389
+ seen.add(node);
1390
+ if (Array.isArray(node)) {
1391
+ node.forEach(walk2);
1392
+ return;
1393
+ }
1394
+ const record = node;
1395
+ const type = typeof record.__typename === "string" ? record.__typename : null;
1396
+ for (const [key, value] of Object.entries(record)) {
1397
+ if (type && Array.isArray(value)) {
1398
+ let keys = byType.get(type);
1399
+ if (!keys) byType.set(type, keys = /* @__PURE__ */ new Set());
1400
+ keys.add(key);
1401
+ }
1402
+ walk2(value);
1403
+ }
1404
+ };
1405
+ walk2(result);
1406
+ listKeysCache.set(result, byType);
1407
+ }
1408
+ return byType.get(typename) ?? NO_KEYS;
1409
+ };
1410
+ }
1411
+
1412
+ // src/core/live-preview/live-request.ts
1413
+ var MAX_BODY_BYTES = 1e6;
1414
+ function requestOrigin(request) {
1415
+ const url = new URL(request.url);
1416
+ const proto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
1417
+ if (proto === "https" || proto === "http") url.protocol = `${proto}:`;
1418
+ return url.origin;
1419
+ }
1420
+ async function readLiveLogFromRequest(request) {
1421
+ try {
1422
+ if (request.method !== "POST") return [];
1423
+ if (request.headers.get(HEADER_LIVE_RENDER) !== "1") return [];
1424
+ const origin = request.headers.get("origin");
1425
+ if (!origin || origin !== requestOrigin(request)) return [];
1426
+ const type = request.headers.get("content-type") ?? "";
1427
+ if (!type.toLowerCase().startsWith("application/json")) return [];
1428
+ const length = Number(request.headers.get("content-length") ?? "0");
1429
+ if (length > MAX_BODY_BYTES) return [];
1430
+ const text = await request.clone().text();
1431
+ if (text.length > MAX_BODY_BYTES) return [];
1432
+ const body = JSON.parse(text);
1433
+ return parsePatchLog(body?.log);
1434
+ } catch {
1435
+ return [];
1436
+ }
1437
+ }
1438
+
1439
+ // src/core/live-preview/edit-links.ts
1440
+ import {
1441
+ vercelStegaCombine as vercelStegaCombine2,
1442
+ vercelStegaDecode as vercelStegaDecode2,
1443
+ vercelStegaSplit as vercelStegaSplit4
1444
+ } from "@vercel/stega";
1445
+ var ENTRY_PARAM = "entry";
1446
+ var TOP_LEVEL_ENTRY = /^[A-Za-z0-9_]+\.\d+$/;
1447
+ function entryIdOf(element) {
1448
+ if (!isObject(element)) return void 0;
1449
+ if (typeof element._id === "string") return element._id;
1450
+ if (element.__typename !== "Assets" || !Array.isArray(element.items)) {
1451
+ return void 0;
1452
+ }
1453
+ const first = element.items[0];
1454
+ return isObject(first) && typeof first._id === "string" ? first._id : void 0;
208
1455
  }
1456
+ function annotate(value, ctx) {
1457
+ if (!ctx.entryId) return value;
1458
+ const { cleaned, encoded } = vercelStegaSplit4(value);
1459
+ if (!encoded) return value;
1460
+ let payload;
1461
+ try {
1462
+ payload = vercelStegaDecode2(encoded);
1463
+ } catch {
1464
+ return value;
1465
+ }
1466
+ if (typeof payload?.href !== "string") return value;
1467
+ let url;
1468
+ try {
1469
+ url = new URL(payload.href);
1470
+ } catch {
1471
+ return value;
1472
+ }
1473
+ if (url.searchParams.has(ENTRY_PARAM)) return value;
1474
+ url.searchParams.set(ENTRY_PARAM, ctx.entryId);
1475
+ const itemId = decodeURIComponent(url.pathname.split("/").pop() ?? "");
1476
+ if (!url.searchParams.has("field") && ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) && itemId === ctx.entryOwnerId) {
1477
+ url.searchParams.set("field", ctx.entryField);
1478
+ }
1479
+ return vercelStegaCombine2(
1480
+ cleaned,
1481
+ { ...payload, href: url.toString() },
1482
+ false
1483
+ );
1484
+ }
1485
+ function walk(value, selections, ctx) {
1486
+ if (typeof value === "string") return annotate(value, ctx);
1487
+ if (Array.isArray(value)) {
1488
+ let changed2 = false;
1489
+ const next2 = value.map((element, index) => {
1490
+ const path = [...ctx.path, String(index)];
1491
+ const entryId = ctx.inAssets ? void 0 : entryIdOf(element);
1492
+ const entry = entryId ? {
1493
+ entryId,
1494
+ entryField: ctx.ownerId ? path.join(".") : void 0,
1495
+ entryOwnerId: ctx.ownerId,
1496
+ inAssets: isObject(element) && element._id === void 0
1497
+ } : {};
1498
+ const out = walk(element, selections, { ...ctx, ...entry, path });
1499
+ if (out !== element) changed2 = true;
1500
+ return out;
1501
+ });
1502
+ return changed2 ? next2 : value;
1503
+ }
1504
+ if (!isObject(value)) return value;
1505
+ const id = typeof value._id === "string" ? value._id : void 0;
1506
+ const typename = typeof value.__typename === "string" ? value.__typename : void 0;
1507
+ const fields = ctx.doc && selections ? collectFields(selections, typename, ctx.doc) : null;
1508
+ let changed = false;
1509
+ const next = {};
1510
+ for (const [key, child] of Object.entries(value)) {
1511
+ const field = fields?.get(key);
1512
+ const name = field?.name ?? key;
1513
+ const out = walk(child, field?.selections ?? null, {
1514
+ ...ctx,
1515
+ ownerId: id ?? ctx.ownerId,
1516
+ path: id ? [name] : [...ctx.path, name]
1517
+ });
1518
+ if (out !== child) changed = true;
1519
+ next[key] = out;
1520
+ }
1521
+ return changed ? next : value;
1522
+ }
1523
+ function annotateEditLinks(result, query, operationName) {
1524
+ let doc = null;
1525
+ if (query !== void 0) {
1526
+ try {
1527
+ doc = readQueryDocument(query, operationName);
1528
+ } catch {
1529
+ doc = null;
1530
+ }
1531
+ }
1532
+ return walk(result, doc?.operation ?? null, { doc, path: [] });
1533
+ }
1534
+
1535
+ // src/core/server.ts
1536
+ var PreprError = class extends Error {
1537
+ constructor(message, code, context, originalError) {
1538
+ super(message);
1539
+ this.code = code;
1540
+ this.context = context;
1541
+ this.originalError = originalError;
1542
+ this.name = "PreprError";
1543
+ }
1544
+ };
1545
+ function getPreprUUIDFromHeaders(headers) {
1546
+ return headers.get("prepr-customer-id");
1547
+ }
1548
+ function getActiveSegmentFromHeaders(headers) {
1549
+ return headers.get("Prepr-Segments");
1550
+ }
1551
+ function getActiveVariantFromHeaders(headers) {
1552
+ return headers.get("Prepr-ABtesting");
1553
+ }
1554
+ var PREPR_HEADER_KEYS = [
1555
+ "prepr-customer-id",
1556
+ "Prepr-Segments",
1557
+ "Prepr-ABtesting",
1558
+ "Prepr-Preview-Bar",
1559
+ "Prepr-Context-utm_source",
1560
+ "Prepr-Context-utm_medium",
1561
+ "Prepr-Context-utm_term",
1562
+ "Prepr-Context-utm_content",
1563
+ "Prepr-Context-utm_campaign",
1564
+ "Prepr-Context-initial_referral",
1565
+ "Prepr-Visitor-IP",
1566
+ "Prepr-Hubspot-Id",
1567
+ "Prepr-Customer-Id-Created",
1568
+ "User-Agent",
1569
+ "Prepr-Package"
1570
+ ];
1571
+ function getPreprHeadersFromHeaders(headers) {
1572
+ const preprHeaders = {};
1573
+ const copy = (key) => {
1574
+ const value = headers.get(key);
1575
+ if (value !== null) {
1576
+ preprHeaders[key] = value;
1577
+ }
1578
+ };
1579
+ for (const key of PREPR_HEADER_KEYS) {
1580
+ copy(key);
1581
+ }
1582
+ return preprHeaders;
1583
+ }
1584
+ function validatePreprToken(token) {
1585
+ if (!token) {
1586
+ throw new PreprError(
1587
+ "Token is required",
1588
+ "MISSING_TOKEN",
1589
+ "validatePreprToken"
1590
+ );
1591
+ }
1592
+ if (!token.startsWith("https://")) {
1593
+ throw new PreprError(
1594
+ "Token must be a valid HTTPS URL",
1595
+ "INVALID_TOKEN",
1596
+ "validatePreprToken"
1597
+ );
1598
+ }
1599
+ }
1600
+ function extractAccessToken(graphqlUrl) {
1601
+ let url;
1602
+ try {
1603
+ url = new URL(graphqlUrl);
1604
+ } catch (error) {
1605
+ throw new PreprError(
1606
+ "Token must be a valid URL",
1607
+ "INVALID_TOKEN",
1608
+ "extractAccessToken",
1609
+ error instanceof Error ? error : new Error(String(error))
1610
+ );
1611
+ }
1612
+ if (url.hostname !== "graphql.prepr.io") {
1613
+ throw new PreprError(
1614
+ "Token must be a graphql.prepr.io URL",
1615
+ "INVALID_TOKEN",
1616
+ "extractAccessToken"
1617
+ );
1618
+ }
1619
+ const pathParts = url.pathname.split("/");
1620
+ const token = pathParts[pathParts.length - 1];
1621
+ if (!token) {
1622
+ throw new PreprError(
1623
+ "Token URL is missing an access token segment",
1624
+ "INVALID_TOKEN",
1625
+ "extractAccessToken"
1626
+ );
1627
+ }
1628
+ return token;
1629
+ }
1630
+ async function getPreprEnvironmentSegments(token) {
1631
+ validatePreprToken(token);
1632
+ try {
1633
+ const response = await fetch(token, {
1634
+ headers: {
1635
+ "Prepr-Package": `@preprio/toolkit@${VERSION}`,
1636
+ // Duplicates the version in Prepr-Package. It keeps the User-Agent
1637
+ // format used by `@preprio/prepr-nextjs`, for Prepr API consumers that
1638
+ // still identify the toolbar by that string.
1639
+ "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
1640
+ "Content-Type": "application/json"
1641
+ },
1642
+ method: "POST",
1643
+ body: JSON.stringify({
1644
+ query: `{
1645
+ _Segments {
1646
+ _id
1647
+ name
1648
+ }
1649
+ }`
1650
+ })
1651
+ });
1652
+ if (!response.ok) {
1653
+ throw new PreprError(
1654
+ `HTTP ${response.status}: ${response.statusText}`,
1655
+ "HTTP_ERROR",
1656
+ "getPreprEnvironmentSegments"
1657
+ );
1658
+ }
1659
+ const json = await response.json();
1660
+ if (!json || !json.data || !json.data._Segments) {
1661
+ throw new PreprError(
1662
+ "Invalid response format from Prepr API",
1663
+ "INVALID_RESPONSE",
1664
+ "getPreprEnvironmentSegments"
1665
+ );
1666
+ }
1667
+ return json.data._Segments;
1668
+ } catch (error) {
1669
+ if (error instanceof PreprError) {
1670
+ throw error;
1671
+ }
1672
+ throw new PreprError(
1673
+ "Failed to fetch segments from Prepr API",
1674
+ "FETCH_ERROR",
1675
+ "getPreprEnvironmentSegments",
1676
+ error instanceof Error ? error : new Error(String(error))
1677
+ );
1678
+ }
1679
+ }
1680
+ async function getToolbarPropsFromHeaders(headers, token, features) {
1681
+ const resolved = resolveFeatures(features);
1682
+ let segments = [];
1683
+ if (resolved.segments) {
1684
+ try {
1685
+ segments = await getPreprEnvironmentSegments(token);
1686
+ } catch {
1687
+ segments = [];
1688
+ }
1689
+ }
1690
+ return {
1691
+ activeSegment: resolved.segments ? getActiveSegmentFromHeaders(headers) : null,
1692
+ activeVariant: resolved.abTesting ? getActiveVariantFromHeaders(headers) : null,
1693
+ segments,
1694
+ data: segments
1695
+ };
1696
+ }
1697
+
1698
+ // src/core/request-helpers.ts
209
1699
  function getPreprUUID(headers) {
210
1700
  return getPreprUUIDFromHeaders(headers);
211
1701
  }
@@ -221,12 +1711,50 @@ function getPreprHeaders(headers) {
221
1711
  async function getToolbarProps(headers, token, features) {
222
1712
  return getToolbarPropsFromHeaders(headers, token, features);
223
1713
  }
1714
+
1715
+ // src/astro/index.ts
1716
+ var LIVE_LOG = /* @__PURE__ */ Symbol.for("@preprio/toolkit/astro-live-log");
1717
+ async function onPreprRequest(context, next, options) {
1718
+ const { requestHeaders, responseCookies } = processFrameworkRequest(
1719
+ context.request,
1720
+ options,
1721
+ "astro"
1722
+ );
1723
+ requestHeaders.forEach((value, key) => {
1724
+ context.request.headers.set(key, value);
1725
+ });
1726
+ const log = options?.preview && context.locals ? await readLiveLogFromRequest(context.request) : [];
1727
+ if (log.length && context.locals) {
1728
+ context.locals[LIVE_LOG] = log;
1729
+ }
1730
+ const response = await next();
1731
+ if (log.length) {
1732
+ response.headers.set("Cache-Control", "private, no-store");
1733
+ }
1734
+ for (const cookie of responseCookies) {
1735
+ response.headers.append("Set-Cookie", serializeCookie(cookie));
1736
+ }
1737
+ return response;
1738
+ }
1739
+ function normalizeQuery2(query, result, options = {}) {
1740
+ if (!options.enabled) return result;
1741
+ const annotated = annotateEditLinks(result, query, options.operationName);
1742
+ const log = options.locals?.[LIVE_LOG];
1743
+ if (!log?.length) return annotated;
1744
+ return normalizeQuery(query, annotated, {
1745
+ log,
1746
+ operationName: options.operationName
1747
+ });
1748
+ }
224
1749
  export {
1750
+ PreprError,
1751
+ extractAccessToken,
225
1752
  getActiveSegment,
226
1753
  getActiveVariant,
227
1754
  getPreprHeaders,
228
1755
  getPreprUUID,
229
1756
  getToolbarProps,
230
- isPersonalizedResponse,
231
- onPreprRequest
1757
+ normalizeQuery2 as normalizeQuery,
1758
+ onPreprRequest,
1759
+ validatePreprToken
232
1760
  };