@akinon/next 1.126.15-v1-rc.12 → 1.126.15
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 +6 -4
- package/__tests__/widget-preview.test.ts +300 -0
- package/data/server/widget.ts +216 -2
- package/hocs/server/with-segment-defaults.tsx +9 -0
- package/package.json +2 -2
- package/utils/app-fetch.ts +3 -1
- package/utils/preview-render.ts +28 -0
- package/utils/preview-token.ts +111 -0
- package/utils/preview.ts +83 -0
- package/utils/pz-segments.ts +30 -1
- package/utils/server-variables.ts +8 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
# @akinon/next
|
|
2
2
|
|
|
3
|
-
## 1.126.15
|
|
3
|
+
## 1.126.15
|
|
4
4
|
|
|
5
5
|
### Patch Changes
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
- 4f2f9b8: ZERO-5149: Bring the theme editor's widget preview to the v1 line
|
|
8
|
+
|
|
9
|
+
Storefronts on @akinon/next 1.x can now open the theme editor's named previews the way 2.x storefronts do. The editor asks `/api/preview/link` for a signed, expiring link, and `?preview=<token>` enters Next.js draft mode through `/api/preview`. While draft mode is on, `getWidgetData` tries `<slug>-preview-<id>` first, the theme-previews registry retires deleted previews, and `getPreviewSnapshot` hands @akinon/pz-theme (2.0.79 or later) the placeholder snapshot it renders from. Preview content is only rendered when Next 14 itself treats the render as a draft, so it can never reach the shared ISR cache. Normal traffic renders live as before.
|
|
10
|
+
|
|
11
|
+
A storefront needs the `[pz]` route layout (`usePzSegment: true`). Legacy `[commerce]/[locale]/[currency]` projects migrate first with `npx projectzero codemod --codemod=migrate-segments`, otherwise previews render live. On top of that it needs `PREVIEW_SECRET` and `MAIN_APP_URL` (optionally `PREVIEW_LINK_TTL_SECONDS`), the `/api/preview` and `/api/preview/link` route handlers, the `?preview` entry in `src/middleware.ts` and the `preview` segment in `settings.js` `pzSegments`, all as in projectzeronext. The new segment changes every page's pz value once, so ISR entries are rebuilt after the upgrade.
|
|
10
12
|
|
|
11
13
|
## 1.126.14
|
|
12
14
|
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
const mockDraftMode = { isEnabled: false };
|
|
2
|
+
// Next 14's own draft decision for the render — false when it will be cached.
|
|
3
|
+
const mockStaticGenerationStore = { isDraftMode: false };
|
|
4
|
+
const mockServerVariables = { locale: 'en', currency: 'usd', previewId: '' };
|
|
5
|
+
const mockWidgets: Record<string, unknown> = {};
|
|
6
|
+
const mockAppFetch = jest.fn();
|
|
7
|
+
const mockCacheWrap = jest.fn();
|
|
8
|
+
|
|
9
|
+
jest.mock('server-only', () => ({}));
|
|
10
|
+
|
|
11
|
+
jest.mock('next/headers', () => ({
|
|
12
|
+
draftMode: () => mockDraftMode
|
|
13
|
+
}));
|
|
14
|
+
|
|
15
|
+
jest.mock(
|
|
16
|
+
'next/dist/client/components/static-generation-async-storage.external',
|
|
17
|
+
() => ({
|
|
18
|
+
staticGenerationAsyncStorage: { getStore: () => mockStaticGenerationStore }
|
|
19
|
+
})
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
jest.mock('../utils/server-variables', () => ({
|
|
23
|
+
ServerVariables: mockServerVariables
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
jest.mock('../data/urls', () => ({
|
|
27
|
+
widgets: { getWidget: (slug: string) => `/widgets/${slug}/` }
|
|
28
|
+
}));
|
|
29
|
+
|
|
30
|
+
jest.mock('../utils/app-fetch', () => ({
|
|
31
|
+
__esModule: true,
|
|
32
|
+
default: (...args: unknown[]) => mockAppFetch(...args)
|
|
33
|
+
}));
|
|
34
|
+
|
|
35
|
+
jest.mock('../lib/cache', () => ({
|
|
36
|
+
Cache: {
|
|
37
|
+
wrap: (...args: unknown[]) => mockCacheWrap(...args)
|
|
38
|
+
},
|
|
39
|
+
CacheKey: { Widget: (slug: string) => `widget_${slug}` }
|
|
40
|
+
}));
|
|
41
|
+
|
|
42
|
+
import { getPreviewSnapshot, getWidgetData } from '../data/server/widget';
|
|
43
|
+
|
|
44
|
+
type FetchArgs = { url: string; init?: { next?: { revalidate: number } } };
|
|
45
|
+
|
|
46
|
+
const registry = (...ids: string[]) => ({
|
|
47
|
+
attributes: {
|
|
48
|
+
theme_previews: {
|
|
49
|
+
value: JSON.stringify({
|
|
50
|
+
version: 1,
|
|
51
|
+
previews: ids.map((id) => ({ id, name: id }))
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const liveWidget = (slug: string) => ({ slug, attributes: { live: true } });
|
|
58
|
+
|
|
59
|
+
const fetchedUrls = () =>
|
|
60
|
+
mockAppFetch.mock.calls.map(([args]) => (args as FetchArgs).url);
|
|
61
|
+
|
|
62
|
+
// The registry is remembered for 5s across requests; every test starts past it.
|
|
63
|
+
let now = 1_800_000_000_000;
|
|
64
|
+
|
|
65
|
+
beforeEach(() => {
|
|
66
|
+
now += 60_000;
|
|
67
|
+
jest.spyOn(Date, 'now').mockReturnValue(now);
|
|
68
|
+
mockDraftMode.isEnabled = true;
|
|
69
|
+
mockStaticGenerationStore.isDraftMode = true;
|
|
70
|
+
mockServerVariables.previewId = 'kis';
|
|
71
|
+
for (const key of Object.keys(mockWidgets)) delete mockWidgets[key];
|
|
72
|
+
mockWidgets['/widgets/theme-previews/'] = registry('draft', 'kis');
|
|
73
|
+
mockAppFetch.mockReset();
|
|
74
|
+
mockAppFetch.mockImplementation(async ({ url }: FetchArgs) =>
|
|
75
|
+
url in mockWidgets ? mockWidgets[url] : { detail: 'Not found.' }
|
|
76
|
+
);
|
|
77
|
+
mockCacheWrap.mockReset();
|
|
78
|
+
mockCacheWrap.mockImplementation(async (key: string) =>
|
|
79
|
+
liveWidget(key.replace(/^widget_/, ''))
|
|
80
|
+
);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
afterEach(() => {
|
|
84
|
+
jest.restoreAllMocks();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
describe('getWidgetData in widget preview', () => {
|
|
88
|
+
it('serves the live widget when draft mode is off, without touching preview slugs', async () => {
|
|
89
|
+
mockDraftMode.isEnabled = false;
|
|
90
|
+
|
|
91
|
+
expect(await getWidgetData({ slug: 'home-banner' })).toEqual(
|
|
92
|
+
liveWidget('home-banner')
|
|
93
|
+
);
|
|
94
|
+
expect(mockAppFetch).not.toHaveBeenCalled();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('serves live when Next 14 caches the render despite a valid bypass cookie', async () => {
|
|
98
|
+
// __prerender_bypass valid (draftMode() on) but Next is writing this render
|
|
99
|
+
// to the shared ISR entry, e.g. because a junk __next_preview_data rode along.
|
|
100
|
+
mockStaticGenerationStore.isDraftMode = false;
|
|
101
|
+
mockWidgets['/widgets/home-banner-preview-kis/'] = {
|
|
102
|
+
attributes: { title: 'Draft banner' }
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
expect(await getWidgetData({ slug: 'home-banner' })).toEqual(
|
|
106
|
+
liveWidget('home-banner')
|
|
107
|
+
);
|
|
108
|
+
expect(mockAppFetch).not.toHaveBeenCalled();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('serves live when there is no request scope (build-time prerender)', async () => {
|
|
112
|
+
const headers = jest.requireMock('next/headers');
|
|
113
|
+
jest.spyOn(headers, 'draftMode').mockImplementation(() => {
|
|
114
|
+
throw new Error('`draftMode` was called outside a request scope');
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
expect(await getWidgetData({ slug: 'home-banner' })).toEqual(
|
|
118
|
+
liveWidget('home-banner')
|
|
119
|
+
);
|
|
120
|
+
expect(mockAppFetch).not.toHaveBeenCalled();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it.each(['', 'Bad--Id', '../x'])(
|
|
124
|
+
'ignores an absent or invalid preview id (%j)',
|
|
125
|
+
async (previewId) => {
|
|
126
|
+
mockServerVariables.previewId = previewId;
|
|
127
|
+
|
|
128
|
+
expect(await getWidgetData({ slug: 'home-banner' })).toEqual(
|
|
129
|
+
liveWidget('home-banner')
|
|
130
|
+
);
|
|
131
|
+
expect(mockAppFetch).not.toHaveBeenCalled();
|
|
132
|
+
}
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
it("returns this preview's copy, read uncached, when it exists", async () => {
|
|
136
|
+
const copy = { attributes: { title: 'Draft banner' } };
|
|
137
|
+
mockWidgets['/widgets/home-banner-preview-kis/'] = copy;
|
|
138
|
+
|
|
139
|
+
expect(await getWidgetData({ slug: 'home-banner' })).toBe(copy);
|
|
140
|
+
const previewRead = mockAppFetch.mock.calls
|
|
141
|
+
.map(([args]) => args as FetchArgs)
|
|
142
|
+
.find(({ url }) => url === '/widgets/home-banner-preview-kis/');
|
|
143
|
+
expect(previewRead?.init?.next).toEqual({ revalidate: 0 });
|
|
144
|
+
expect(mockCacheWrap).not.toHaveBeenCalled();
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('falls back to live when the preview has no copy of the widget', async () => {
|
|
148
|
+
expect(await getWidgetData({ slug: 'home-banner' })).toEqual(
|
|
149
|
+
liveWidget('home-banner')
|
|
150
|
+
);
|
|
151
|
+
expect(fetchedUrls()).toContain('/widgets/home-banner-preview-kis/');
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('never serves a snapshot holder as the widget itself', async () => {
|
|
155
|
+
mockWidgets['/widgets/homepage-body-preview-kis/'] = {
|
|
156
|
+
attributes: { preview_snapshot: '{"version":0}' }
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
expect(await getWidgetData({ slug: 'homepage-body' })).toEqual(
|
|
160
|
+
liveWidget('homepage-body')
|
|
161
|
+
);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('never overlays theme-config and never nests a copy of this preview', async () => {
|
|
165
|
+
await getWidgetData({ slug: 'theme-config' });
|
|
166
|
+
await getWidgetData({ slug: 'header-preview-kis' });
|
|
167
|
+
|
|
168
|
+
expect(fetchedUrls()).not.toContain('/widgets/theme-config-preview-kis/');
|
|
169
|
+
expect(fetchedUrls()).not.toContain(
|
|
170
|
+
'/widgets/header-preview-kis-preview-kis/'
|
|
171
|
+
);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it('overlays a live slug that merely looks like a copy of another preview', async () => {
|
|
175
|
+
const copy = { attributes: { title: 'Draft page' } };
|
|
176
|
+
mockWidgets['/widgets/page-summer-preview-2026-preview-kis/'] = copy;
|
|
177
|
+
|
|
178
|
+
expect(await getWidgetData({ slug: 'page-summer-preview-2026' })).toBe(
|
|
179
|
+
copy
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('renders live for a preview the registry no longer lists', async () => {
|
|
184
|
+
mockWidgets['/widgets/theme-previews/'] = registry('draft');
|
|
185
|
+
mockWidgets['/widgets/home-banner-preview-kis/'] = {
|
|
186
|
+
attributes: { title: 'Deleted preview' }
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
expect(await getWidgetData({ slug: 'home-banner' })).toEqual(
|
|
190
|
+
liveWidget('home-banner')
|
|
191
|
+
);
|
|
192
|
+
expect(fetchedUrls()).not.toContain('/widgets/home-banner-preview-kis/');
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it('fails open when the registry cannot be read', async () => {
|
|
196
|
+
const copy = { attributes: { title: 'Draft banner' } };
|
|
197
|
+
mockWidgets['/widgets/home-banner-preview-kis/'] = copy;
|
|
198
|
+
mockWidgets['/widgets/theme-previews/'] = {
|
|
199
|
+
attributes: { theme_previews: 'not json' }
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
expect(await getWidgetData({ slug: 'home-banner' })).toBe(copy);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it('reads the registry at most once within its 5s window', async () => {
|
|
206
|
+
const registryReads = () =>
|
|
207
|
+
fetchedUrls().filter((url) => url === '/widgets/theme-previews/');
|
|
208
|
+
|
|
209
|
+
await getWidgetData({ slug: 'home-banner' });
|
|
210
|
+
jest.spyOn(Date, 'now').mockReturnValue(now + 4_999);
|
|
211
|
+
await getWidgetData({ slug: 'footer' });
|
|
212
|
+
expect(registryReads()).toHaveLength(1);
|
|
213
|
+
|
|
214
|
+
jest.spyOn(Date, 'now').mockReturnValue(now + 5_000);
|
|
215
|
+
await getWidgetData({ slug: 'header' });
|
|
216
|
+
expect(registryReads()).toHaveLength(2);
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
describe('getPreviewSnapshot', () => {
|
|
221
|
+
const snapshot = {
|
|
222
|
+
version: 2,
|
|
223
|
+
savedAt: '2026-09-29T10:00:00.000Z',
|
|
224
|
+
themeSettings: {},
|
|
225
|
+
dataSources: [],
|
|
226
|
+
breakpoints: [{ id: 'tablet', minWidth: 768 }],
|
|
227
|
+
customPages: [],
|
|
228
|
+
sections: [{ id: 's1', blocks: [] }]
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const holder = (value: unknown) => ({
|
|
232
|
+
attributes: { preview_snapshot: value }
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it('returns the blob exactly as the editor wrote it', async () => {
|
|
236
|
+
mockWidgets['/widgets/homepage-body-preview-kis/'] = holder(
|
|
237
|
+
JSON.stringify(snapshot)
|
|
238
|
+
);
|
|
239
|
+
|
|
240
|
+
expect(await getPreviewSnapshot({ slug: 'homepage-body' })).toEqual(
|
|
241
|
+
snapshot
|
|
242
|
+
);
|
|
243
|
+
const read = mockAppFetch.mock.calls
|
|
244
|
+
.map(([args]) => args as FetchArgs)
|
|
245
|
+
.find(({ url }) => url === '/widgets/homepage-body-preview-kis/');
|
|
246
|
+
expect(read?.init?.next).toEqual({ revalidate: 0 });
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it('unwraps an attribute stored as { value }', async () => {
|
|
250
|
+
mockWidgets['/widgets/homepage-body-preview-kis/'] = holder({
|
|
251
|
+
value: JSON.stringify({ ...snapshot, version: 1 })
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
expect((await getPreviewSnapshot({ slug: 'homepage-body' }))?.version).toBe(
|
|
255
|
+
1
|
|
256
|
+
);
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it.each([
|
|
260
|
+
['a discarded snapshot', '{"version":0}'],
|
|
261
|
+
['malformed JSON', '{"version":2,'],
|
|
262
|
+
['sections that are not a list', '{"version":2,"sections":{}}'],
|
|
263
|
+
['a non-numeric version', '{"version":"2","sections":[]}'],
|
|
264
|
+
['an empty value', '']
|
|
265
|
+
])('treats %s as no snapshot', async (_label, value) => {
|
|
266
|
+
mockWidgets['/widgets/homepage-body-preview-kis/'] = holder(value);
|
|
267
|
+
|
|
268
|
+
expect(await getPreviewSnapshot({ slug: 'homepage-body' })).toBeNull();
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
it('is null outside draft mode or without a registered preview', async () => {
|
|
272
|
+
mockWidgets['/widgets/homepage-body-preview-kis/'] = holder(
|
|
273
|
+
JSON.stringify(snapshot)
|
|
274
|
+
);
|
|
275
|
+
|
|
276
|
+
mockDraftMode.isEnabled = false;
|
|
277
|
+
expect(await getPreviewSnapshot({ slug: 'homepage-body' })).toBeNull();
|
|
278
|
+
|
|
279
|
+
// Only the registry can refuse here: this preview's holder does exist.
|
|
280
|
+
mockDraftMode.isEnabled = true;
|
|
281
|
+
mockServerVariables.previewId = 'winter';
|
|
282
|
+
mockWidgets['/widgets/homepage-body-preview-winter/'] = holder(
|
|
283
|
+
JSON.stringify(snapshot)
|
|
284
|
+
);
|
|
285
|
+
expect(await getPreviewSnapshot({ slug: 'homepage-body' })).toBeNull();
|
|
286
|
+
expect(fetchedUrls()).not.toContain(
|
|
287
|
+
'/widgets/homepage-body-preview-winter/'
|
|
288
|
+
);
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
it('is null when Next 14 caches the render despite a valid bypass cookie', async () => {
|
|
292
|
+
mockStaticGenerationStore.isDraftMode = false;
|
|
293
|
+
mockWidgets['/widgets/homepage-body-preview-kis/'] = holder(
|
|
294
|
+
JSON.stringify(snapshot)
|
|
295
|
+
);
|
|
296
|
+
|
|
297
|
+
expect(await getPreviewSnapshot({ slug: 'homepage-body' })).toBeNull();
|
|
298
|
+
expect(mockAppFetch).not.toHaveBeenCalled();
|
|
299
|
+
});
|
|
300
|
+
});
|
package/data/server/widget.ts
CHANGED
|
@@ -4,13 +4,197 @@ import { CacheOptions, WidgetResultType } from '../../types';
|
|
|
4
4
|
import appFetch from '../../utils/app-fetch';
|
|
5
5
|
import { widgets } from '../urls';
|
|
6
6
|
import { ServerVariables } from '../../utils/server-variables';
|
|
7
|
+
import {
|
|
8
|
+
isPreviewCopySlug,
|
|
9
|
+
isValidPreviewId,
|
|
10
|
+
previewSlug
|
|
11
|
+
} from '../../utils/preview';
|
|
12
|
+
import { isDraftRender } from '../../utils/preview-render';
|
|
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
|
+
// Draft mode as Next 14 caches it, not just the bypass cookie — see
|
|
110
|
+
// utils/preview-render.ts.
|
|
111
|
+
if (!isDraftRender()) return '';
|
|
112
|
+
const previewId = ServerVariables.previewId;
|
|
113
|
+
if (!isValidPreviewId(previewId)) return '';
|
|
114
|
+
return (await registryKnowsPreview(previewId, locale, currency))
|
|
115
|
+
? previewId
|
|
116
|
+
: '';
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Whole-placeholder preview snapshot written by the theme editor into the
|
|
121
|
+
* `preview_snapshot` attribute of `<placeholderSlug>-preview-<previewId>`.
|
|
122
|
+
* When present (draft mode only), the placeholder renders straight from this
|
|
123
|
+
* blob — no per-section fetches.
|
|
124
|
+
*/
|
|
125
|
+
export type PreviewSnapshot = {
|
|
126
|
+
version: number;
|
|
127
|
+
savedAt?: string;
|
|
128
|
+
themeSettings?: Record<string, unknown> | null;
|
|
129
|
+
dataSources?: unknown[];
|
|
130
|
+
sections: unknown[];
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
export const getPreviewSnapshot = async ({
|
|
134
|
+
slug,
|
|
135
|
+
locale = ServerVariables.locale,
|
|
136
|
+
currency = ServerVariables.currency
|
|
137
|
+
}: {
|
|
138
|
+
slug: string;
|
|
139
|
+
locale?: string;
|
|
140
|
+
currency?: string;
|
|
141
|
+
}): Promise<PreviewSnapshot | null> => {
|
|
142
|
+
const previewId = slug ? await previewIdForRequest(locale, currency) : '';
|
|
143
|
+
if (!previewId) {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const widget = await getWidgetDataHandler(
|
|
148
|
+
previewSlug(slug, previewId),
|
|
149
|
+
locale,
|
|
150
|
+
currency,
|
|
151
|
+
undefined,
|
|
152
|
+
PREVIEW_NO_STORE
|
|
153
|
+
)();
|
|
154
|
+
|
|
155
|
+
const rawAttribute = (
|
|
156
|
+
widget as { attributes?: Record<string, unknown> } | null
|
|
157
|
+
)?.attributes?.[PREVIEW_SNAPSHOT_ATTRIBUTE];
|
|
158
|
+
const rawValue =
|
|
159
|
+
typeof rawAttribute === 'object' &&
|
|
160
|
+
rawAttribute !== null &&
|
|
161
|
+
'value' in rawAttribute
|
|
162
|
+
? (rawAttribute as { value?: unknown }).value
|
|
163
|
+
: rawAttribute;
|
|
164
|
+
|
|
165
|
+
if (typeof rawValue !== 'string' || !rawValue) {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
const parsed = JSON.parse(rawValue);
|
|
171
|
+
// Any version the editor has shipped so far, not just the first one. The
|
|
172
|
+
// fields this reader uses (`sections`, `themeSettings`, `dataSources`)
|
|
173
|
+
// have been present since v1 and later versions only ADD keys it ignores
|
|
174
|
+
// — v2 carries the editor's own brand-config pieces (custom pages, style
|
|
175
|
+
// presets, section templates) so a theme applied into a working copy is
|
|
176
|
+
// not lost. Pinning the check to one number meant a blob the editor could
|
|
177
|
+
// write was silently unrenderable here, falling back to the LIVE page.
|
|
178
|
+
if (
|
|
179
|
+
typeof parsed?.version === 'number' &&
|
|
180
|
+
parsed.version >= 1 &&
|
|
181
|
+
Array.isArray(parsed.sections)
|
|
182
|
+
) {
|
|
183
|
+
return parsed as PreviewSnapshot;
|
|
184
|
+
}
|
|
185
|
+
} catch {
|
|
186
|
+
// Malformed snapshot — fall back to the live render path.
|
|
187
|
+
}
|
|
188
|
+
return null;
|
|
189
|
+
};
|
|
7
190
|
|
|
8
191
|
const getWidgetDataHandler =
|
|
9
192
|
(
|
|
10
193
|
slug: string,
|
|
11
194
|
locale: string,
|
|
12
195
|
currency: string,
|
|
13
|
-
headers?: Record<string, string
|
|
196
|
+
headers?: Record<string, string>,
|
|
197
|
+
next?: { revalidate: number }
|
|
14
198
|
) =>
|
|
15
199
|
async () => {
|
|
16
200
|
if (!slug) {
|
|
@@ -22,7 +206,8 @@ const getWidgetDataHandler =
|
|
|
22
206
|
locale,
|
|
23
207
|
currency,
|
|
24
208
|
init: {
|
|
25
|
-
headers
|
|
209
|
+
headers,
|
|
210
|
+
...(next ? { next } : {})
|
|
26
211
|
}
|
|
27
212
|
});
|
|
28
213
|
};
|
|
@@ -40,6 +225,35 @@ export const getWidgetData = async <T>({
|
|
|
40
225
|
cacheOptions?: CacheOptions;
|
|
41
226
|
headers?: Record<string, string>;
|
|
42
227
|
}): Promise<WidgetResultType<T>> => {
|
|
228
|
+
const requestPreviewId =
|
|
229
|
+
slug === 'theme-config' ? '' : await previewIdForRequest(locale, currency);
|
|
230
|
+
const previewId = isPreviewTransformableSlug(slug, requestPreviewId)
|
|
231
|
+
? requestPreviewId
|
|
232
|
+
: '';
|
|
233
|
+
if (previewId) {
|
|
234
|
+
const previewData = await getWidgetDataHandler(
|
|
235
|
+
previewSlug(slug, previewId),
|
|
236
|
+
locale,
|
|
237
|
+
currency,
|
|
238
|
+
headers,
|
|
239
|
+
PREVIEW_NO_STORE
|
|
240
|
+
)();
|
|
241
|
+
|
|
242
|
+
// A snapshot HOLDER (placeholder blob carrier, consumed exclusively via
|
|
243
|
+
// getPreviewSnapshot) is not a per-widget preview copy — returning it
|
|
244
|
+
// here would shadow the live widget with an attribute-less shell when
|
|
245
|
+
// its blob is malformed and the caller fell back to the live path.
|
|
246
|
+
const previewAttributes = (
|
|
247
|
+
previewData as { attributes?: Record<string, unknown> } | null
|
|
248
|
+
)?.attributes;
|
|
249
|
+
if (
|
|
250
|
+
previewAttributes &&
|
|
251
|
+
previewAttributes[PREVIEW_SNAPSHOT_ATTRIBUTE] === undefined
|
|
252
|
+
) {
|
|
253
|
+
return previewData as WidgetResultType<T>;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
43
257
|
return Cache.wrap(
|
|
44
258
|
CacheKey.Widget(slug),
|
|
45
259
|
locale,
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
getBuiltInSegments,
|
|
11
11
|
isLegacyMode
|
|
12
12
|
} from '../../utils/pz-segments';
|
|
13
|
+
import { isValidPreviewId, PREVIEW_PZ_SEGMENT } from '../../utils/preview';
|
|
13
14
|
|
|
14
15
|
type SegmentType = 'root-layout' | 'layout' | 'page';
|
|
15
16
|
|
|
@@ -28,6 +29,9 @@ export const withSegmentDefaults =
|
|
|
28
29
|
let componentProps = { ...props };
|
|
29
30
|
let localeValue: string;
|
|
30
31
|
let currencyValue: string;
|
|
32
|
+
// Which named widget preview this render belongs to, if any — see
|
|
33
|
+
// utils/preview.ts for why it travels in the route rather than a cookie.
|
|
34
|
+
let previewValue = '';
|
|
31
35
|
|
|
32
36
|
if (isLegacyMode(settings)) {
|
|
33
37
|
localeValue = (props.params as any).locale;
|
|
@@ -38,6 +42,10 @@ export const withSegmentDefaults =
|
|
|
38
42
|
const builtIn = getBuiltInSegments(parsed, settings);
|
|
39
43
|
localeValue = builtIn.locale;
|
|
40
44
|
currencyValue = builtIn.currency;
|
|
45
|
+
// Cookie-derived, so re-validated here rather than trusted.
|
|
46
|
+
previewValue = isValidPreviewId(parsed[PREVIEW_PZ_SEGMENT])
|
|
47
|
+
? parsed[PREVIEW_PZ_SEGMENT]
|
|
48
|
+
: '';
|
|
41
49
|
}
|
|
42
50
|
|
|
43
51
|
if (options.segmentType === 'root-layout') {
|
|
@@ -51,6 +59,7 @@ export const withSegmentDefaults =
|
|
|
51
59
|
|
|
52
60
|
ServerVariables.locale = localeValue;
|
|
53
61
|
ServerVariables.currency = currencyValue;
|
|
62
|
+
ServerVariables.previewId = previewValue;
|
|
54
63
|
|
|
55
64
|
return await (
|
|
56
65
|
<>
|
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": "1.126.15
|
|
4
|
+
"version": "1.126.15",
|
|
5
5
|
"private": false,
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"bin": {
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"set-cookie-parser": "2.6.0"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
|
-
"@akinon/eslint-plugin-projectzero": "1.126.15
|
|
38
|
+
"@akinon/eslint-plugin-projectzero": "1.126.15",
|
|
39
39
|
"@babel/core": "7.26.10",
|
|
40
40
|
"@babel/preset-env": "7.26.9",
|
|
41
41
|
"@babel/preset-typescript": "7.27.0",
|
package/utils/app-fetch.ts
CHANGED
|
@@ -52,7 +52,9 @@ const appFetch = async <T>({
|
|
|
52
52
|
'x-forwarded-for': ip
|
|
53
53
|
};
|
|
54
54
|
|
|
55
|
-
|
|
55
|
+
// Callers may pass their own cache directives (e.g. widget preview
|
|
56
|
+
// fetches use revalidate: 0); only apply the default when they don't.
|
|
57
|
+
init.next = init.next ?? {
|
|
56
58
|
revalidate: Settings.usePrettyUrlRoute ? 0 : 60
|
|
57
59
|
};
|
|
58
60
|
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
import { draftMode } from 'next/headers';
|
|
3
|
+
import { staticGenerationAsyncStorage } from 'next/dist/client/components/static-generation-async-storage.external';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* True only for a render Next.js itself treats as a draft render — one that
|
|
7
|
+
* is never written to the ISR cache.
|
|
8
|
+
*
|
|
9
|
+
* `draftMode().isEnabled` alone is not enough on Next 14. It compares only
|
|
10
|
+
* the `__prerender_bypass` cookie, while the decision to keep a render out of
|
|
11
|
+
* the ISR cache also reads the Pages Router `__next_preview_data` cookie: a
|
|
12
|
+
* valid bypass sent together with any junk data cookie renders "in draft
|
|
13
|
+
* mode" INTO the shared ISR entry, preview banner and preview content
|
|
14
|
+
* included. The static-generation store carries that caching decision
|
|
15
|
+
* (`isDraftMode`), so both have to agree. Next 15+ renders such a request as
|
|
16
|
+
* a prerender with draft mode off, which is why main reads draftMode() alone.
|
|
17
|
+
*/
|
|
18
|
+
export const isDraftRender = (): boolean => {
|
|
19
|
+
try {
|
|
20
|
+
return (
|
|
21
|
+
draftMode().isEnabled &&
|
|
22
|
+
staticGenerationAsyncStorage.getStore()?.isDraftMode === true
|
|
23
|
+
);
|
|
24
|
+
} catch {
|
|
25
|
+
// No request scope (e.g. build-time prerender) — never a preview.
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
@@ -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
|
+
};
|
package/utils/preview.ts
ADDED
|
@@ -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
|
+
};
|
package/utils/pz-segments.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
};
|