@akinon/next 2.0.78 → 2.0.79-beta.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @akinon/next
2
2
 
3
+ ## 2.0.79-beta.1
4
+
5
+ ### Patch Changes
6
+
7
+ - cbbbfd757: ZERO-4376: Bootstrap beta cycle (next-main pre-release motor)
8
+
9
+ ## 2.0.79-beta.0
10
+
11
+ ### Patch Changes
12
+
13
+ - cbbbfd757: ZERO-4376: Bootstrap beta cycle (next-main pre-release motor)
14
+
3
15
  ## 2.0.78
4
16
 
5
17
  ## 2.0.77
@@ -1,16 +1,192 @@
1
1
  import { Cache, CacheKey } from '../../lib/cache';
2
2
  import 'server-only';
3
+ import { draftMode } from 'next/headers';
3
4
  import { CacheOptions, WidgetResultType, WidgetSchemaType } from '../../types';
4
5
  import appFetch from '../../utils/app-fetch';
5
6
  import { widgets } from '../urls';
6
7
  import { ServerVariables } from '../../utils/server-variables';
8
+ import {
9
+ isPreviewCopySlug,
10
+ isValidPreviewId,
11
+ previewSlug
12
+ } from '../../utils/preview';
13
+
14
+ /**
15
+ * Widget preview (draft mode): the theme editor keeps any number of NAMED
16
+ * previews, each storing its pages under `<slug>-preview-<previewId>`. With
17
+ * draft mode on (entered via /api/preview, toggled by `?preview` on any page
18
+ * url) and a preview id on the request, every widget fetch first tries that
19
+ * preview's copy and falls back to the live slug when none exists — a
20
+ * preview renders as "live + that preview's overlay". Preview fetches bypass
21
+ * Redis and the fetch data cache so the editor's latest save is visible.
22
+ *
23
+ * BOTH signals are required: draft mode alone renders live (no id ⇒ no
24
+ * preview slug to try), and an id alone does nothing without draft mode.
25
+ */
26
+ const PREVIEW_SNAPSHOT_ATTRIBUTE = 'preview_snapshot';
27
+
28
+ const PREVIEW_NO_STORE = { revalidate: 0 };
29
+
30
+ // The snapshot blob owns theme settings/data sources in preview, so the
31
+ // theme-config widget itself is never slug-transformed; a slug that is
32
+ // already this preview's copy is never transformed twice. Checked against
33
+ // the CURRENT id, not a shape — a live slug may legitimately end in
34
+ // `-preview-<something>` (a custom page named `summer-preview-2026`).
35
+ const isPreviewTransformableSlug = (slug: string, previewId: string): boolean =>
36
+ slug !== 'theme-config' && !isPreviewCopySlug(slug, previewId);
37
+
38
+ /**
39
+ * The editor's directory of previews that exist (`theme-previews` widget,
40
+ * `theme_previews` attribute). Deleting a preview removes it here first and
41
+ * clears only the pages the editor had loaded — so this is what makes a
42
+ * deleted preview stop rendering, even for a browser that still carries its
43
+ * cookie. Read uncached, remembered briefly across requests: a deleted
44
+ * preview may linger for at most REGISTRY_TTL_MS. An unreadable registry
45
+ * fails OPEN (behaves as before the check existed) rather than blanking
46
+ * every preview on a transient backend error.
47
+ */
48
+ const PREVIEW_REGISTRY_SLUG = 'theme-previews';
49
+ const PREVIEW_REGISTRY_ATTRIBUTE = 'theme_previews';
50
+ const REGISTRY_TTL_MS = 5_000;
51
+
52
+ let registryMemo: { ids: Set<string> | null; expires: number } = {
53
+ ids: null,
54
+ expires: 0
55
+ };
56
+
57
+ const unwrapAttribute = (raw: unknown): unknown =>
58
+ typeof raw === 'object' && raw !== null && 'value' in raw
59
+ ? (raw as { value?: unknown }).value
60
+ : raw;
61
+
62
+ const registryKnowsPreview = async (
63
+ previewId: string,
64
+ locale: string,
65
+ currency: string
66
+ ): Promise<boolean> => {
67
+ const now = Date.now();
68
+ if (registryMemo.expires <= now) {
69
+ let ids: Set<string> | null = null;
70
+ try {
71
+ const widget = await getWidgetDataHandler(
72
+ PREVIEW_REGISTRY_SLUG,
73
+ locale,
74
+ currency,
75
+ undefined,
76
+ PREVIEW_NO_STORE
77
+ )();
78
+ const raw = unwrapAttribute(
79
+ (widget as { attributes?: Record<string, unknown> } | null)
80
+ ?.attributes?.[PREVIEW_REGISTRY_ATTRIBUTE]
81
+ );
82
+ if (typeof raw === 'string' && raw) {
83
+ const parsed = JSON.parse(raw);
84
+ if (Array.isArray(parsed?.previews)) {
85
+ ids = new Set(
86
+ (parsed.previews as Array<{ id?: unknown }>)
87
+ .map((entry) => entry?.id)
88
+ .filter((id): id is string => typeof id === 'string')
89
+ );
90
+ }
91
+ }
92
+ } catch {
93
+ ids = null;
94
+ }
95
+ registryMemo = { ids, expires: now + REGISTRY_TTL_MS };
96
+ }
97
+ return registryMemo.ids ? registryMemo.ids.has(previewId) : true;
98
+ };
99
+
100
+ /**
101
+ * The named preview this render belongs to, or '' when the request is not a
102
+ * preview at all. The id is decoded from the pz route segment (see
103
+ * utils/preview.ts) and re-validated here — it originates from a cookie.
104
+ */
105
+ const previewIdForRequest = async (
106
+ locale: string = ServerVariables.locale,
107
+ currency: string = ServerVariables.currency
108
+ ): Promise<string> => {
109
+ try {
110
+ if (!(await draftMode()).isEnabled) return '';
111
+ } catch {
112
+ // No request scope (e.g. build-time prerender) — never a preview.
113
+ return '';
114
+ }
115
+ const previewId = ServerVariables.previewId;
116
+ if (!isValidPreviewId(previewId)) return '';
117
+ return (await registryKnowsPreview(previewId, locale, currency))
118
+ ? previewId
119
+ : '';
120
+ };
121
+
122
+ /**
123
+ * Whole-placeholder preview snapshot written by the theme editor into the
124
+ * `preview_snapshot` attribute of `<placeholderSlug>-preview-<previewId>`.
125
+ * When present (draft mode only), the placeholder renders straight from this
126
+ * blob — no per-section fetches.
127
+ */
128
+ export type PreviewSnapshot = {
129
+ version: number;
130
+ savedAt?: string;
131
+ themeSettings?: Record<string, unknown> | null;
132
+ dataSources?: unknown[];
133
+ sections: unknown[];
134
+ };
135
+
136
+ export const getPreviewSnapshot = async ({
137
+ slug,
138
+ locale = ServerVariables.locale,
139
+ currency = ServerVariables.currency
140
+ }: {
141
+ slug: string;
142
+ locale?: string;
143
+ currency?: string;
144
+ }): Promise<PreviewSnapshot | null> => {
145
+ const previewId = slug ? await previewIdForRequest(locale, currency) : '';
146
+ if (!previewId) {
147
+ return null;
148
+ }
149
+
150
+ const widget = await getWidgetDataHandler(
151
+ previewSlug(slug, previewId),
152
+ locale,
153
+ currency,
154
+ undefined,
155
+ PREVIEW_NO_STORE
156
+ )();
157
+
158
+ const rawAttribute = (
159
+ widget as { attributes?: Record<string, unknown> } | null
160
+ )?.attributes?.[PREVIEW_SNAPSHOT_ATTRIBUTE];
161
+ const rawValue =
162
+ typeof rawAttribute === 'object' &&
163
+ rawAttribute !== null &&
164
+ 'value' in rawAttribute
165
+ ? (rawAttribute as { value?: unknown }).value
166
+ : rawAttribute;
167
+
168
+ if (typeof rawValue !== 'string' || !rawValue) {
169
+ return null;
170
+ }
171
+
172
+ try {
173
+ const parsed = JSON.parse(rawValue);
174
+ if (parsed?.version === 1 && Array.isArray(parsed.sections)) {
175
+ return parsed as PreviewSnapshot;
176
+ }
177
+ } catch {
178
+ // Malformed snapshot — fall back to the live render path.
179
+ }
180
+ return null;
181
+ };
7
182
 
