@preprio/toolkit 1.0.0-rc.4 → 1.0.0-rc.6
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.
- package/README.md +2 -0
- package/dist/astro/index.cjs +126 -18
- package/dist/astro/index.js +128 -19
- package/dist/{chunk-A2J7R4LR.js → chunk-I26P2EQI.js} +1 -1
- package/dist/{chunk-QWTSVPEQ.js → chunk-OCTRCNW2.js} +1 -1
- package/dist/{chunk-KM2GME62.js → chunk-RWFAFYHU.js} +90 -1
- package/dist/{chunk-6PMBN7OR.js → chunk-SAOE54OB.js} +1 -1
- package/dist/{chunk-K62RW46G.js → chunk-WQRPW3TM.js} +1 -1
- package/dist/index.cjs +128 -19
- package/dist/index.d.cts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.js +44 -23
- package/dist/{live-preview-HCBNBC6C.js → live-preview-NUDEDAYQ.js} +2 -2
- package/dist/nextjs/components.cjs +1 -1
- package/dist/nextjs/components.js +2 -2
- package/dist/nextjs/index.cjs +189 -20
- package/dist/nextjs/index.d.cts +47 -1
- package/dist/nextjs/index.d.ts +47 -1
- package/dist/nextjs/index.js +190 -21
- package/dist/nextjs/live-action.js +3 -3
- package/dist/nextjs/live.cjs +102 -6
- package/dist/nextjs/live.d.cts +7 -1
- package/dist/nextjs/live.d.ts +7 -1
- package/dist/nextjs/live.js +8 -6
- package/dist/nuxt/index.cjs +1 -1
- package/dist/nuxt/index.js +1 -1
- package/dist/nuxt/{live-preview-KO4IKWTX.js → live-preview-V2X6GPSK.js} +88 -1
- package/dist/nuxt/live.cjs +130 -17
- package/dist/nuxt/live.js +38 -18
- package/dist/react/components.cjs +1 -1
- package/dist/react/components.js +1 -1
- package/dist/sveltekit/index.cjs +1 -1
- package/dist/sveltekit/index.js +1 -1
- package/dist/sveltekit/{live-preview-KO4IKWTX.js → live-preview-V2X6GPSK.js} +88 -1
- package/dist/sveltekit/live.cjs +130 -17
- package/dist/sveltekit/live.js +38 -18
- package/package.json +1 -1
package/dist/nextjs/index.cjs
CHANGED
|
@@ -40,6 +40,7 @@ __export(nextjs_exports, {
|
|
|
40
40
|
getPreprHeaders: () => getPreprHeaders,
|
|
41
41
|
getPreprUUID: () => getPreprUUID,
|
|
42
42
|
getToolbarProps: () => getToolbarProps,
|
|
43
|
+
livePreviewFetch: () => livePreviewFetch,
|
|
43
44
|
normalizeQuery: () => normalizeQuery,
|
|
44
45
|
validatePreprToken: () => validatePreprToken
|
|
45
46
|
});
|
|
@@ -49,7 +50,7 @@ module.exports = __toCommonJS(nextjs_exports);
|
|
|
49
50
|
var import_server = require("next/server");
|
|
50
51
|
|
|
51
52
|
// src/version.ts
|
|
52
|
-
var VERSION = "1.0.0-rc.
|
|
53
|
+
var VERSION = "1.0.0-rc.6";
|
|
53
54
|
|
|
54
55
|
// src/core/constants.ts
|
|
55
56
|
var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
|
|
@@ -476,6 +477,94 @@ function indexSnapshot(data) {
|
|
|
476
477
|
|
|
477
478
|
// src/core/live-preview/patch.ts
|
|
478
479
|
var import_stega2 = require("@vercel/stega");
|
|
480
|
+
|
|
481
|
+
// src/core/live-preview/internal-links.ts
|
|
482
|
+
var INTERNAL_HREF = /^[pa]uuid#/;
|
|
483
|
+
var ANCHOR = /<a\b([^>]*)>([\s\S]*?)<\/a>/gi;
|
|
484
|
+
var HREF = /(\shref\s*=\s*)(["'])(.*?)\2/i;
|
|
485
|
+
var TAGS = /<[^>]+>/g;
|
|
486
|
+
function anchorsIn(html) {
|
|
487
|
+
const out = [];
|
|
488
|
+
for (const match of html.matchAll(ANCHOR)) {
|
|
489
|
+
const attributes = match[1];
|
|
490
|
+
const inner = match[2];
|
|
491
|
+
out.push({
|
|
492
|
+
start: match.index ?? 0,
|
|
493
|
+
end: (match.index ?? 0) + match[0].length,
|
|
494
|
+
attributes,
|
|
495
|
+
inner,
|
|
496
|
+
href: HREF.exec(attributes)?.[3] ?? null,
|
|
497
|
+
text: inner.replace(TAGS, "").trim()
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
return out;
|
|
501
|
+
}
|
|
502
|
+
var isInternal = (anchor) => anchor.href !== null && INTERNAL_HREF.test(anchor.href);
|
|
503
|
+
function fit(pushed, page) {
|
|
504
|
+
if (!isInternal(pushed) && pushed.href !== page.href) return 0;
|
|
505
|
+
if (isInternal(pushed) && page.href !== null && INTERNAL_HREF.test(page.href))
|
|
506
|
+
return 0;
|
|
507
|
+
return pushed.text === page.text ? 2 : 1;
|
|
508
|
+
}
|
|
509
|
+
function align(pushed, page) {
|
|
510
|
+
const rows = pushed.length + 1;
|
|
511
|
+
const cols = page.length + 1;
|
|
512
|
+
const score = Array.from(
|
|
513
|
+
{ length: rows },
|
|
514
|
+
() => new Array(cols).fill(0)
|
|
515
|
+
);
|
|
516
|
+
for (let i2 = pushed.length - 1; i2 >= 0; i2--) {
|
|
517
|
+
for (let j2 = page.length - 1; j2 >= 0; j2--) {
|
|
518
|
+
const pair = fit(pushed[i2], page[j2]);
|
|
519
|
+
score[i2][j2] = Math.max(
|
|
520
|
+
score[i2 + 1][j2],
|
|
521
|
+
score[i2][j2 + 1],
|
|
522
|
+
pair ? pair + score[i2 + 1][j2 + 1] : 0
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
const out = new Array(pushed.length).fill(-1);
|
|
527
|
+
let i = 0;
|
|
528
|
+
let j = 0;
|
|
529
|
+
while (i < pushed.length && j < page.length) {
|
|
530
|
+
const pair = fit(pushed[i], page[j]);
|
|
531
|
+
if (pair && score[i][j] === pair + score[i + 1][j + 1]) {
|
|
532
|
+
out[i++] = j++;
|
|
533
|
+
} else if (score[i + 1][j] >= score[i][j + 1]) {
|
|
534
|
+
i++;
|
|
535
|
+
} else {
|
|
536
|
+
j++;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
return out;
|
|
540
|
+
}
|
|
541
|
+
function resolveInternalLinks(current, value) {
|
|
542
|
+
const pushed = anchorsIn(value);
|
|
543
|
+
if (!pushed.some(isInternal)) return value;
|
|
544
|
+
const page = typeof current === "string" ? anchorsIn(current) : [];
|
|
545
|
+
const pairs = align(pushed, page);
|
|
546
|
+
let out = "";
|
|
547
|
+
let cursor = 0;
|
|
548
|
+
pushed.forEach((anchor, i) => {
|
|
549
|
+
if (!isInternal(anchor)) return;
|
|
550
|
+
out += value.slice(cursor, anchor.start);
|
|
551
|
+
const match = pairs[i] >= 0 ? page[pairs[i]] : null;
|
|
552
|
+
if (match?.href != null) {
|
|
553
|
+
const href = match.href;
|
|
554
|
+
const attributes = anchor.attributes.replace(
|
|
555
|
+
HREF,
|
|
556
|
+
(_all, lead, quote) => `${lead}${quote}${href}${quote}`
|
|
557
|
+
);
|
|
558
|
+
out += `<a${attributes}>${anchor.inner}</a>`;
|
|
559
|
+
} else {
|
|
560
|
+
out += anchor.inner;
|
|
561
|
+
}
|
|
562
|
+
cursor = anchor.end;
|
|
563
|
+
});
|
|
564
|
+
return out + value.slice(cursor);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// src/core/live-preview/patch.ts
|
|
479
568
|
var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
480
569
|
function mergeObject(current, incoming) {
|
|
481
570
|
let changed = false;
|
|
@@ -573,7 +662,8 @@ function writeAtPath(root, fullPath, value, markChanged = () => {
|
|
|
573
662
|
} else if (!isPatchable(container[key])) {
|
|
574
663
|
return root;
|
|
575
664
|
} else {
|
|
576
|
-
|
|
665
|
+
const linked = typeof value === "string" ? resolveInternalLinks(container[key], value) : value;
|
|
666
|
+
next = keepEditLink(container[key], linked);
|
|
577
667
|
}
|
|
578
668
|
if (container[key] === next) return root;
|
|
579
669
|
const newRoot = cloneNode(root);
|
|
@@ -1356,34 +1446,53 @@ function entryIdOf(element) {
|
|
|
1356
1446
|
const first = element.items[0];
|
|
1357
1447
|
return isObject(first) && typeof first._id === "string" ? first._id : void 0;
|
|
1358
1448
|
}
|
|
1359
|
-
function
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1449
|
+
function encodeLink(payload) {
|
|
1450
|
+
try {
|
|
1451
|
+
return (0, import_stega4.legacyStegaEncode)(payload);
|
|
1452
|
+
} catch {
|
|
1453
|
+
return (0, import_stega4.vercelStegaEncode)(payload);
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
function rewriteLink(encoded, entryId, entryField, entryOwnerId) {
|
|
1363
1457
|
let payload;
|
|
1364
1458
|
try {
|
|
1365
1459
|
payload = (0, import_stega4.vercelStegaDecode)(encoded);
|
|
1366
1460
|
} catch {
|
|
1367
|
-
return
|
|
1461
|
+
return "";
|
|
1368
1462
|
}
|
|
1369
|
-
if (typeof payload?.href !== "string") return
|
|
1463
|
+
if (typeof payload?.href !== "string") return "";
|
|
1370
1464
|
let url;
|
|
1371
1465
|
try {
|
|
1372
1466
|
url = new URL(payload.href);
|
|
1373
1467
|
} catch {
|
|
1374
|
-
return
|
|
1468
|
+
return "";
|
|
1375
1469
|
}
|
|
1376
|
-
if (url.searchParams.has(ENTRY_PARAM)) return
|
|
1377
|
-
url.searchParams.set(ENTRY_PARAM,
|
|
1470
|
+
if (url.searchParams.has(ENTRY_PARAM)) return "";
|
|
1471
|
+
url.searchParams.set(ENTRY_PARAM, entryId);
|
|
1378
1472
|
const itemId = decodeURIComponent(url.pathname.split("/").pop() ?? "");
|
|
1379
|
-
if (!url.searchParams.has("field") &&
|
|
1380
|
-
url.searchParams.set("field",
|
|
1473
|
+
if (!url.searchParams.has("field") && entryField && itemId === entryOwnerId) {
|
|
1474
|
+
url.searchParams.set("field", entryField);
|
|
1381
1475
|
}
|
|
1382
|
-
return (
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1476
|
+
return encodeLink({ ...payload, href: url.toString() });
|
|
1477
|
+
}
|
|
1478
|
+
var MAX_REWRITTEN = 1e4;
|
|
1479
|
+
var rewritten = /* @__PURE__ */ new Map();
|
|
1480
|
+
function annotate(value, ctx) {
|
|
1481
|
+
if (!ctx.entryId) return value;
|
|
1482
|
+
const { cleaned, encoded } = (0, import_stega4.vercelStegaSplit)(value);
|
|
1483
|
+
if (!encoded) return value;
|
|
1484
|
+
const entryField = ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) ? ctx.entryField : "";
|
|
1485
|
+
const key = `${ctx.entryId}
|
|
1486
|
+
${entryField}
|
|
1487
|
+
${ctx.entryOwnerId ?? ""}
|
|
1488
|
+
${encoded}`;
|
|
1489
|
+
let link = rewritten.get(key);
|
|
1490
|
+
if (link === void 0) {
|
|
1491
|
+
link = rewriteLink(encoded, ctx.entryId, entryField, ctx.entryOwnerId);
|
|
1492
|
+
if (rewritten.size >= MAX_REWRITTEN) rewritten.clear();
|
|
1493
|
+
rewritten.set(key, link);
|
|
1494
|
+
}
|
|
1495
|
+
return link ? cleaned + link : value;
|
|
1387
1496
|
}
|
|
1388
1497
|
function walk(value, selections, ctx) {
|
|
1389
1498
|
if (typeof value === "string") return annotate(value, ctx);
|
|
@@ -1464,11 +1573,17 @@ function takeLiveLog(token) {
|
|
|
1464
1573
|
if (!token || !TOKEN_PATTERN.test(token)) return [];
|
|
1465
1574
|
const map = slots();
|
|
1466
1575
|
const slot = map.get(token);
|
|
1467
|
-
map.delete(token);
|
|
1468
1576
|
const now = Date.now();
|
|
1469
1577
|
prune(map, now);
|
|
1470
1578
|
if (!slot || slot.expires <= now) return [];
|
|
1471
|
-
|
|
1579
|
+
const { log } = slot;
|
|
1580
|
+
slot.log = [];
|
|
1581
|
+
return log;
|
|
1582
|
+
}
|
|
1583
|
+
function hasLiveLog(token) {
|
|
1584
|
+
if (!token || !TOKEN_PATTERN.test(token)) return false;
|
|
1585
|
+
const slot = slots().get(token);
|
|
1586
|
+
return slot !== void 0 && slot.expires > Date.now();
|
|
1472
1587
|
}
|
|
1473
1588
|
|
|
1474
1589
|
// src/core/server.ts
|
|
@@ -1680,6 +1795,59 @@ async function normalizeQuery(query, result, options = {}) {
|
|
|
1680
1795
|
if (!log.length) return annotated;
|
|
1681
1796
|
return applyPatchLog(query, annotated, log, options.operationName);
|
|
1682
1797
|
}
|
|
1798
|
+
var MAX_STORED_RESPONSES = 30;
|
|
1799
|
+
var STORED_RESPONSE_TTL_MS = 5 * 6e4;
|
|
1800
|
+
var storedResponses = /* @__PURE__ */ new Map();
|
|
1801
|
+
var documentIds = /* @__PURE__ */ new WeakMap();
|
|
1802
|
+
var nextDocumentId = 0;
|
|
1803
|
+
function queryKey(query) {
|
|
1804
|
+
if (typeof query === "string") return query;
|
|
1805
|
+
let id = documentIds.get(query);
|
|
1806
|
+
if (id === void 0) documentIds.set(query, id = nextDocumentId++);
|
|
1807
|
+
return `#${id}`;
|
|
1808
|
+
}
|
|
1809
|
+
function responseKey(key, preprHeaders) {
|
|
1810
|
+
try {
|
|
1811
|
+
return JSON.stringify([
|
|
1812
|
+
queryKey(key.query),
|
|
1813
|
+
key.variables ?? null,
|
|
1814
|
+
// Segment, A/B variant and visitor decide what Prepr returns.
|
|
1815
|
+
Object.entries(preprHeaders).sort(([a], [b]) => a < b ? -1 : 1)
|
|
1816
|
+
]);
|
|
1817
|
+
} catch {
|
|
1818
|
+
return null;
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
async function livePreviewFetch(key, fetcher, options = {}) {
|
|
1822
|
+
if (!options.enabled) return fetcher();
|
|
1823
|
+
let unsaved;
|
|
1824
|
+
let preprHeaders;
|
|
1825
|
+
try {
|
|
1826
|
+
const h = await readHeaders();
|
|
1827
|
+
preprHeaders = getPreprHeadersFromHeaders(h);
|
|
1828
|
+
unsaved = h.has(HEADER_NEXT_ACTION) && hasLiveLog((await (0, import_headers.cookies)()).get(LIVE_LOG_COOKIE)?.value);
|
|
1829
|
+
} catch (error) {
|
|
1830
|
+
navigation.unstable_rethrow?.(error);
|
|
1831
|
+
return fetcher();
|
|
1832
|
+
}
|
|
1833
|
+
const id = responseKey(key, preprHeaders);
|
|
1834
|
+
if (id === null) return fetcher();
|
|
1835
|
+
const now = Date.now();
|
|
1836
|
+
if (unsaved) {
|
|
1837
|
+
const stored = storedResponses.get(id);
|
|
1838
|
+
if (stored && stored.expires > now) return stored.value;
|
|
1839
|
+
}
|
|
1840
|
+
const value = await fetcher();
|
|
1841
|
+
storedResponses.delete(id);
|
|
1842
|
+
for (const [other, stored] of storedResponses) {
|
|
1843
|
+
if (stored.expires > now && storedResponses.size < MAX_STORED_RESPONSES) {
|
|
1844
|
+
break;
|
|
1845
|
+
}
|
|
1846
|
+
storedResponses.delete(other);
|
|
1847
|
+
}
|
|
1848
|
+
storedResponses.set(id, { value, expires: now + STORED_RESPONSE_TTL_MS });
|
|
1849
|
+
return value;
|
|
1850
|
+
}
|
|
1683
1851
|
|
|
1684
1852
|
// src/nextjs/index.ts
|
|
1685
1853
|
var import_components = require("./components.cjs");
|
|
@@ -1695,6 +1863,7 @@ var import_components = require("./components.cjs");
|
|
|
1695
1863
|
getPreprHeaders,
|
|
1696
1864
|
getPreprUUID,
|
|
1697
1865
|
getToolbarProps,
|
|
1866
|
+
livePreviewFetch,
|
|
1698
1867
|
normalizeQuery,
|
|
1699
1868
|
validatePreprToken
|
|
1700
1869
|
});
|
package/dist/nextjs/index.d.cts
CHANGED
|
@@ -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 };
|
package/dist/nextjs/index.d.ts
CHANGED
|
@@ -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 };
|
package/dist/nextjs/index.js
CHANGED
|
@@ -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.
|
|
5
|
+
var VERSION = "1.0.0-rc.6";
|
|
6
6
|
|
|
7
7
|
// src/core/constants.ts
|
|
8
8
|
var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
|
|
@@ -433,6 +433,94 @@ function indexSnapshot(data) {
|
|
|
433
433
|
|
|
434
434
|
// src/core/live-preview/patch.ts
|
|
435
435
|
import { vercelStegaSplit as vercelStegaSplit2 } from "@vercel/stega";
|
|
436
|
+
|
|
437
|
+
// src/core/live-preview/internal-links.ts
|
|
438
|
+
var INTERNAL_HREF = /^[pa]uuid#/;
|
|
439
|
+
var ANCHOR = /<a\b([^>]*)>([\s\S]*?)<\/a>/gi;
|
|
440
|
+
var HREF = /(\shref\s*=\s*)(["'])(.*?)\2/i;
|
|
441
|
+
var TAGS = /<[^>]+>/g;
|
|
442
|
+
function anchorsIn(html) {
|
|
443
|
+
const out = [];
|
|
444
|
+
for (const match of html.matchAll(ANCHOR)) {
|
|
445
|
+
const attributes = match[1];
|
|
446
|
+
const inner = match[2];
|
|
447
|
+
out.push({
|
|
448
|
+
start: match.index ?? 0,
|
|
449
|
+
end: (match.index ?? 0) + match[0].length,
|
|
450
|
+
attributes,
|
|
451
|
+
inner,
|
|
452
|
+
href: HREF.exec(attributes)?.[3] ?? null,
|
|
453
|
+
text: inner.replace(TAGS, "").trim()
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
return out;
|
|
457
|
+
}
|
|
458
|
+
var isInternal = (anchor) => anchor.href !== null && INTERNAL_HREF.test(anchor.href);
|
|
459
|
+
function fit(pushed, page) {
|
|
460
|
+
if (!isInternal(pushed) && pushed.href !== page.href) return 0;
|
|
461
|
+
if (isInternal(pushed) && page.href !== null && INTERNAL_HREF.test(page.href))
|
|
462
|
+
return 0;
|
|
463
|
+
return pushed.text === page.text ? 2 : 1;
|
|
464
|
+
}
|
|
465
|
+
function align(pushed, page) {
|
|
466
|
+
const rows = pushed.length + 1;
|
|
467
|
+
const cols = page.length + 1;
|
|
468
|
+
const score = Array.from(
|
|
469
|
+
{ length: rows },
|
|
470
|
+
() => new Array(cols).fill(0)
|
|
471
|
+
);
|
|
472
|
+
for (let i2 = pushed.length - 1; i2 >= 0; i2--) {
|
|
473
|
+
for (let j2 = page.length - 1; j2 >= 0; j2--) {
|
|
474
|
+
const pair = fit(pushed[i2], page[j2]);
|
|
475
|
+
score[i2][j2] = Math.max(
|
|
476
|
+
score[i2 + 1][j2],
|
|
477
|
+
score[i2][j2 + 1],
|
|
478
|
+
pair ? pair + score[i2 + 1][j2 + 1] : 0
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const out = new Array(pushed.length).fill(-1);
|
|
483
|
+
let i = 0;
|
|
484
|
+
let j = 0;
|
|
485
|
+
while (i < pushed.length && j < page.length) {
|
|
486
|
+
const pair = fit(pushed[i], page[j]);
|
|
487
|
+
if (pair && score[i][j] === pair + score[i + 1][j + 1]) {
|
|
488
|
+
out[i++] = j++;
|
|
489
|
+
} else if (score[i + 1][j] >= score[i][j + 1]) {
|
|
490
|
+
i++;
|
|
491
|
+
} else {
|
|
492
|
+
j++;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
return out;
|
|
496
|
+
}
|
|
497
|
+
function resolveInternalLinks(current, value) {
|
|
498
|
+
const pushed = anchorsIn(value);
|
|
499
|
+
if (!pushed.some(isInternal)) return value;
|
|
500
|
+
const page = typeof current === "string" ? anchorsIn(current) : [];
|
|
501
|
+
const pairs = align(pushed, page);
|
|
502
|
+
let out = "";
|
|
503
|
+
let cursor = 0;
|
|
504
|
+
pushed.forEach((anchor, i) => {
|
|
505
|
+
if (!isInternal(anchor)) return;
|
|
506
|
+
out += value.slice(cursor, anchor.start);
|
|
507
|
+
const match = pairs[i] >= 0 ? page[pairs[i]] : null;
|
|
508
|
+
if (match?.href != null) {
|
|
509
|
+
const href = match.href;
|
|
510
|
+
const attributes = anchor.attributes.replace(
|
|
511
|
+
HREF,
|
|
512
|
+
(_all, lead, quote) => `${lead}${quote}${href}${quote}`
|
|
513
|
+
);
|
|
514
|
+
out += `<a${attributes}>${anchor.inner}</a>`;
|
|
515
|
+
} else {
|
|
516
|
+
out += anchor.inner;
|
|
517
|
+
}
|
|
518
|
+
cursor = anchor.end;
|
|
519
|
+
});
|
|
520
|
+
return out + value.slice(cursor);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// src/core/live-preview/patch.ts
|
|
436
524
|
var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
437
525
|
function mergeObject(current, incoming) {
|
|
438
526
|
let changed = false;
|
|
@@ -530,7 +618,8 @@ function writeAtPath(root, fullPath, value, markChanged = () => {
|
|
|
530
618
|
} else if (!isPatchable(container[key])) {
|
|
531
619
|
return root;
|
|
532
620
|
} else {
|
|
533
|
-
|
|
621
|
+
const linked = typeof value === "string" ? resolveInternalLinks(container[key], value) : value;
|
|
622
|
+
next = keepEditLink(container[key], linked);
|
|
534
623
|
}
|
|
535
624
|
if (container[key] === next) return root;
|
|
536
625
|
const newRoot = cloneNode(root);
|
|
@@ -1302,8 +1391,9 @@ function listKeysIn(result) {
|
|
|
1302
1391
|
|
|
1303
1392
|
// src/core/live-preview/edit-links.ts
|
|
1304
1393
|
import {
|
|
1305
|
-
|
|
1394
|
+
legacyStegaEncode,
|
|
1306
1395
|
vercelStegaDecode as vercelStegaDecode2,
|
|
1396
|
+
vercelStegaEncode,
|
|
1307
1397
|
vercelStegaSplit as vercelStegaSplit4
|
|
1308
1398
|
} from "@vercel/stega";
|
|
1309
1399
|
var ENTRY_PARAM = "entry";
|
|
@@ -1317,34 +1407,53 @@ function entryIdOf(element) {
|
|
|
1317
1407
|
const first = element.items[0];
|
|
1318
1408
|
return isObject(first) && typeof first._id === "string" ? first._id : void 0;
|
|
1319
1409
|
}
|
|
1320
|
-
function
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1410
|
+
function encodeLink(payload) {
|
|
1411
|
+
try {
|
|
1412
|
+
return legacyStegaEncode(payload);
|
|
1413
|
+
} catch {
|
|
1414
|
+
return vercelStegaEncode(payload);
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
function rewriteLink(encoded, entryId, entryField, entryOwnerId) {
|
|
1324
1418
|
let payload;
|
|
1325
1419
|
try {
|
|
1326
1420
|
payload = vercelStegaDecode2(encoded);
|
|
1327
1421
|
} catch {
|
|
1328
|
-
return
|
|
1422
|
+
return "";
|
|
1329
1423
|
}
|
|
1330
|
-
if (typeof payload?.href !== "string") return
|
|
1424
|
+
if (typeof payload?.href !== "string") return "";
|
|
1331
1425
|
let url;
|
|
1332
1426
|
try {
|
|
1333
1427
|
url = new URL(payload.href);
|
|
1334
1428
|
} catch {
|
|
1335
|
-
return
|
|
1429
|
+
return "";
|
|
1336
1430
|
}
|
|
1337
|
-
if (url.searchParams.has(ENTRY_PARAM)) return
|
|
1338
|
-
url.searchParams.set(ENTRY_PARAM,
|
|
1431
|
+
if (url.searchParams.has(ENTRY_PARAM)) return "";
|
|
1432
|
+
url.searchParams.set(ENTRY_PARAM, entryId);
|
|
1339
1433
|
const itemId = decodeURIComponent(url.pathname.split("/").pop() ?? "");
|
|
1340
|
-
if (!url.searchParams.has("field") &&
|
|
1341
|
-
url.searchParams.set("field",
|
|
1434
|
+
if (!url.searchParams.has("field") && entryField && itemId === entryOwnerId) {
|
|
1435
|
+
url.searchParams.set("field", entryField);
|
|
1342
1436
|
}
|
|
1343
|
-
return
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1437
|
+
return encodeLink({ ...payload, href: url.toString() });
|
|
1438
|
+
}
|
|
1439
|
+
var MAX_REWRITTEN = 1e4;
|
|
1440
|
+
var rewritten = /* @__PURE__ */ new Map();
|
|
1441
|
+
function annotate(value, ctx) {
|
|
1442
|
+
if (!ctx.entryId) return value;
|
|
1443
|
+
const { cleaned, encoded } = vercelStegaSplit4(value);
|
|
1444
|
+
if (!encoded) return value;
|
|
1445
|
+
const entryField = ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) ? ctx.entryField : "";
|
|
1446
|
+
const key = `${ctx.entryId}
|
|
1447
|
+
${entryField}
|
|
1448
|
+
${ctx.entryOwnerId ?? ""}
|
|
1449
|
+
${encoded}`;
|
|
1450
|
+
let link = rewritten.get(key);
|
|
1451
|
+
if (link === void 0) {
|
|
1452
|
+
link = rewriteLink(encoded, ctx.entryId, entryField, ctx.entryOwnerId);
|
|
1453
|
+
if (rewritten.size >= MAX_REWRITTEN) rewritten.clear();
|
|
1454
|
+
rewritten.set(key, link);
|
|
1455
|
+
}
|
|
1456
|
+
return link ? cleaned + link : value;
|
|
1348
1457
|
}
|
|
1349
1458
|
function walk(value, selections, ctx) {
|
|
1350
1459
|
if (typeof value === "string") return annotate(value, ctx);
|
|
@@ -1425,11 +1534,17 @@ function takeLiveLog(token) {
|
|
|
1425
1534
|
if (!token || !TOKEN_PATTERN.test(token)) return [];
|
|
1426
1535
|
const map = slots();
|
|
1427
1536
|
const slot = map.get(token);
|
|
1428
|
-
map.delete(token);
|
|
1429
1537
|
const now = Date.now();
|
|
1430
1538
|
prune(map, now);
|
|
1431
1539
|
if (!slot || slot.expires <= now) return [];
|
|
1432
|
-
|
|
1540
|
+
const { log } = slot;
|
|
1541
|
+
slot.log = [];
|
|
1542
|
+
return log;
|
|
1543
|
+
}
|
|
1544
|
+
function hasLiveLog(token) {
|
|
1545
|
+
if (!token || !TOKEN_PATTERN.test(token)) return false;
|
|
1546
|
+
const slot = slots().get(token);
|
|
1547
|
+
return slot !== void 0 && slot.expires > Date.now();
|
|
1433
1548
|
}
|
|
1434
1549
|
|
|
1435
1550
|
// src/core/server.ts
|
|
@@ -1641,6 +1756,59 @@ async function normalizeQuery(query, result, options = {}) {
|
|
|
1641
1756
|
if (!log.length) return annotated;
|
|
1642
1757
|
return applyPatchLog(query, annotated, log, options.operationName);
|
|
1643
1758
|
}
|
|
1759
|
+
var MAX_STORED_RESPONSES = 30;
|
|
1760
|
+
var STORED_RESPONSE_TTL_MS = 5 * 6e4;
|
|
1761
|
+
var storedResponses = /* @__PURE__ */ new Map();
|
|
1762
|
+
var documentIds = /* @__PURE__ */ new WeakMap();
|
|
1763
|
+
var nextDocumentId = 0;
|
|
1764
|
+
function queryKey(query) {
|
|
1765
|
+
if (typeof query === "string") return query;
|
|
1766
|
+
let id = documentIds.get(query);
|
|
1767
|
+
if (id === void 0) documentIds.set(query, id = nextDocumentId++);
|
|
1768
|
+
return `#${id}`;
|
|
1769
|
+
}
|
|
1770
|
+
function responseKey(key, preprHeaders) {
|
|
1771
|
+
try {
|
|
1772
|
+
return JSON.stringify([
|
|
1773
|
+
queryKey(key.query),
|
|
1774
|
+
key.variables ?? null,
|
|
1775
|
+
// Segment, A/B variant and visitor decide what Prepr returns.
|
|
1776
|
+
Object.entries(preprHeaders).sort(([a], [b]) => a < b ? -1 : 1)
|
|
1777
|
+
]);
|
|
1778
|
+
} catch {
|
|
1779
|
+
return null;
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
async function livePreviewFetch(key, fetcher, options = {}) {
|
|
1783
|
+
if (!options.enabled) return fetcher();
|
|
1784
|
+
let unsaved;
|
|
1785
|
+
let preprHeaders;
|
|
1786
|
+
try {
|
|
1787
|
+
const h = await readHeaders();
|
|
1788
|
+
preprHeaders = getPreprHeadersFromHeaders(h);
|
|
1789
|
+
unsaved = h.has(HEADER_NEXT_ACTION) && hasLiveLog((await cookies()).get(LIVE_LOG_COOKIE)?.value);
|
|
1790
|
+
} catch (error) {
|
|
1791
|
+
navigation.unstable_rethrow?.(error);
|
|
1792
|
+
return fetcher();
|
|
1793
|
+
}
|
|
1794
|
+
const id = responseKey(key, preprHeaders);
|
|
1795
|
+
if (id === null) return fetcher();
|
|
1796
|
+
const now = Date.now();
|
|
1797
|
+
if (unsaved) {
|
|
1798
|
+
const stored = storedResponses.get(id);
|
|
1799
|
+
if (stored && stored.expires > now) return stored.value;
|
|
1800
|
+
}
|
|
1801
|
+
const value = await fetcher();
|
|
1802
|
+
storedResponses.delete(id);
|
|
1803
|
+
for (const [other, stored] of storedResponses) {
|
|
1804
|
+
if (stored.expires > now && storedResponses.size < MAX_STORED_RESPONSES) {
|
|
1805
|
+
break;
|
|
1806
|
+
}
|
|
1807
|
+
storedResponses.delete(other);
|
|
1808
|
+
}
|
|
1809
|
+
storedResponses.set(id, { value, expires: now + STORED_RESPONSE_TTL_MS });
|
|
1810
|
+
return value;
|
|
1811
|
+
}
|
|
1644
1812
|
|
|
1645
1813
|
// src/nextjs/index.ts
|
|
1646
1814
|
import {
|
|
@@ -1658,6 +1826,7 @@ export {
|
|
|
1658
1826
|
getPreprHeaders,
|
|
1659
1827
|
getPreprUUID,
|
|
1660
1828
|
getToolbarProps,
|
|
1829
|
+
livePreviewFetch,
|
|
1661
1830
|
normalizeQuery,
|
|
1662
1831
|
validatePreprToken
|
|
1663
1832
|
};
|