@preprio/toolkit 1.0.0-rc.4 → 1.0.0-rc.5

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.
@@ -236,6 +236,46 @@ interface NextNormalizeQueryOptions {
236
236
  * component that should update. Server-only; Next.js 16+.
237
237
  */
238
238
  declare function normalizeQuery<T>(query: QueryInput, result: T, options?: NextNormalizeQueryOptions): Promise<T>;
239
+ interface LivePreviewFetchKey {
240
+ /** The query the fetcher runs, string or document. */
241
+ query: QueryInput;
242
+ /** Its variables. */
243
+ variables?: Record<string, unknown>;
244
+ }
245
+ interface LivePreviewFetchOptions {
246
+ /**
247
+ * Pass the same preview flag as the middleware; never `true` on a
248
+ * production deployment. When false (the default) the fetcher runs as it
249
+ * is and the request is not read.
250
+ */
251
+ enabled?: boolean;
252
+ }
253
+ /**
254
+ * Skips the Prepr request while an editor types. Wrap the fetch of a query
255
+ * whose result goes through `normalizeQuery`:
256
+ *
257
+ * ```ts
258
+ * const data = await livePreviewFetch(
259
+ * { query: GetPageDocument, variables: { slug } },
260
+ * () => fetchFromPrepr(GetPageDocument, { slug }),
261
+ * { enabled: isPreview },
262
+ * );
263
+ * const page = await normalizeQuery(GetPageDocument, data, { enabled: isPreview });
264
+ * ```
265
+ *
266
+ * A render for unsaved changes gets the response of the last full render of
267
+ * the same query, variables and Prepr headers; `normalizeQuery` puts the
268
+ * changes on top. Every other render (a page load, a save) runs the fetcher
269
+ * and stores what it returns. Stored content is not changed by typing, so
270
+ * the page shows the same as without this helper.
271
+ *
272
+ * Responses are kept in the memory of the server process, a few at a time
273
+ * and for a few minutes; another instance or an expired response runs the
274
+ * fetcher. Treat the returned value as read-only: renders share it. Keys
275
+ * must tell responses apart, so include every variable the fetcher uses.
276
+ * Server-only.
277
+ */
278
+ declare function livePreviewFetch<T>(key: LivePreviewFetchKey, fetcher: () => Promise<T>, options?: LivePreviewFetchOptions): Promise<T>;
239
279
 
240
280
  /** Error thrown by the token helpers and the segments fetch. */
241
281
  declare class PreprError extends Error {
@@ -340,6 +380,12 @@ interface PreprRefreshProps {
340
380
  allowedEditorOrigins?: string[];
341
381
  /** Your preview token uses GraphQL strict mode; see the toolbar option. */
342
382
  strictMode?: boolean;
383
+ /**
384
+ * How long typing must pause, in milliseconds, before the unsaved changes
385
+ * go to the server. Default 150. Lower shows changes sooner at the cost of
386
+ * more server renders; raise it when a render is expensive.
387
+ */
388
+ syncDebounceMs?: number;
343
389
  }
344
390
  interface UseLiveOptions {
345
391
  /** Query (string or DocumentNode) passed as-is to the fetcher. */
@@ -347,4 +393,4 @@ interface UseLiveOptions {
347
393
  variables?: Record<string, unknown>;
348
394
  }
349
395
 
350
- export { type LiveFetcher, type LivePreviewConfig, type NextNormalizeQueryOptions, PreprError, type PreprMiddlewareOptions, type PreprRefreshProps, PreprToolbar, PreprTrackingPixel, type PreprTrackingPixelProps, type UseLiveOptions, createPreprMiddleware, extractAccessToken, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprUUID, getToolbarProps, normalizeQuery, validatePreprToken };
396
+ export { type LiveFetcher, type LivePreviewConfig, type LivePreviewFetchKey, type LivePreviewFetchOptions, type NextNormalizeQueryOptions, PreprError, type PreprMiddlewareOptions, type PreprRefreshProps, PreprToolbar, PreprTrackingPixel, type PreprTrackingPixelProps, type UseLiveOptions, createPreprMiddleware, extractAccessToken, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprUUID, getToolbarProps, livePreviewFetch, normalizeQuery, validatePreprToken };
@@ -236,6 +236,46 @@ interface NextNormalizeQueryOptions {
236
236
  * component that should update. Server-only; Next.js 16+.
237
237
  */
238
238
  declare function normalizeQuery<T>(query: QueryInput, result: T, options?: NextNormalizeQueryOptions): Promise<T>;
239
+ interface LivePreviewFetchKey {
240
+ /** The query the fetcher runs, string or document. */
241
+ query: QueryInput;
242
+ /** Its variables. */
243
+ variables?: Record<string, unknown>;
244
+ }
245
+ interface LivePreviewFetchOptions {
246
+ /**
247
+ * Pass the same preview flag as the middleware; never `true` on a
248
+ * production deployment. When false (the default) the fetcher runs as it
249
+ * is and the request is not read.
250
+ */
251
+ enabled?: boolean;
252
+ }
253
+ /**
254
+ * Skips the Prepr request while an editor types. Wrap the fetch of a query
255
+ * whose result goes through `normalizeQuery`:
256
+ *
257
+ * ```ts
258
+ * const data = await livePreviewFetch(
259
+ * { query: GetPageDocument, variables: { slug } },
260
+ * () => fetchFromPrepr(GetPageDocument, { slug }),
261
+ * { enabled: isPreview },
262
+ * );
263
+ * const page = await normalizeQuery(GetPageDocument, data, { enabled: isPreview });
264
+ * ```
265
+ *
266
+ * A render for unsaved changes gets the response of the last full render of
267
+ * the same query, variables and Prepr headers; `normalizeQuery` puts the
268
+ * changes on top. Every other render (a page load, a save) runs the fetcher
269
+ * and stores what it returns. Stored content is not changed by typing, so
270
+ * the page shows the same as without this helper.
271
+ *
272
+ * Responses are kept in the memory of the server process, a few at a time
273
+ * and for a few minutes; another instance or an expired response runs the
274
+ * fetcher. Treat the returned value as read-only: renders share it. Keys
275
+ * must tell responses apart, so include every variable the fetcher uses.
276
+ * Server-only.
277
+ */
278
+ declare function livePreviewFetch<T>(key: LivePreviewFetchKey, fetcher: () => Promise<T>, options?: LivePreviewFetchOptions): Promise<T>;
239
279
 
240
280
  /** Error thrown by the token helpers and the segments fetch. */
241
281
  declare class PreprError extends Error {
@@ -340,6 +380,12 @@ interface PreprRefreshProps {
340
380
  allowedEditorOrigins?: string[];
341
381
  /** Your preview token uses GraphQL strict mode; see the toolbar option. */
342
382
  strictMode?: boolean;
383
+ /**
384
+ * How long typing must pause, in milliseconds, before the unsaved changes
385
+ * go to the server. Default 150. Lower shows changes sooner at the cost of
386
+ * more server renders; raise it when a render is expensive.
387
+ */
388
+ syncDebounceMs?: number;
343
389
  }
344
390
  interface UseLiveOptions {
345
391
  /** Query (string or DocumentNode) passed as-is to the fetcher. */
@@ -347,4 +393,4 @@ interface UseLiveOptions {
347
393
  variables?: Record<string, unknown>;
348
394
  }
349
395
 
350
- export { type LiveFetcher, type LivePreviewConfig, type NextNormalizeQueryOptions, PreprError, type PreprMiddlewareOptions, type PreprRefreshProps, PreprToolbar, PreprTrackingPixel, type PreprTrackingPixelProps, type UseLiveOptions, createPreprMiddleware, extractAccessToken, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprUUID, getToolbarProps, normalizeQuery, validatePreprToken };
396
+ export { type LiveFetcher, type LivePreviewConfig, type LivePreviewFetchKey, type LivePreviewFetchOptions, type NextNormalizeQueryOptions, PreprError, type PreprMiddlewareOptions, type PreprRefreshProps, PreprToolbar, PreprTrackingPixel, type PreprTrackingPixelProps, type UseLiveOptions, createPreprMiddleware, extractAccessToken, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprUUID, getToolbarProps, livePreviewFetch, normalizeQuery, validatePreprToken };
@@ -2,7 +2,7 @@
2
2
  import { NextResponse } from "next/server";
3
3
 
4
4
  // src/version.ts
5
- var VERSION = "1.0.0-rc.4";
5
+ var VERSION = "1.0.0-rc.5";
6
6
 
7
7
  // src/core/constants.ts
8
8
  var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
@@ -1302,8 +1302,9 @@ function listKeysIn(result) {
1302
1302
 
1303
1303
  // src/core/live-preview/edit-links.ts
1304
1304
  import {
1305
- vercelStegaCombine as vercelStegaCombine2,
1305
+ legacyStegaEncode,
1306
1306
  vercelStegaDecode as vercelStegaDecode2,
1307
+ vercelStegaEncode,
1307
1308
  vercelStegaSplit as vercelStegaSplit4
1308
1309
  } from "@vercel/stega";
1309
1310
  var ENTRY_PARAM = "entry";
@@ -1317,34 +1318,53 @@ function entryIdOf(element) {
1317
1318
  const first = element.items[0];
1318
1319
  return isObject(first) && typeof first._id === "string" ? first._id : void 0;
1319
1320
  }
1320
- function annotate(value, ctx) {
1321
- if (!ctx.entryId) return value;
1322
- const { cleaned, encoded } = vercelStegaSplit4(value);
1323
- if (!encoded) return value;
1321
+ function encodeLink(payload) {
1322
+ try {
1323
+ return legacyStegaEncode(payload);
1324
+ } catch {
1325
+ return vercelStegaEncode(payload);
1326
+ }
1327
+ }
1328
+ function rewriteLink(encoded, entryId, entryField, entryOwnerId) {
1324
1329
  let payload;
1325
1330
  try {
1326
1331
  payload = vercelStegaDecode2(encoded);
1327
1332
  } catch {
1328
- return value;
1333
+ return "";
1329
1334
  }
1330
- if (typeof payload?.href !== "string") return value;
1335
+ if (typeof payload?.href !== "string") return "";
1331
1336
  let url;
1332
1337
  try {
1333
1338
  url = new URL(payload.href);
1334
1339
  } catch {
1335
- return value;
1340
+ return "";
1336
1341
  }
1337
- if (url.searchParams.has(ENTRY_PARAM)) return value;
1338
- url.searchParams.set(ENTRY_PARAM, ctx.entryId);
1342
+ if (url.searchParams.has(ENTRY_PARAM)) return "";
1343
+ url.searchParams.set(ENTRY_PARAM, entryId);
1339
1344
  const itemId = decodeURIComponent(url.pathname.split("/").pop() ?? "");
1340
- if (!url.searchParams.has("field") && ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) && itemId === ctx.entryOwnerId) {
1341
- url.searchParams.set("field", ctx.entryField);
1345
+ if (!url.searchParams.has("field") && entryField && itemId === entryOwnerId) {
1346
+ url.searchParams.set("field", entryField);
1342
1347
  }
1343
- return vercelStegaCombine2(
1344
- cleaned,
1345
- { ...payload, href: url.toString() },
1346
- false
1347
- );
1348
+ return encodeLink({ ...payload, href: url.toString() });
1349
+ }
1350
+ var MAX_REWRITTEN = 1e4;
1351
+ var rewritten = /* @__PURE__ */ new Map();
1352
+ function annotate(value, ctx) {
1353
+ if (!ctx.entryId) return value;
1354
+ const { cleaned, encoded } = vercelStegaSplit4(value);
1355
+ if (!encoded) return value;
1356
+ const entryField = ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) ? ctx.entryField : "";
1357
+ const key = `${ctx.entryId}
1358
+ ${entryField}
1359
+ ${ctx.entryOwnerId ?? ""}
1360
+ ${encoded}`;
1361
+ let link = rewritten.get(key);
1362
+ if (link === void 0) {
1363
+ link = rewriteLink(encoded, ctx.entryId, entryField, ctx.entryOwnerId);
1364
+ if (rewritten.size >= MAX_REWRITTEN) rewritten.clear();
1365
+ rewritten.set(key, link);
1366
+ }
1367
+ return link ? cleaned + link : value;
1348
1368
  }
1349
1369
  function walk(value, selections, ctx) {
1350
1370
  if (typeof value === "string") return annotate(value, ctx);
@@ -1425,11 +1445,17 @@ function takeLiveLog(token) {
1425
1445
  if (!token || !TOKEN_PATTERN.test(token)) return [];
1426
1446
  const map = slots();
1427
1447
  const slot = map.get(token);
1428
- map.delete(token);
1429
1448
  const now = Date.now();
1430
1449
  prune(map, now);
1431
1450
  if (!slot || slot.expires <= now) return [];
1432
- return slot.log;
1451
+ const { log } = slot;
1452
+ slot.log = [];
1453
+ return log;
1454
+ }
1455
+ function hasLiveLog(token) {
1456
+ if (!token || !TOKEN_PATTERN.test(token)) return false;
1457
+ const slot = slots().get(token);
1458
+ return slot !== void 0 && slot.expires > Date.now();
1433
1459
  }
1434
1460
 
1435
1461
  // src/core/server.ts
@@ -1641,6 +1667,59 @@ async function normalizeQuery(query, result, options = {}) {
1641
1667
  if (!log.length) return annotated;
1642
1668
  return applyPatchLog(query, annotated, log, options.operationName);
1643
1669
  }
1670
+ var MAX_STORED_RESPONSES = 30;
1671
+ var STORED_RESPONSE_TTL_MS = 5 * 6e4;
1672
+ var storedResponses = /* @__PURE__ */ new Map();
1673
+ var documentIds = /* @__PURE__ */ new WeakMap();
1674
+ var nextDocumentId = 0;
1675
+ function queryKey(query) {
1676
+ if (typeof query === "string") return query;
1677
+ let id = documentIds.get(query);
1678
+ if (id === void 0) documentIds.set(query, id = nextDocumentId++);
1679
+ return `#${id}`;
1680
+ }
1681
+ function responseKey(key, preprHeaders) {
1682
+ try {
1683
+ return JSON.stringify([
1684
+ queryKey(key.query),
1685
+ key.variables ?? null,
1686
+ // Segment, A/B variant and visitor decide what Prepr returns.
1687
+ Object.entries(preprHeaders).sort(([a], [b]) => a < b ? -1 : 1)
1688
+ ]);
1689
+ } catch {
1690
+ return null;
1691
+ }
1692
+ }
1693
+ async function livePreviewFetch(key, fetcher, options = {}) {
1694
+ if (!options.enabled) return fetcher();
1695
+ let unsaved;
1696
+ let preprHeaders;
1697
+ try {
1698
+ const h = await readHeaders();
1699
+ preprHeaders = getPreprHeadersFromHeaders(h);
1700
+ unsaved = h.has(HEADER_NEXT_ACTION) && hasLiveLog((await cookies()).get(LIVE_LOG_COOKIE)?.value);
1701
+ } catch (error) {
1702
+ navigation.unstable_rethrow?.(error);
1703
+ return fetcher();
1704
+ }
1705
+ const id = responseKey(key, preprHeaders);
1706
+ if (id === null) return fetcher();
1707
+ const now = Date.now();
1708
+ if (unsaved) {
1709
+ const stored = storedResponses.get(id);
1710
+ if (stored && stored.expires > now) return stored.value;
1711
+ }
1712
+ const value = await fetcher();
1713
+ storedResponses.delete(id);
1714
+ for (const [other, stored] of storedResponses) {
1715
+ if (stored.expires > now && storedResponses.size < MAX_STORED_RESPONSES) {
1716
+ break;
1717
+ }
1718
+ storedResponses.delete(other);
1719
+ }
1720
+ storedResponses.set(id, { value, expires: now + STORED_RESPONSE_TTL_MS });
1721
+ return value;
1722
+ }
1644
1723
 
1645
1724
  // src/nextjs/index.ts
1646
1725
  import {
@@ -1658,6 +1737,7 @@ export {
1658
1737
  getPreprHeaders,
1659
1738
  getPreprUUID,
1660
1739
  getToolbarProps,
1740
+ livePreviewFetch,
1661
1741
  normalizeQuery,
1662
1742
  validatePreprToken
1663
1743
  };
@@ -1,8 +1,8 @@
1
1
  "use server";
2
2
  import {
3
3
  isPreviewFromHeaders
4
- } from "../chunk-6PMBN7OR.js";
5
- import "../chunk-QWTSVPEQ.js";
4
+ } from "../chunk-GRFTP62X.js";
5
+ import "../chunk-A4J3JRMY.js";
6
6
  import {
7
7
  parsePatchLog
8
8
  } from "../chunk-KM2GME62.js";
@@ -1798,6 +1798,7 @@ function createLiveStarter(options = {}) {
1798
1798
  var import_live_action = require("./live-action.cjs");
1799
1799
  var debug6 = createScopedLogger("live-preview:next");
1800
1800
  var LOG_SYNC_DEBOUNCE_MS = 150;
1801
+ var debounceOf = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : LOG_SYNC_DEBOUNCE_MS;
1801
1802
  var starter = createLiveStarter({
1802
1803
  storeOptions() {
1803
1804
  const skipped = new Set(quarantined());
@@ -1842,7 +1843,8 @@ function useLive(data, opts) {
1842
1843
  function PreprRefresh({
1843
1844
  enabled = false,
1844
1845
  allowedEditorOrigins: origins,
1845
- strictMode: strict = false
1846
+ strictMode: strict = false,
1847
+ syncDebounceMs
1846
1848
  }) {
1847
1849
  const router = (0, import_navigation.useRouter)();
1848
1850
  const originsKey = origins?.join(" ");
@@ -1852,7 +1854,7 @@ function PreprRefresh({
1852
1854
  strictMode: strict,
1853
1855
  allowedEditorOrigins: originsKey?.split(" ")
1854
1856
  });
1855
- const sync = createLogSync();
1857
+ const sync = createLogSync(debounceOf(syncDebounceMs));
1856
1858
  let unsubscribe = null;
1857
1859
  let active = true;
1858
1860
  void starter.start().then((started) => {
@@ -1872,7 +1874,7 @@ function PreprRefresh({
1872
1874
  unsubscribe?.();
1873
1875
  sync.cancel();
1874
1876
  };
1875
- }, [enabled, originsKey, strict, router]);
1877
+ }, [enabled, originsKey, strict, syncDebounceMs, router]);
1876
1878
  return null;
1877
1879
  }
1878
1880
  var STEGA_CHARS = /[\u200b-\u200d\u2060-\u2064\ufeff]/;
@@ -1947,7 +1949,7 @@ function watchClientRenders(watched) {
1947
1949
  }, CLIENT_RENDER_MS);
1948
1950
  });
1949
1951
  }
1950
- function createLogSync() {
1952
+ function createLogSync(debounceMs) {
1951
1953
  let timer = null;
1952
1954
  let inFlight = false;
1953
1955
  let pending = null;
@@ -1999,7 +2001,7 @@ function createLogSync() {
1999
2001
  timer = null;
2000
2002
  if (inFlight) pending = log;
2001
2003
  else void send(log);
2002
- }, LOG_SYNC_DEBOUNCE_MS);
2004
+ }, debounceMs);
2003
2005
  },
2004
2006
  cancel() {
2005
2007
  cancelled = true;
@@ -23,6 +23,12 @@ interface PreprRefreshProps {
23
23
  allowedEditorOrigins?: string[];
24
24
  /** Your preview token uses GraphQL strict mode; see the toolbar option. */
25
25
  strictMode?: boolean;
26
+ /**
27
+ * How long typing must pause, in milliseconds, before the unsaved changes
28
+ * go to the server. Default 150. Lower shows changes sooner at the cost of
29
+ * more server renders; raise it when a render is expensive.
30
+ */
31
+ syncDebounceMs?: number;
26
32
  }
27
33
  interface UseLiveOptions {
28
34
  /** Query (string or DocumentNode) passed as-is to the fetcher. */
@@ -49,6 +55,6 @@ declare function useLive<T>(data: T, opts?: UseLiveOptions): T;
49
55
  * Use this or `useLive` with a `query`, not both: a save would refetch and
50
56
  * refresh.
51
57
  */
52
- declare function PreprRefresh({ enabled, allowedEditorOrigins: origins, strictMode: strict, }: PreprRefreshProps): null;
58
+ declare function PreprRefresh({ enabled, allowedEditorOrigins: origins, strictMode: strict, syncDebounceMs, }: PreprRefreshProps): null;
53
59
 
54
60
  export { type LivePreviewConfig, PreprRefresh, type PreprRefreshProps, type UseLiveOptions, initLivePreview, useLive };
@@ -23,6 +23,12 @@ interface PreprRefreshProps {
23
23
  allowedEditorOrigins?: string[];
24
24
  /** Your preview token uses GraphQL strict mode; see the toolbar option. */
25
25
  strictMode?: boolean;
26
+ /**
27
+ * How long typing must pause, in milliseconds, before the unsaved changes
28
+ * go to the server. Default 150. Lower shows changes sooner at the cost of
29
+ * more server renders; raise it when a render is expensive.
30
+ */
31
+ syncDebounceMs?: number;
26
32
  }
27
33
  interface UseLiveOptions {
28
34
  /** Query (string or DocumentNode) passed as-is to the fetcher. */
@@ -49,6 +55,6 @@ declare function useLive<T>(data: T, opts?: UseLiveOptions): T;
49
55
  * Use this or `useLive` with a `query`, not both: a save would refetch and
50
56
  * refresh.
51
57
  */
52
- declare function PreprRefresh({ enabled, allowedEditorOrigins: origins, strictMode: strict, }: PreprRefreshProps): null;
58
+ declare function PreprRefresh({ enabled, allowedEditorOrigins: origins, strictMode: strict, syncDebounceMs, }: PreprRefreshProps): null;
53
59
 
54
60
  export { type LivePreviewConfig, PreprRefresh, type PreprRefreshProps, type UseLiveOptions, initLivePreview, useLive };
@@ -76,6 +76,7 @@ function createLiveStarter(options = {}) {
76
76
  import { syncPreprLiveLog } from "./live-action.js";
77
77
  var debug = createScopedLogger("live-preview:next");
78
78
  var LOG_SYNC_DEBOUNCE_MS = 150;
79
+ var debounceOf = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : LOG_SYNC_DEBOUNCE_MS;
79
80
  var starter = createLiveStarter({
80
81
  storeOptions() {
81
82
  const skipped = new Set(quarantined());
@@ -120,7 +121,8 @@ function useLive(data, opts) {
120
121
  function PreprRefresh({
121
122
  enabled = false,
122
123
  allowedEditorOrigins: origins,
123
- strictMode: strict = false
124
+ strictMode: strict = false,
125
+ syncDebounceMs
124
126
  }) {
125
127
  const router = useRouter();
126
128
  const originsKey = origins?.join(" ");
@@ -130,7 +132,7 @@ function PreprRefresh({
130
132
  strictMode: strict,
131
133
  allowedEditorOrigins: originsKey?.split(" ")
132
134
  });
133
- const sync = createLogSync();
135
+ const sync = createLogSync(debounceOf(syncDebounceMs));
134
136
  let unsubscribe = null;
135
137
  let active = true;
136
138
  void starter.start().then((started) => {
@@ -150,7 +152,7 @@ function PreprRefresh({
150
152
  unsubscribe?.();
151
153
  sync.cancel();
152
154
  };
153
- }, [enabled, originsKey, strict, router]);
155
+ }, [enabled, originsKey, strict, syncDebounceMs, router]);
154
156
  return null;
155
157
  }
156
158
  var STEGA_CHARS = /[\u200b-\u200d\u2060-\u2064\ufeff]/;
@@ -225,7 +227,7 @@ function watchClientRenders(watched) {
225
227
  }, CLIENT_RENDER_MS);
226
228
  });
227
229
  }
228
- function createLogSync() {
230
+ function createLogSync(debounceMs) {
229
231
  let timer = null;
230
232
  let inFlight = false;
231
233
  let pending = null;
@@ -277,7 +279,7 @@ function createLogSync() {
277
279
  timer = null;
278
280
  if (inFlight) pending = log;
279
281
  else void send(log);
280
- }, LOG_SYNC_DEBOUNCE_MS);
282
+ }, debounceMs);
281
283
  },
282
284
  cancel() {
283
285
  cancelled = true;
@@ -35,7 +35,7 @@ __export(nuxt_exports, {
35
35
  module.exports = __toCommonJS(nuxt_exports);
36
36
 
37
37
  // src/version.ts
38
- var VERSION = "1.0.0-rc.4";
38
+ var VERSION = "1.0.0-rc.5";
39
39
 
40
40
  // src/core/constants.ts
41
41
  var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
@@ -11,7 +11,7 @@ import {
11
11
  } from "./chunk-LUKVPOJ2.js";
12
12
 
13
13
  // src/version.ts
14
- var VERSION = "1.0.0-rc.4";
14
+ var VERSION = "1.0.0-rc.5";
15
15
 
16
16
  // src/core/features.ts
17
17
  function isEnabled(config) {
@@ -1741,34 +1741,53 @@ function entryIdOf(element) {
1741
1741
  const first = element.items[0];
1742
1742
  return isObject(first) && typeof first._id === "string" ? first._id : void 0;
1743
1743
  }
1744
- function annotate(value, ctx) {
1745
- if (!ctx.entryId) return value;
1746
- const { cleaned, encoded } = (0, import_stega.vercelStegaSplit)(value);
1747
- if (!encoded) return value;
1744
+ function encodeLink(payload) {
1745
+ try {
1746
+ return (0, import_stega.legacyStegaEncode)(payload);
1747
+ } catch {
1748
+ return (0, import_stega.vercelStegaEncode)(payload);
1749
+ }
1750
+ }
1751
+ function rewriteLink(encoded, entryId, entryField, entryOwnerId) {
1748
1752
  let payload;
1749
1753
  try {
1750
1754
  payload = (0, import_stega.vercelStegaDecode)(encoded);
1751
1755
  } catch {
1752
- return value;
1756
+ return "";
1753
1757
  }
1754
- if (typeof payload?.href !== "string") return value;
1758
+ if (typeof payload?.href !== "string") return "";
1755
1759
  let url;
1756
1760
  try {
1757
1761
  url = new URL(payload.href);
1758
1762
  } catch {
1759
- return value;
1763
+ return "";
1760
1764
  }
1761
- if (url.searchParams.has(ENTRY_PARAM)) return value;
1762
- url.searchParams.set(ENTRY_PARAM, ctx.entryId);
1765
+ if (url.searchParams.has(ENTRY_PARAM)) return "";
1766
+ url.searchParams.set(ENTRY_PARAM, entryId);
1763
1767
  const itemId = decodeURIComponent(url.pathname.split("/").pop() ?? "");
1764
- if (!url.searchParams.has("field") && ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) && itemId === ctx.entryOwnerId) {
1765
- url.searchParams.set("field", ctx.entryField);
1768
+ if (!url.searchParams.has("field") && entryField && itemId === entryOwnerId) {
1769
+ url.searchParams.set("field", entryField);
1766
1770
  }
1767
- return (0, import_stega.vercelStegaCombine)(
1768
- cleaned,
1769
- { ...payload, href: url.toString() },
1770
- false
1771
- );
1771
+ return encodeLink({ ...payload, href: url.toString() });
1772
+ }
1773
+ var MAX_REWRITTEN = 1e4;
1774
+ var rewritten = /* @__PURE__ */ new Map();
1775
+ function annotate(value, ctx) {
1776
+ if (!ctx.entryId) return value;
1777
+ const { cleaned, encoded } = (0, import_stega.vercelStegaSplit)(value);
1778
+ if (!encoded) return value;
1779
+ const entryField = ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) ? ctx.entryField : "";
1780
+ const key = `${ctx.entryId}
1781
+ ${entryField}
1782
+ ${ctx.entryOwnerId ?? ""}
1783
+ ${encoded}`;
1784
+ let link = rewritten.get(key);
1785
+ if (link === void 0) {
1786
+ link = rewriteLink(encoded, ctx.entryId, entryField, ctx.entryOwnerId);
1787
+ if (rewritten.size >= MAX_REWRITTEN) rewritten.clear();
1788
+ rewritten.set(key, link);
1789
+ }
1790
+ return link ? cleaned + link : value;
1772
1791
  }
1773
1792
  function walk(value, selections, ctx) {
1774
1793
  if (typeof value === "string") return annotate(value, ctx);
package/dist/nuxt/live.js CHANGED
@@ -15,8 +15,9 @@ import {
15
15
 
16
16
  // src/core/live-preview/edit-links.ts
17
17
  import {
18
- vercelStegaCombine,
18
+ legacyStegaEncode,
19
19
  vercelStegaDecode,
20
+ vercelStegaEncode,
20
21
  vercelStegaSplit
21
22
  } from "@vercel/stega";
22
23
  var ENTRY_PARAM = "entry";
@@ -30,34 +31,53 @@ function entryIdOf(element) {
30
31
  const first = element.items[0];
31
32
  return isObject(first) && typeof first._id === "string" ? first._id : void 0;
32
33
  }
33
- function annotate(value, ctx) {
34
- if (!ctx.entryId) return value;
35
- const { cleaned, encoded } = vercelStegaSplit(value);
36
- if (!encoded) return value;
34
+ function encodeLink(payload) {
35
+ try {
36
+ return legacyStegaEncode(payload);
37
+ } catch {
38
+ return vercelStegaEncode(payload);
39
+ }
40
+ }
41
+ function rewriteLink(encoded, entryId, entryField, entryOwnerId) {
37
42
  let payload;
38
43
  try {
39
44
  payload = vercelStegaDecode(encoded);
40
45
  } catch {
41
- return value;
46
+ return "";
42
47
  }
43
- if (typeof payload?.href !== "string") return value;
48
+ if (typeof payload?.href !== "string") return "";
44
49
  let url;
45
50
  try {
46
51
  url = new URL(payload.href);
47
52
  } catch {
48
- return value;
53
+ return "";
49
54
  }
50
- if (url.searchParams.has(ENTRY_PARAM)) return value;
51
- url.searchParams.set(ENTRY_PARAM, ctx.entryId);
55
+ if (url.searchParams.has(ENTRY_PARAM)) return "";
56
+ url.searchParams.set(ENTRY_PARAM, entryId);
52
57
  const itemId = decodeURIComponent(url.pathname.split("/").pop() ?? "");
53
- if (!url.searchParams.has("field") && ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) && itemId === ctx.entryOwnerId) {
54
- url.searchParams.set("field", ctx.entryField);
58
+ if (!url.searchParams.has("field") && entryField && itemId === entryOwnerId) {
59
+ url.searchParams.set("field", entryField);
55
60
  }
56
- return vercelStegaCombine(
57
- cleaned,
58
- { ...payload, href: url.toString() },
59
- false
60
- );
61
+ return encodeLink({ ...payload, href: url.toString() });
62
+ }
63
+ var MAX_REWRITTEN = 1e4;
64
+ var rewritten = /* @__PURE__ */ new Map();
65
+ function annotate(value, ctx) {
66
+ if (!ctx.entryId) return value;
67
+ const { cleaned, encoded } = vercelStegaSplit(value);
68
+ if (!encoded) return value;
69
+ const entryField = ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) ? ctx.entryField : "";
70
+ const key = `${ctx.entryId}
71
+ ${entryField}
72
+ ${ctx.entryOwnerId ?? ""}
73
+ ${encoded}`;
74
+ let link = rewritten.get(key);
75
+ if (link === void 0) {
76
+ link = rewriteLink(encoded, ctx.entryId, entryField, ctx.entryOwnerId);
77
+ if (rewritten.size >= MAX_REWRITTEN) rewritten.clear();
78
+ rewritten.set(key, link);
79
+ }
80
+ return link ? cleaned + link : value;
61
81
  }
62
82
  function walk(value, selections, ctx) {
63
83
  if (typeof value === "string") return annotate(value, ctx);
@@ -3703,7 +3703,7 @@ function createPreprPreview(opts = {}) {
3703
3703
  }
3704
3704
 
3705
3705
  // src/version.ts
3706
- var VERSION = "1.0.0-rc.4";
3706
+ var VERSION = "1.0.0-rc.5";
3707
3707
 
3708
3708
  // src/core/pixel.ts
3709
3709
  var PIXEL_SCRIPT_URL = "https://cdn.tracking.prepr.io/js/prepr.min.js";
@@ -3679,7 +3679,7 @@ function createPreprPreview(opts = {}) {
3679
3679
  }
3680
3680
 
3681
3681
  // src/version.ts
3682
- var VERSION = "1.0.0-rc.4";
3682
+ var VERSION = "1.0.0-rc.5";
3683
3683
 
3684
3684
  // src/core/pixel.ts
3685
3685
  var PIXEL_SCRIPT_URL = "https://cdn.tracking.prepr.io/js/prepr.min.js";
@@ -35,7 +35,7 @@ __export(sveltekit_exports, {
35
35
  module.exports = __toCommonJS(sveltekit_exports);
36
36
 
37
37
  // src/version.ts
38
- var VERSION = "1.0.0-rc.4";
38
+ var VERSION = "1.0.0-rc.5";
39
39
 
40
40
  // src/core/constants.ts
41
41
  var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";