8
183
  const getWidgetDataHandler =
9
184
  (
10
185
  slug: string,
11
186
  locale: string,
12
187
  currency: string,
13
- headers?: Record<string, string>
188
+ headers?: Record<string, string>,
189
+ next?: { revalidate: number }
14
190
  ) =>
15
191
  async () => {
16
192
  if (!slug) {
@@ -22,13 +198,20 @@ const getWidgetDataHandler =
22
198
  locale,
23
199
  currency,
24
200
  init: {
25
- headers
201
+ headers,
202
+ ...(next ? { next } : {})
26
203
  }
27
204
  });
28
205
  };
29
206
 
30
207
  const getWidgetSchemaDataHandler =
31
- (widgetSlug: string, locale: string, currency: string) => async () => {
208
+ (
209
+ widgetSlug: string,
210
+ locale: string,
211
+ currency: string,
212
+ next?: { revalidate: number }
213
+ ) =>
214
+ async () => {
32
215
  if (!widgetSlug) {
33
216
  return null;
34
217
  }
@@ -36,7 +219,8 @@ const getWidgetSchemaDataHandler =
36
219
  return await appFetch({
37
220
  url: widgets.getWidgetSchema(widgetSlug),
38
221
  locale,
39
- currency
222
+ currency,
223
+ init: next ? { next } : {}
40
224
  });
41
225
  };
42
226
 
@@ -53,6 +237,35 @@ export const getWidgetData = async <T>({
53
237
  cacheOptions?: CacheOptions;
54
238
  headers?: Record<string, string>;
55
239
  }): Promise<WidgetResultType<T>> => {
240
+ const requestPreviewId =
241
+ slug === 'theme-config' ? '' : await previewIdForRequest(locale, currency);
242
+ const previewId = isPreviewTransformableSlug(slug, requestPreviewId)
243
+ ? requestPreviewId
244
+ : '';
245
+ if (previewId) {
246
+ const previewData = await getWidgetDataHandler(
247
+ previewSlug(slug, previewId),
248
+ locale,
249
+ currency,
250
+ headers,
251
+ PREVIEW_NO_STORE
252
+ )();
253
+
254
+ // A snapshot HOLDER (placeholder blob carrier, consumed exclusively via
255
+ // getPreviewSnapshot) is not a per-widget preview copy — returning it
256
+ // here would shadow the live widget with an attribute-less shell when
257
+ // its blob is malformed and the caller fell back to the live path.
258
+ const previewAttributes = (
259
+ previewData as { attributes?: Record<string, unknown> } | null
260
+ )?.attributes;
261
+ if (
262
+ previewAttributes &&
263
+ previewAttributes[PREVIEW_SNAPSHOT_ATTRIBUTE] === undefined
264
+ ) {
265
+ return previewData as WidgetResultType<T>;
266
+ }
267
+ }
268
+
56
269
  return Cache.wrap(
57
270
  CacheKey.Widget(slug),
58
271
  locale,
@@ -65,7 +278,13 @@ export const getWidgetData = async <T>({
65
278
  };
66
279
 
67
280
  const getCollectionWidgetDataHandler =
68
- (slug: string, locale: string, currency: string) => async () => {
281
+ (
282
+ slug: string,
283
+ locale: string,
284
+ currency: string,
285
+ next?: { revalidate: number }
286
+ ) =>
287
+ async () => {
69
288
  if (!slug) {
70
289
  return null;
71
290
  }
@@ -73,7 +292,8 @@ const getCollectionWidgetDataHandler =
73
292
  return await appFetch({
74
293
  url: widgets.getCollectionWidget(slug),
75
294
  locale,
76
- currency
295
+ currency,
296
+ init: next ? { next } : {}
77
297
  });
78
298
  };
79
299
 
@@ -88,6 +308,24 @@ export const getCollectionWidgetData = async <T>({
88
308
  currency?: string;
89
309
  cacheOptions?: CacheOptions;
90
310
  }): Promise<WidgetResultType<T>> => {
311
+ const requestPreviewId =
312
+ slug === 'theme-config' ? '' : await previewIdForRequest(locale, currency);
313
+ const previewId = isPreviewTransformableSlug(slug, requestPreviewId)
314
+ ? requestPreviewId
315
+ : '';
316
+ if (previewId) {
317
+ const previewData = await getCollectionWidgetDataHandler(
318
+ previewSlug(slug, previewId),
319
+ locale,
320
+ currency,
321
+ PREVIEW_NO_STORE
322
+ )();
323
+
324
+ if ((previewData as { attributes?: unknown } | null)?.attributes) {
325
+ return previewData as WidgetResultType<T>;
326
+ }
327
+ }
328
+
91
329
  return Cache.wrap(
92
330
  CacheKey.Widget(`collection:${slug}`),
93
331
  locale,
@@ -110,6 +348,26 @@ export const getWidgetSchemaData = async <T>({
110
348
  currency?: string;
111
349
  cacheOptions?: CacheOptions;
112
350
  }): Promise<WidgetSchemaType<T>> => {
351
+ const requestPreviewId =
352
+ widgetSlug === 'theme-config'
353
+ ? ''
354
+ : await previewIdForRequest(locale, currency);
355
+ const previewId = isPreviewTransformableSlug(widgetSlug, requestPreviewId)
356
+ ? requestPreviewId
357
+ : '';
358
+ if (previewId) {
359
+ const previewData = await getWidgetSchemaDataHandler(
360
+ previewSlug(widgetSlug, previewId),
361
+ locale,
362
+ currency,
363
+ PREVIEW_NO_STORE
364
+ )();
365
+
366
+ if ((previewData as { schema?: unknown } | null)?.schema) {
367
+ return previewData as WidgetSchemaType<T>;
368
+ }
369
+ }
370
+
113
371
  return Cache.wrap(
114
372
  CacheKey.WidgetSchema(widgetSlug),
115
373
  locale,
@@ -15,6 +15,7 @@ import {
15
15
  getBuiltInSegments,
16
16
  isLegacyMode
17
17
  } from '../../utils/pz-segments';
18
+ import { isValidPreviewId, PREVIEW_PZ_SEGMENT } from '../../utils/preview';
18
19
 
19
20
  type SegmentType = 'root-layout' | 'layout' | 'page';
20
21
 
@@ -60,6 +61,9 @@ export const withSegmentDefaults =
60
61
 
61
62
  let localeValue: string;
62
63
  let currencyValue: string;
64
+ // Which named widget preview this render belongs to, if any — see
65
+ // utils/preview.ts for why it travels in the route rather than a cookie.
66
+ let previewValue = '';
63
67
 
64
68
  if (isLegacyMode(settings)) {
65
69
  localeValue = resolvedParams.locale;
@@ -70,6 +74,10 @@ export const withSegmentDefaults =
70
74
  const builtIn = getBuiltInSegments(parsed, settings);
71
75
  localeValue = builtIn.locale;
72
76
  currencyValue = builtIn.currency;
77
+ // Cookie-derived, so re-validated here rather than trusted.
78
+ previewValue = isValidPreviewId(parsed[PREVIEW_PZ_SEGMENT])
79
+ ? parsed[PREVIEW_PZ_SEGMENT]
80
+ : '';
73
81
  }
74
82
 
75
83
  if (options.segmentType === 'root-layout') {
@@ -83,6 +91,7 @@ export const withSegmentDefaults =
83
91
 
84
92
  ServerVariables.locale = localeValue;
85
93
  ServerVariables.currency = currencyValue;
94
+ ServerVariables.previewId = previewValue;
86
95
 
87
96
  return await (
88
97
  <>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@akinon/next",
3
3
  "description": "Core package for Project Zero Next",
4
- "version": "2.0.78",
4
+ "version": "2.0.79-beta.1",
5
5
  "private": false,
6
6
  "license": "MIT",
7
7
  "bin": {
@@ -36,7 +36,7 @@
36
36
  "set-cookie-parser": "2.6.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@akinon/eslint-plugin-projectzero": "2.0.78",
39
+ "@akinon/eslint-plugin-projectzero": "2.0.79-beta.1",
40
40
  "@babel/core": "7.26.10",
41
41
  "@babel/preset-env": "7.26.9",
42
42
  "@babel/preset-typescript": "7.27.0",
@@ -76,7 +76,9 @@ const appFetch = async <T>({
76
76
  'x-forwarded-for': ip
77
77
  };
78
78
 
79
- init.next = {
79
+ // Callers may pass their own cache directives (e.g. widget preview
80
+ // fetches use revalidate: 0); only apply the default when they don't.
81
+ init.next = init.next ?? {
80
82
  revalidate: Settings.usePrettyUrlRoute ? 0 : 60
81
83
  };
82
84
 
@@ -0,0 +1,111 @@
1
+ import { isValidPreviewId } from './preview';
2
+
3
+ /**
4
+ * Signed, expiring preview entry tokens.
5
+ *
6
+ * The storefront never hands out its PREVIEW_SECRET: the editor asks
7
+ * `/api/preview/link` (proving it is an editor user with its Omnitron token)
8
+ * and receives a token that names ONE preview and dies at `expiresAt`. A leaked
9
+ * link therefore exposes nothing lasting, and rotating the secret invalidates
10
+ * every outstanding link at once.
11
+ *
12
+ * Format: `v1.<previewId>.<expiresAt unix seconds>.<base64url HMAC-SHA256>`.
13
+ * Web Crypto only, so the same code runs in Node route handlers and on the
14
+ * edge.
15
+ */
16
+ export const PREVIEW_TOKEN_VERSION = 'v1';
17
+
18
+ /** How long an editor-issued preview link stays valid unless configured. */
19
+ export const DEFAULT_PREVIEW_LINK_TTL_SECONDS = 24 * 60 * 60;
20
+
21
+ export interface PreviewTokenClaims {
22
+ previewId: string;
23
+ /** Unix time in SECONDS. */
24
+ expiresAt: number;
25
+ }
26
+
27
+ export type PreviewTokenVerdict =
28
+ | { ok: true; claims: PreviewTokenClaims }
29
+ | { ok: false; reason: 'malformed' | 'expired' | 'invalid-signature' };
30
+
31
+ // Created per call: the module is also imported where TextEncoder only shows
32
+ // up after a polyfill (jsdom), and the cost is negligible.
33
+ const encode = (value: string) => new TextEncoder().encode(value);
34
+
35
+ const base64url = (bytes: ArrayBuffer): string => {
36
+ const view = new Uint8Array(bytes);
37
+ let binary = '';
38
+ for (let i = 0; i < view.length; i++) {
39
+ binary += String.fromCharCode(view[i]);
40
+ }
41
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
42
+ };
43
+
44
+ const hmac = async (secret: string, payload: string): Promise<string> => {
45
+ const key = await crypto.subtle.importKey(
46
+ 'raw',
47
+ encode(secret),
48
+ { name: 'HMAC', hash: 'SHA-256' },
49
+ false,
50
+ ['sign']
51
+ );
52
+ return base64url(await crypto.subtle.sign('HMAC', key, encode(payload)));
53
+ };
54
+
55
+ /** Constant-time string equality — a signature check must not leak by timing. */
56
+ const timingSafeEqual = (a: string, b: string): boolean => {
57
+ if (a.length !== b.length) return false;
58
+ let diff = 0;
59
+ for (let i = 0; i < a.length; i++) {
60
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
61
+ }
62
+ return diff === 0;
63
+ };
64
+
65
+ const payloadOf = ({ previewId, expiresAt }: PreviewTokenClaims): string =>
66
+ `${PREVIEW_TOKEN_VERSION}.${previewId}.${expiresAt}`;
67
+
68
+ export const signPreviewToken = async (
69
+ claims: PreviewTokenClaims,
70
+ secret: string
71
+ ): Promise<string> => {
72
+ if (!isValidPreviewId(claims.previewId)) {
73
+ throw new Error('signPreviewToken: invalid preview id');
74
+ }
75
+ if (!Number.isInteger(claims.expiresAt) || claims.expiresAt <= 0) {
76
+ throw new Error('signPreviewToken: invalid expiry');
77
+ }
78
+ const payload = payloadOf(claims);
79
+ return `${payload}.${await hmac(secret, payload)}`;
80
+ };
81
+
82
+ export const verifyPreviewToken = async (
83
+ token: string,
84
+ secret: string,
85
+ nowMs: number = Date.now()
86
+ ): Promise<PreviewTokenVerdict> => {
87
+ const parts = typeof token === 'string' ? token.split('.') : [];
88
+ if (parts.length !== 4 || parts[0] !== PREVIEW_TOKEN_VERSION) {
89
+ return { ok: false, reason: 'malformed' };
90
+ }
91
+ const [, previewId, expiresAtRaw, signature] = parts;
92
+ const expiresAt = Number(expiresAtRaw);
93
+ if (
94
+ !isValidPreviewId(previewId) ||
95
+ !/^\d+$/.test(expiresAtRaw) ||
96
+ !Number.isSafeInteger(expiresAt) ||
97
+ !signature
98
+ ) {
99
+ return { ok: false, reason: 'malformed' };
100
+ }
101
+ // Signature before expiry: an attacker must not learn which expired tokens
102
+ // were once valid.
103
+ const expected = await hmac(secret, payloadOf({ previewId, expiresAt }));
104
+ if (!timingSafeEqual(signature, expected)) {
105
+ return { ok: false, reason: 'invalid-signature' };
106
+ }
107
+ if (expiresAt * 1000 <= nowMs) {
108
+ return { ok: false, reason: 'expired' };
109
+ }
110
+ return { ok: true, claims: { previewId, expiresAt } };
111
+ };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Widget preview contract — shared by the middleware/route handler that
3
+ * enters preview, the pz segment that carries which preview is being viewed,
4
+ * and the widget fetch layer that resolves the preview copies.
5
+ *
6
+ * The theme editor writes the other half of this contract: it creates named
7
+ * previews and stores each one's pages under `<slug>-preview-<id>`. The two
8
+ * sides must never drift.
9
+ */
10
+
11
+ /** Suffix before the preview id — hyphenated because Omnitron slugifies. */
12
+ export const PREVIEW_SLUG_SUFFIX = '-preview';
13
+
14
+ /** Remembers which named preview this browser is viewing. */
15
+ export const PREVIEW_ID_COOKIE = 'pz-preview-id';
16
+
17
+ /** Next.js's own draft-mode cookie — set by `draftMode().enable()`. */
18
+ export const DRAFT_MODE_COOKIE = '__prerender_bypass';
19
+
20
+ /** Query key on the editor's link, consumed by the /api/preview handler. */
21
+ export const PREVIEW_ID_QUERY_PARAM = 'preview_id';
22
+
23
+ /**
24
+ * The pz segment carrying the preview id into the render.
25
+ *
26
+ * A cookie cannot be used directly: the pages that render widgets are
27
+ * `dynamic = 'force-static'`, and Next.js blanks `cookies()`/`headers()`
28
+ * under that config (draftMode is the exception). Route params always
29
+ * survive, so the middleware resolves the cookie into this segment and the
30
+ * server components read it from there. See settings.js `pzSegments`.
31
+ */
32
+ export const PREVIEW_PZ_SEGMENT = 'preview';
33
+
34
+ /**
35
+ * Ids come from a cookie, so they are validated everywhere they are used:
36
+ * lowercase slug words joined by single hyphens, bounded length — exactly
37
+ * what the editor produces (see slugifyPreviewId there). No `--` anywhere:
38
+ * that is the pz segment separator, and an id containing it would make the
39
+ * segment undecodable.
40
+ */
41
+ export const isValidPreviewId = (id: unknown): id is string =>
42
+ typeof id === 'string' &&
43
+ id.length <= 32 &&
44
+ /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id);
45
+
46
+ /** The slug a widget's copy lives under inside one named preview. */
47
+ export const previewSlug = (slug: string, previewId: string): string =>
48
+ `${slug}${PREVIEW_SLUG_SUFFIX}-${previewId}`;
49
+
50
+ /**
51
+ * True for slugs shaped like a preview copy of something. A HEURISTIC — a
52
+ * live slug can legitimately end this way (a custom page named
53
+ * `summer-preview-2026`), so the fetch layer does not use it to decide
54
+ * whether to overlay; see `isPreviewCopySlug`.
55
+ */
56
+ export const isPreviewSlug = (slug: string): boolean =>
57
+ /-preview-[a-z0-9-]+$/.test(slug);
58
+
59
+ /**
60
+ * True when `slug` is already the copy of something inside THIS preview —
61
+ * the exact check the fetch layer needs so preview slugs are never nested,
62
+ * without misreading live slugs that merely look like one.
63
+ */
64
+ export const isPreviewCopySlug = (slug: string, previewId: string): boolean =>
65
+ previewId !== '' && slug.endsWith(previewSlug('', previewId));
66
+
67
+ /**
68
+ * Resolves the pz segment value from the request — used by settings.js.
69
+ * An invalid or absent cookie yields '' (no preview), which the fetch layer
70
+ * treats as "render live".
71
+ *
72
+ * The id only counts alongside Next's draft-mode cookie: without it the
73
+ * request renders live anyway, and folding an unauthenticated cookie value
74
+ * into the route segment would let any visitor mint a fresh ISR/Redis cache
75
+ * key per request.
76
+ */
77
+ export const resolvePreviewSegment = (req: {
78
+ cookies: { get: (name: string) => { value: string } | undefined };
79
+ }): string => {
80
+ if (!req.cookies.get(DRAFT_MODE_COOKIE)?.value) return '';
81
+ const value = req.cookies.get(PREVIEW_ID_COOKIE)?.value ?? '';
82
+ return isValidPreviewId(value) ? value : '';
83
+ };
@@ -40,15 +40,44 @@ export function encodePzValue(
40
40
  .join(config.separator);
41
41
  }
42
42
 
43
+ /**
44
+ * Inverse of `encodePzValue`.
45
+ *
46
+ * The `url` segment is `encodeURIComponent(fullUrl)`, and that leaves `-`
47
+ * alone — so a pathname containing the separator (`/collections/summer--sale`)
48
+ * splits into extra parts. Only `url` can do that (locale, currency and the
49
+ * custom segments are validated slugs), so the segments before it are read
50
+ * from the front, the ones after it from the back, and whatever is left in
51
+ * the middle is the url re-joined. A purely positional read would hand the
52
+ * url's tail to the segment after it — with a preview segment present that
53
+ * meant rendering the wrong preview (or live) with a misleading banner.
54
+ */
43
55
  export function decodePzValue(
44
56
  pzValue: string,
45
57
  config: PzSegmentsConfig
46
58
  ): Record<string, string> {
47
59
  const parts = pzValue.split(config.separator);
48
60
  const result: Record<string, string> = {};
61
+ const urlIndex = config.segments.findIndex((seg) => seg.name === 'url');
49
62
 
63
+ if (urlIndex === -1 || parts.length <= config.segments.length) {
64
+ config.segments.forEach((seg, index) => {
65
+ result[seg.name] = parts[index] ?? '';
66
+ });
67
+ return result;
68
+ }
69
+
70
+ const trailing = config.segments.length - urlIndex - 1;
50
71
  config.segments.forEach((seg, index) => {
51
- result[seg.name] = parts[index] ?? '';
72
+ if (index < urlIndex) {
73
+ result[seg.name] = parts[index] ?? '';
74
+ } else if (index === urlIndex) {
75
+ result[seg.name] = parts
76
+ .slice(urlIndex, parts.length - trailing)
77
+ .join(config.separator);
78
+ } else {
79
+ result[seg.name] = parts[parts.length - trailing + (index - urlIndex - 1)] ?? '';
80
+ }
52
81
  });
53
82
 
54
83
  return result;
@@ -6,5 +6,12 @@ const { locales, defaultLocaleValue, defaultCurrencyCode } =
6
6
  export const ServerVariables = {
7
7
  locale: locales.find((l) => l.value === defaultLocaleValue)?.value ?? '',
8
8
  currency: defaultCurrencyCode,
9
- globalHeaders: {}
9
+ globalHeaders: {},
10
+ /**
11
+ * Which named widget preview the current render belongs to, decoded from
12
+ * the pz route segment by withSegmentDefaults. Empty for ordinary traffic.
13
+ * Only ever acted on together with draft mode, so a value left behind by a
14
+ * concurrent request cannot leak preview content to a normal visitor.
15
+ */
16
+ previewId: ''
10
17
  };