@akinon/next 2.0.79-beta.1 → 2.0.79-rc.0
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 +28 -8
- package/api/client-env.ts +78 -0
- package/bin/pz-generate-routes.js +4 -1
- package/components/plugin-module.tsx +0 -1
- package/data/client/checkout.ts +0 -1
- package/data/client/wishlist.ts +22 -0
- package/data/server/category.ts +14 -2
- package/data/server/list.ts +13 -1
- package/data/server/product.ts +10 -0
- package/data/server/special-page.ts +14 -1
- package/data/server/widget.ts +20 -265
- package/data/urls.ts +13 -4
- package/hocs/server/with-segment-defaults.tsx +0 -9
- package/hooks/index.ts +1 -0
- package/hooks/use-captcha.tsx +1 -1
- package/hooks/use-client-env.ts +265 -0
- package/middlewares/default.ts +254 -247
- package/middlewares/pretty-url.ts +3 -1
- package/package.json +2 -2
- package/plugins.d.ts +10 -0
- package/plugins.js +1 -0
- package/redux/middlewares/checkout.ts +45 -3
- package/redux/middlewares/pre-order/installment-option.ts +9 -1
- package/types/index.ts +20 -9
- package/utils/app-fetch.ts +1 -3
- package/utils/csrf.ts +1 -1
- package/utils/payload-optimizer.ts +481 -0
- package/utils/pz-segments.ts +1 -30
- package/utils/server-variables.ts +1 -8
- package/with-pz-config.js +6 -1
- package/utils/preview-token.ts +0 -111
- package/utils/preview.ts +0 -83
package/CHANGELOG.md
CHANGED
|
@@ -1,16 +1,36 @@
|
|
|
1
1
|
# @akinon/next
|
|
2
2
|
|
|
3
|
-
## 2.0.79-
|
|
3
|
+
## 2.0.79-rc.0
|
|
4
4
|
|
|
5
5
|
### Patch Changes
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
-
|
|
7
|
+
- 86187b1c: ZERO-4879: Repair sync-merge corruption in default middleware and server data loaders — remove a duplicated block that left an unbalanced brace, and restore the awaited `result` binding the payload optimization reads
|
|
8
|
+
- 0cf9ea239: BRDG-16491: Prevent redirect when iframe payment is active
|
|
9
|
+
- 324f97d55: ZERO-4219: replace masterpass-rest-complete with masterpass-rest-callback
|
|
10
|
+
- 51ea06888: ZERO-4377: Fix checkout card type state being cleared after valid bin number responses.
|
|
11
|
+
- ZERO-4160: Enhance oauth-login middleware with improved request handling and logging
|
|
12
|
+
- 2fea4143: ZERO-4620: Add runtime access to `NEXT_PUBLIC_*` environment variables from Client Components
|
|
13
|
+
- b55acb768: ZERO-2577: Fix pagination bug and update usePagination hook and ensure pagination controls rendering correctly
|
|
14
|
+
- 760258c1c: ZERO-4160: Enhance oauth-login middleware to handle fetch errors and improve response handling
|
|
15
|
+
- 143be2b9d: ZERO-3457: Crop styles are customizable and logic improved for rendering similar products modal
|
|
16
|
+
- 7889b08fe: ZERO-4276: Enhance route generation by adding .env loading and custom skip segments support
|
|
17
|
+
- 9f8cd3bc5: ZERO-3449: AI Search Active Filters & Crop Style changes have been implemented
|
|
18
|
+
- bfafa3f49: ZERO-4160: Refactor oauth-login middleware to use fetchCommerce for API calls and improve cookie handling
|
|
19
|
+
- 57d7eb305: ZERO-4276: Refactor route generation logic by removing environment loading and simplifying skip segments handling
|
|
20
|
+
- d99a6a7d5: ZERO-3457_1: Fixed the settings prop and made sure everything is customizable.
|
|
21
|
+
- 9db81a714: ZERO-4365: Remove brand `@theme/*` alias imports from library packages
|
|
22
|
+
- 591e345e1: ZERO-3855: Enhance credit card payment handling in checkout middlewares
|
|
23
|
+
- 4de5303c5: ZERO-2504: add cookie filter to api client request
|
|
24
|
+
- 95b139dc1: ZERO-3795: Remove duplicate entry for SavedCard in PluginComponents map
|
|
25
|
+
- 1d00f2d06: BRDG-16664: Set secure flag for CSRF token cookies in useCaptcha and default middleware
|
|
26
|
+
- 4ac7b2a1e: ZERO-4219: fix masterpass-rest callback route format and double-encoded error cookie
|
|
27
|
+
- e9598c71: ZERO-4622: Images remotePatterns for improved readability
|
|
28
|
+
- 4998a9631: ZERO-4168: Add server-side payload optimization
|
|
29
|
+
- 804d2bd6c: ZERO-4536: Add akinon.net domain to CSP frame-ancestors directive
|
|
30
|
+
- 3909d3224: Edit the duplicate Plugin.SimilarProducts in the plugin-module.
|
|
31
|
+
- 6a3d8a631: ZERO-4541: Fix URL query string formatting in getOrders and getOldOrders functions
|
|
32
|
+
- e18836b20: ZERO-4160: Restore scope in Sentry addon configuration in akinon.json
|
|
33
|
+
- b1111d7b: ZERO-4841: Guard `withPrettyUrl` against calling `String.prototype.replace` with an `undefined` locale prefix on projects without a URL locale prefix (e.g. `HideDefaultLocale`) — previously this coerced to the literal string `"undefined"` and silently stripped a trailing `/undefined` segment from the path before the pretty-url lookup, causing bogus URLs like `/{product-slug}/undefined` to resolve and rewrite to the real product page (200) instead of 404
|
|
14
34
|
|
|
15
35
|
## 2.0.78
|
|
16
36
|
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Runtime access to public (`NEXT_PUBLIC_*`) environment variables.
|
|
5
|
+
*
|
|
6
|
+
* Next.js inlines `process.env.NEXT_PUBLIC_*` into the bundle at *build* time.
|
|
7
|
+
* On hosting platforms where the build has no access to the environment (e.g.
|
|
8
|
+
* Akinon Cloud Commerce), those references resolve to `undefined` in the
|
|
9
|
+
* browser. This route reads the variables from the *server runtime* instead —
|
|
10
|
+
* `process.env[name]` is a computed lookup, so webpack never statically inlines
|
|
11
|
+
* it — and hands them back to the client.
|
|
12
|
+
*
|
|
13
|
+
* Only `NEXT_PUBLIC_`-prefixed names are resolvable. These values are public by
|
|
14
|
+
* design (they are shipped to the browser anyway), so nothing secret can leak
|
|
15
|
+
* through here; the prefix check is what keeps server-only secrets unreadable.
|
|
16
|
+
*
|
|
17
|
+
* Query: one or more `env` params, repeated (`?env=A&env=B`) and/or comma
|
|
18
|
+
* separated (`?env=A,B`). Names must include the full prefix. Responds with a
|
|
19
|
+
* `{ [name]: value | null }` map (`null` when the variable is not set).
|
|
20
|
+
*
|
|
21
|
+
* The consuming route file must set `export const dynamic = 'force-dynamic'` so
|
|
22
|
+
* Next never statically caches a build-time (empty) response.
|
|
23
|
+
*
|
|
24
|
+
* @see `@akinon/next/hooks` — `useClientEnv` / `getClientEnv` read from here.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const CLIENT_ENV_NAME = /^NEXT_PUBLIC_[A-Za-z0-9_]+$/;
|
|
28
|
+
|
|
29
|
+
export async function GET(request: NextRequest) {
|
|
30
|
+
try {
|
|
31
|
+
const { searchParams } = new URL(request.url);
|
|
32
|
+
|
|
33
|
+
const names = Array.from(
|
|
34
|
+
new Set(
|
|
35
|
+
searchParams
|
|
36
|
+
.getAll('env')
|
|
37
|
+
.flatMap((value) => value.split(','))
|
|
38
|
+
.map((value) => value.trim())
|
|
39
|
+
.filter(Boolean)
|
|
40
|
+
)
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
if (names.length === 0) {
|
|
44
|
+
return NextResponse.json(
|
|
45
|
+
{ message: 'At least one `env` query parameter is required.' },
|
|
46
|
+
{ status: 400 }
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const invalid = names.filter((name) => !CLIENT_ENV_NAME.test(name));
|
|
51
|
+
|
|
52
|
+
if (invalid.length > 0) {
|
|
53
|
+
return NextResponse.json(
|
|
54
|
+
{
|
|
55
|
+
message:
|
|
56
|
+
'Only NEXT_PUBLIC_-prefixed environment variables can be read.',
|
|
57
|
+
invalid
|
|
58
|
+
},
|
|
59
|
+
{ status: 400 }
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const values = names.reduce<Record<string, string | null>>((acc, name) => {
|
|
64
|
+
acc[name] = process.env[name] ?? null;
|
|
65
|
+
return acc;
|
|
66
|
+
}, {});
|
|
67
|
+
|
|
68
|
+
return NextResponse.json(values, {
|
|
69
|
+
headers: { 'Cache-Control': 'no-store' }
|
|
70
|
+
});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
console.error('Error in client-env API:', error);
|
|
73
|
+
return NextResponse.json(
|
|
74
|
+
{ message: 'Internal server error' },
|
|
75
|
+
{ status: 500 }
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -6,6 +6,7 @@ const findBaseDir = require('../utils/find-base-dir');
|
|
|
6
6
|
|
|
7
7
|
const generateRoutes = () => {
|
|
8
8
|
const baseDir = findBaseDir();
|
|
9
|
+
|
|
9
10
|
const srcDir = path.join(baseDir, 'src');
|
|
10
11
|
const appDir = path.join(srcDir, 'app');
|
|
11
12
|
|
|
@@ -34,8 +35,10 @@ const generateRoutes = () => {
|
|
|
34
35
|
'[segment]',
|
|
35
36
|
'[url]',
|
|
36
37
|
'[theme]',
|
|
37
|
-
'[member_type]'
|
|
38
|
+
'[member_type]',
|
|
39
|
+
'[clienttype]'
|
|
38
40
|
];
|
|
41
|
+
|
|
39
42
|
const skipCatchAllRoutes = ['[...prettyurl]', '[...not_found]'];
|
|
40
43
|
|
|
41
44
|
const walkDirectory = (dir, basePath = '') => {
|
package/data/client/checkout.ts
CHANGED
|
@@ -718,7 +718,6 @@ export const checkoutApi = api.injectEndpoints({
|
|
|
718
718
|
},
|
|
719
719
|
async onQueryStarted(arg, { dispatch, queryFulfilled }) {
|
|
720
720
|
dispatch(setPaymentStepBusy(true));
|
|
721
|
-
dispatch(setCardType(arg));
|
|
722
721
|
await queryFulfilled;
|
|
723
722
|
dispatch(setPaymentStepBusy(false));
|
|
724
723
|
}
|
package/data/client/wishlist.ts
CHANGED
|
@@ -26,6 +26,19 @@ interface GetFavoritesResponse {
|
|
|
26
26
|
results: FavoriteItem[];
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
export interface FavouriteProductIdItem {
|
|
30
|
+
product_id: number;
|
|
31
|
+
favourite_id: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface GetFavouriteProductIdsResponse {
|
|
35
|
+
favourite_products: FavouriteProductIdItem[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface GetFavouriteProductIdsParams {
|
|
39
|
+
productIds: Array<number | string>;
|
|
40
|
+
}
|
|
41
|
+
|
|
29
42
|
interface AddFavoriteResponse {
|
|
30
43
|
pk: number;
|
|
31
44
|
product: number;
|
|
@@ -83,6 +96,14 @@ export const wishlistApi = api.injectEndpoints({
|
|
|
83
96
|
buildClientRequestUrl(wishlist.getFavorites({ page, limit })),
|
|
84
97
|
providesTags: ['Favorite']
|
|
85
98
|
}),
|
|
99
|
+
getFavouriteProductIds: build.query<
|
|
100
|
+
GetFavouriteProductIdsResponse,
|
|
101
|
+
GetFavouriteProductIdsParams
|
|
102
|
+
>({
|
|
103
|
+
query: ({ productIds }) =>
|
|
104
|
+
buildClientRequestUrl(wishlist.getFavouriteProductIds(productIds)),
|
|
105
|
+
providesTags: ['Favorite']
|
|
106
|
+
}),
|
|
86
107
|
addFavorite: build.mutation<AddFavoriteResponse, number>({
|
|
87
108
|
query: (productPk: number) => ({
|
|
88
109
|
url: buildClientRequestUrl(wishlist.addFavorite, {
|
|
@@ -196,6 +217,7 @@ export const wishlistApi = api.injectEndpoints({
|
|
|
196
217
|
|
|
197
218
|
export const {
|
|
198
219
|
useGetFavoritesQuery,
|
|
220
|
+
useGetFavouriteProductIdsQuery,
|
|
199
221
|
useAddFavoriteMutation,
|
|
200
222
|
useRemoveFavoriteMutation,
|
|
201
223
|
useAddStockAlertMutation,
|
package/data/server/category.ts
CHANGED
|
@@ -8,6 +8,8 @@ import { parse } from 'lossless-json';
|
|
|
8
8
|
import logger from '../../utils/log';
|
|
9
9
|
import { headers as nHeaders } from 'next/headers';
|
|
10
10
|
import { ServerVariables } from '../../utils/server-variables';
|
|
11
|
+
import { optimizeCategoryResponse } from '../../utils/payload-optimizer';
|
|
12
|
+
import settings from 'settings';
|
|
11
13
|
|
|
12
14
|
function getCategoryDataHandler(
|
|
13
15
|
pk: number,
|
|
@@ -81,7 +83,7 @@ function getCategoryDataHandler(
|
|
|
81
83
|
};
|
|
82
84
|
}
|
|
83
85
|
|
|
84
|
-
export const getCategoryData = ({
|
|
86
|
+
export const getCategoryData = async ({
|
|
85
87
|
pk,
|
|
86
88
|
searchParams,
|
|
87
89
|
headers,
|
|
@@ -96,7 +98,7 @@ export const getCategoryData = ({
|
|
|
96
98
|
}) => {
|
|
97
99
|
searchParams = normalizeSearchParams(searchParams);
|
|
98
100
|
|
|
99
|
-
|
|
101
|
+
const result = await Cache.wrap(
|
|
100
102
|
CacheKey.Category(pk, searchParams, headers),
|
|
101
103
|
locale,
|
|
102
104
|
getCategoryDataHandler(pk, locale, currency, searchParams, headers),
|
|
@@ -105,6 +107,16 @@ export const getCategoryData = ({
|
|
|
105
107
|
compressed: true
|
|
106
108
|
}
|
|
107
109
|
);
|
|
110
|
+
|
|
111
|
+
if (settings.payloadOptimization?.enabled && result?.data) {
|
|
112
|
+
try {
|
|
113
|
+
return { ...result, data: optimizeCategoryResponse(result.data, settings.payloadOptimization) };
|
|
114
|
+
} catch (e) {
|
|
115
|
+
logger.error('Payload optimization failed for category', { pk, error: (e as Error).message });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return result;
|
|
108
120
|
};
|
|
109
121
|
|
|
110
122
|
function getCategoryBySlugDataHandler(
|
package/data/server/list.ts
CHANGED
|
@@ -7,6 +7,8 @@ import appFetch, { FetchResponseType } from '../../utils/app-fetch';
|
|
|
7
7
|
import { parse } from 'lossless-json';
|
|
8
8
|
import logger from '../../utils/log';
|
|
9
9
|
import { ServerVariables } from '../../utils/server-variables';
|
|
10
|
+
import { optimizeCategoryResponse } from '../../utils/payload-optimizer';
|
|
11
|
+
import settings from 'settings';
|
|
10
12
|
|
|
11
13
|
const getListDataHandler = (
|
|
12
14
|
locale,
|
|
@@ -69,7 +71,7 @@ export const getListData = async ({
|
|
|
69
71
|
}) => {
|
|
70
72
|
searchParams = normalizeSearchParams(searchParams);
|
|
71
73
|
|
|
72
|
-
|
|
74
|
+
const result = await Cache.wrap(
|
|
73
75
|
CacheKey.List(searchParams, headers),
|
|
74
76
|
locale,
|
|
75
77
|
getListDataHandler(locale, currency, searchParams, headers),
|
|
@@ -78,4 +80,14 @@ export const getListData = async ({
|
|
|
78
80
|
compressed: true
|
|
79
81
|
}
|
|
80
82
|
);
|
|
83
|
+
|
|
84
|
+
if (settings.payloadOptimization?.enabled && result) {
|
|
85
|
+
try {
|
|
86
|
+
return optimizeCategoryResponse(result, settings.payloadOptimization);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
logger.error('Payload optimization failed for list', { error: (e as Error).message });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return result;
|
|
81
93
|
};
|
package/data/server/product.ts
CHANGED
|
@@ -5,6 +5,8 @@ import appFetch from '../../utils/app-fetch';
|
|
|
5
5
|
import { normalizeSearchParams } from '../../utils/normalize-search-params';
|
|
6
6
|
import { ServerVariables } from '../../utils/server-variables';
|
|
7
7
|
import logger from '../../utils/log';
|
|
8
|
+
import { optimizeProductResponse } from '../../utils/payload-optimizer';
|
|
9
|
+
import settings from 'settings';
|
|
8
10
|
|
|
9
11
|
type GetProduct = {
|
|
10
12
|
pk: number | string;
|
|
@@ -166,5 +168,13 @@ export const getProductData = async ({
|
|
|
166
168
|
throw error;
|
|
167
169
|
}
|
|
168
170
|
|
|
171
|
+
if (settings.payloadOptimization?.enabled && result?.data) {
|
|
172
|
+
try {
|
|
173
|
+
return { ...result, data: optimizeProductResponse(result.data, settings.payloadOptimization) };
|
|
174
|
+
} catch (e) {
|
|
175
|
+
logger.error('Payload optimization failed for product', { pk, error: (e as Error).message });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
169
179
|
return result;
|
|
170
180
|
};
|
|
@@ -5,6 +5,9 @@ import { generateCommerceSearchParams } from '../../utils';
|
|
|
5
5
|
import { normalizeSearchParams } from '../../utils/normalize-search-params';
|
|
6
6
|
import appFetch from '../../utils/app-fetch';
|
|
7
7
|
import { ServerVariables } from '../../utils/server-variables';
|
|
8
|
+
import { optimizeCategoryResponse } from '../../utils/payload-optimizer';
|
|
9
|
+
import logger from '../../utils/log';
|
|
10
|
+
import settings from 'settings';
|
|
8
11
|
|
|
9
12
|
const getSpecialPageDataHandler = (
|
|
10
13
|
pk: number,
|
|
@@ -48,7 +51,7 @@ export const getSpecialPageData = async ({
|
|
|
48
51
|
}) => {
|
|
49
52
|
searchParams = normalizeSearchParams(searchParams);
|
|
50
53
|
|
|
51
|
-
|
|
54
|
+
const result = await Cache.wrap(
|
|
52
55
|
CacheKey.SpecialPage(pk, searchParams, headers),
|
|
53
56
|
locale,
|
|
54
57
|
getSpecialPageDataHandler(pk, locale, currency, searchParams, headers),
|
|
@@ -57,4 +60,14 @@ export const getSpecialPageData = async ({
|
|
|
57
60
|
compressed: true
|
|
58
61
|
}
|
|
59
62
|
);
|
|
63
|
+
|
|
64
|
+
if (settings.payloadOptimization?.enabled && result) {
|
|
65
|
+
try {
|
|
66
|
+
return optimizeCategoryResponse(result, settings.payloadOptimization);
|
|
67
|
+
} catch (e) {
|
|
68
|
+
logger.error('Payload optimization failed for special-page', { pk, error: (e as Error).message });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return result;
|
|
60
73
|
};
|
package/data/server/widget.ts
CHANGED
|
@@ -1,192 +1,19 @@
|
|
|
1
1
|
import { Cache, CacheKey } from '../../lib/cache';
|
|
2
2
|
import 'server-only';
|
|
3
|
-
import { draftMode } from 'next/headers';
|
|
4
3
|
import { CacheOptions, WidgetResultType, WidgetSchemaType } from '../../types';
|
|
5
4
|
import appFetch from '../../utils/app-fetch';
|
|
6
5
|
import { widgets } from '../urls';
|
|
7
6
|
import { ServerVariables } from '../../utils/server-variables';
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
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
|
+
import { optimizeWidgetResponse } from '../../utils/payload-optimizer';
|
|
8
|
+
import logger from '../../utils/log';
|
|
9
|
+
import settings from 'settings';
|
|
182
10
|
|
|
183
11
|
const getWidgetDataHandler =
|
|
184
12
|
(
|
|
185
13
|
slug: string,
|
|
186
14
|
locale: string,
|
|
187
15
|
currency: string,
|
|
188
|
-
headers?: Record<string, string
|
|
189
|
-
next?: { revalidate: number }
|
|
16
|
+
headers?: Record<string, string>
|
|
190
17
|
) =>
|
|
191
18
|
async () => {
|
|
192
19
|
if (!slug) {
|
|
@@ -198,20 +25,13 @@ const getWidgetDataHandler =
|
|
|
198
25
|
locale,
|
|
199
26
|
currency,
|
|
200
27
|
init: {
|
|
201
|
-
headers
|
|
202
|
-
...(next ? { next } : {})
|
|
28
|
+
headers
|
|
203
29
|
}
|
|
204
30
|
});
|
|
205
31
|
};
|
|
206
32
|
|
|
207
33
|
const getWidgetSchemaDataHandler =
|
|
208
|
-
(
|
|
209
|
-
widgetSlug: string,
|
|
210
|
-
locale: string,
|
|
211
|
-
currency: string,
|
|
212
|
-
next?: { revalidate: number }
|
|
213
|
-
) =>
|
|
214
|
-
async () => {
|
|
34
|
+
(widgetSlug: string, locale: string, currency: string) => async () => {
|
|
215
35
|
if (!widgetSlug) {
|
|
216
36
|
return null;
|
|
217
37
|
}
|
|
@@ -219,8 +39,7 @@ const getWidgetSchemaDataHandler =
|
|
|
219
39
|
return await appFetch({
|
|
220
40
|
url: widgets.getWidgetSchema(widgetSlug),
|
|
221
41
|
locale,
|
|
222
|
-
currency
|
|
223
|
-
init: next ? { next } : {}
|
|
42
|
+
currency
|
|
224
43
|
});
|
|
225
44
|
};
|
|
226
45
|
|
|
@@ -237,36 +56,7 @@ export const getWidgetData = async <T>({
|
|
|
237
56
|
cacheOptions?: CacheOptions;
|
|
238
57
|
headers?: Record<string, string>;
|
|
239
58
|
}): Promise<WidgetResultType<T>> => {
|
|
240
|
-
const
|
|
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
|
-
|
|
269
|
-
return Cache.wrap(
|
|
59
|
+
const result = await Cache.wrap(
|
|
270
60
|
CacheKey.Widget(slug),
|
|
271
61
|
locale,
|
|
272
62
|
getWidgetDataHandler(slug, locale, currency, headers),
|
|
@@ -275,16 +65,20 @@ export const getWidgetData = async <T>({
|
|
|
275
65
|
...cacheOptions
|
|
276
66
|
}
|
|
277
67
|
);
|
|
68
|
+
|
|
69
|
+
if (settings.payloadOptimization?.enabled && result) {
|
|
70
|
+
try {
|
|
71
|
+
return optimizeWidgetResponse(result, settings.payloadOptimization) as WidgetResultType<T>;
|
|
72
|
+
} catch (e) {
|
|
73
|
+
logger.error('Payload optimization failed for widget', { slug, error: (e as Error).message });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return result as WidgetResultType<T>;
|
|
278
78
|
};
|
|
279
79
|
|
|
280
80
|
const getCollectionWidgetDataHandler =
|
|
281
|
-
(
|
|
282
|
-
slug: string,
|
|
283
|
-
locale: string,
|
|
284
|
-
currency: string,
|
|
285
|
-
next?: { revalidate: number }
|
|
286
|
-
) =>
|
|
287
|
-
async () => {
|
|
81
|
+
(slug: string, locale: string, currency: string) => async () => {
|
|
288
82
|
if (!slug) {
|
|
289
83
|
return null;
|
|
290
84
|
}
|
|
@@ -292,8 +86,7 @@ const getCollectionWidgetDataHandler =
|
|
|
292
86
|
return await appFetch({
|
|
293
87
|
url: widgets.getCollectionWidget(slug),
|
|
294
88
|
locale,
|
|
295
|
-
currency
|
|
296
|
-
init: next ? { next } : {}
|
|
89
|
+
currency
|
|
297
90
|
});
|
|
298
91
|
};
|
|
299
92
|
|
|
@@ -308,24 +101,6 @@ export const getCollectionWidgetData = async <T>({
|
|
|
308
101
|
currency?: string;
|
|
309
102
|
cacheOptions?: CacheOptions;
|
|
310
103
|
}): 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
|
-
|
|
329
104
|
return Cache.wrap(
|
|
330
105
|
CacheKey.Widget(`collection:${slug}`),
|
|
331
106
|
locale,
|
|
@@ -348,26 +123,6 @@ export const getWidgetSchemaData = async <T>({
|
|
|
348
123
|
currency?: string;
|
|
349
124
|
cacheOptions?: CacheOptions;
|
|
350
125
|
}): 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
|
-
|
|
371
126
|
return Cache.wrap(
|
|
372
127
|
CacheKey.WidgetSchema(widgetSlug),
|
|
373
128
|
locale,
|