@akinon/next 2.0.149-rc.0 → 2.0.150-beta.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.
@@ -36,21 +36,6 @@ import { LocaleUrlStrategy } from '../../localization';
36
36
  import { showMobile3dIframe } from '../../utils/mobile-3d-iframe';
37
37
  import { showRedirectionIframe } from '../../utils/redirection-iframe';
38
38
 
39
- const IFRAME_REDIRECTION_KEY = 'pz-iframe-redirection-active';
40
-
41
- const isIframeRedirectionActive = () =>
42
- typeof window !== 'undefined' &&
43
- sessionStorage.getItem(IFRAME_REDIRECTION_KEY) === 'true';
44
-
45
- const setIframeRedirectionActive = (active: boolean) => {
46
- if (typeof window === 'undefined') return;
47
- if (active) {
48
- sessionStorage.setItem(IFRAME_REDIRECTION_KEY, 'true');
49
- } else {
50
- sessionStorage.removeItem(IFRAME_REDIRECTION_KEY);
51
- }
52
- };
53
-
54
39
  interface CheckoutResult {
55
40
  payload: {
56
41
  errors?: Record<string, string[]>;
@@ -87,7 +72,7 @@ export const redirectUrlMiddleware: Middleware = () => {
87
72
  const result = next(action) as CheckoutResult;
88
73
  const redirectUrl = result?.payload?.redirect_url;
89
74
 
90
- if (redirectUrl && !isIframeRedirectionActive()) {
75
+ if (redirectUrl) {
91
76
  const currentLocale = getCookie('pz-locale');
92
77
 
93
78
  let url = redirectUrl;
@@ -117,15 +102,8 @@ export const contextListMiddleware: Middleware = ({
117
102
  const { isMobileApp, userPhoneNumber } = getState().root;
118
103
  const result = next(action) as CheckoutResult;
119
104
  const preOrder = result?.payload?.pre_order;
120
- const act = action as MiddlewareAction;
121
105
 
122
106
  if (result?.payload?.context_list) {
123
- const endpointName = act.meta?.arg?.endpointName;
124
- const isBinNumberResponse = endpointName === 'setBinNumber';
125
- const hasCardTypeInContextList = result.payload.context_list.some(
126
- (ctx) => ctx.page_context.card_type
127
- );
128
-
129
107
  result.payload.context_list.forEach((context) => {
130
108
  const redirectUrl = context.page_context.redirect_url;
131
109
  const isIframe = context.page_context.is_iframe ?? false;
@@ -159,7 +137,6 @@ export const contextListMiddleware: Middleware = ({
159
137
  if (isMobileDevice && isIframePaymentOptionIncluded) {
160
138
  showMobile3dIframe(urlObj.toString());
161
139
  } else if (isIframe) {
162
- setIframeRedirectionActive(true);
163
140
  showRedirectionIframe(urlObj.toString());
164
141
  } else {
165
142
  window.location.href = urlObj.toString();
@@ -236,34 +213,15 @@ export const contextListMiddleware: Middleware = ({
236
213
  (ctx) => ctx.page_name === 'DeliveryOptionSelectionPage'
237
214
  )
238
215
  ) {
239
- const isCreditCardPayment =
240
- preOrder?.payment_option?.payment_type === 'credit_card' ||
241
- preOrder?.payment_option?.payment_type === 'masterpass';
242
-
243
216
  if (context.page_context.card_type) {
244
217
  dispatch(setCardType(context.page_context.card_type));
245
- } else if (
246
- isCreditCardPayment &&
247
- isBinNumberResponse &&
248
- !hasCardTypeInContextList
249
- ) {
250
- dispatch(setCardType(null));
251
- dispatch(setInstallmentOptions([]));
252
218
  }
253
219
 
254
220
  if (
255
221
  context.page_context.installments &&
256
222
  preOrder?.payment_option?.payment_type !== 'masterpass_rest'
257
223
  ) {
258
- if (
259
- !isCreditCardPayment ||
260
- context.page_context.card_type ||
261
- hasCardTypeInContextList
262
- ) {
263
- dispatch(
264
- setInstallmentOptions(context.page_context.installments)
265
- );
266
- }
224
+ dispatch(setInstallmentOptions(context.page_context.installments));
267
225
  }
268
226
  }
269
227
 
@@ -14,17 +14,9 @@ export const installmentOptionMiddleware: Middleware = ({
14
14
  return result;
15
15
  }
16
16
 
17
- const { installmentOptions, cardType } = getState().checkout;
17
+ const { installmentOptions } = getState().checkout;
18
18
  const { endpoints: apiEndpoints } = checkoutApi;
19
19
 
20
- const isCreditCardPayment =
21
- preOrder?.payment_option?.payment_type === 'credit_card' ||
22
- preOrder?.payment_option?.payment_type === 'masterpass';
23
-
24
- if (isCreditCardPayment && !cardType) {
25
- return result;
26
- }
27
-
28
20
  if (
29
21
  !preOrder?.installment &&
30
22
  preOrder?.payment_option?.payment_type !== 'saved_card' &&
package/types/index.ts CHANGED
@@ -85,12 +85,6 @@ export interface Settings {
85
85
  };
86
86
  usePrettyUrlRoute?: boolean;
87
87
  commerceUrl: string;
88
- /**
89
- * This option allows you to track Sentry events on the client side, in addition to server and edge environments.
90
- *
91
- * It overrides process.env.NEXT_PUBLIC_SENTRY_DSN and process.env.SENTRY_DSN.
92
- */
93
- sentryDsn?: string;
94
88
  /**
95
89
  * CSRF cookie hardening settings.
96
90
  *
@@ -242,7 +236,6 @@ export interface Settings {
242
236
  separator?: string;
243
237
  segments: PzSegmentDefinition[];
244
238
  };
245
- payloadOptimization?: import('../utils/payload-optimizer').PayloadOptimizationConfig;
246
239
  }
247
240
 
248
241
  export interface CacheOptions {
@@ -302,9 +295,7 @@ export interface PzSegmentsConfig {
302
295
  }
303
296
 
304
297
  // Search params type compatible with both Next.js resolved searchParams and URLSearchParams
305
- export type SearchParams =
306
- | Record<string, string | string[] | undefined>
307
- | URLSearchParams;
298
+ export type SearchParams = Record<string, string | string[] | undefined> | URLSearchParams;
308
299
 
309
300
  // Raw Next 16 server prop shape, used at the middleware/HOC boundary before normalization
310
301
  export type RawSearchParams = Record<string, string | string[] | undefined>;
@@ -337,16 +328,14 @@ export interface RootLayoutProps<T = any> extends LayoutProps<T> {
337
328
 
338
329
  // Async versions for Next.js 16 generateMetadata and internal use
339
330
  export interface AsyncPageProps<T = any> {
340
- params: Promise<
341
- T & {
342
- pz?: string;
343
- commerce?: string;
344
- locale?: string;
345
- currency?: string;
346
- url?: string;
347
- [key: string]: any;
348
- }
349
- >;
331
+ params: Promise<T & {
332
+ pz?: string;
333
+ commerce?: string;
334
+ locale?: string;
335
+ currency?: string;
336
+ url?: string;
337
+ [key: string]: any;
338
+ }>;
350
339
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
351
340
  }
352
341
 
package/utils/csrf.ts CHANGED
@@ -46,7 +46,7 @@ export function getCsrfCookieFlags(): CsrfCookieFlags {
46
46
 
47
47
  return {
48
48
  httpOnly,
49
- secure: process.env.NODE_ENV === 'production',
49
+ secure: httpOnly && process.env.NODE_ENV === 'production',
50
50
  sameSite: 'lax'
51
51
  };
52
52
  }
package/with-pz-config.js CHANGED
@@ -30,10 +30,6 @@ const defaultConfig = {
30
30
  {
31
31
  protocol: 'https',
32
32
  hostname: '**.akinoncdn.com'
33
- },
34
- {
35
- protocol: 'https',
36
- hostname: '**.akinoncloudcdn.com'
37
33
  }
38
34
  ]
39
35
  },
@@ -78,8 +74,7 @@ const defaultConfig = {
78
74
  acc[`@akinon/${plugin}`] = false;
79
75
  return acc;
80
76
  }, {}),
81
- translations: false,
82
- '@opentelemetry/exporter-jaeger': false
77
+ translations: false
83
78
  };
84
79
  // Ensure webpack can resolve deps from the app's node_modules when
85
80
  // compiling transpiled packages (e.g. @akinon/next) whose imports
package/api/client-env.ts DELETED
@@ -1,78 +0,0 @@
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
- }
@@ -1,265 +0,0 @@
1
- 'use client';
2
-
3
- import { useEffect, useState } from 'react';
4
-
5
- /**
6
- * Runtime access to public (`NEXT_PUBLIC_*`) environment variables from Client
7
- * Components.
8
- *
9
- * `process.env.NEXT_PUBLIC_*` is inlined at *build* time, so on platforms where
10
- * the build has no environment (e.g. Akinon Cloud Commerce) it resolves to
11
- * `undefined` in the browser. These helpers read the value from the server
12
- * runtime through the `/api/client-env` route handler instead
13
- * (`@akinon/next/api/client-env`).
14
- *
15
- * Always pass the full variable name, including the `NEXT_PUBLIC_` prefix:
16
- *
17
- * ```tsx
18
- * // inside a Client Component
19
- * const { value, isLoading } = useClientEnv('NEXT_PUBLIC_MAP_API_KEY');
20
- *
21
- * // imperative (event handlers, third-party init, ...)
22
- * const key = await getClientEnv('NEXT_PUBLIC_MAP_API_KEY');
23
- * ```
24
- *
25
- * Server Components do not need this — read the value with computed access
26
- * (`process.env['NEXT_PUBLIC_MAP_API_KEY']`) so it is not build-time inlined.
27
- */
28
-
29
- const ENDPOINT = '/api/client-env';
30
-
31
- // Shared across every caller so each variable is fetched at most once per page
32
- // load, no matter how many components ask for it.
33
- const cache = new Map<string, string | null>();
34
- const inflight = new Map<string, Promise<string | null>>();
35
-
36
- function request(names: string[]): void {
37
- const pending = names.filter(
38
- (name) => !cache.has(name) && !inflight.has(name)
39
- );
40
-
41
- if (pending.length === 0) return;
42
-
43
- const query = pending
44
- .map((name) => `env=${encodeURIComponent(name)}`)
45
- .join('&');
46
-
47
- const response = fetch(`${ENDPOINT}?${query}`, {
48
- headers: { Accept: 'application/json' }
49
- })
50
- .then((res) => {
51
- if (!res.ok) {
52
- throw new Error(`Failed to load client env (status ${res.status}).`);
53
- }
54
- return res.json() as Promise<Record<string, string | null>>;
55
- })
56
- .then((data) => {
57
- pending.forEach((name) => cache.set(name, data?.[name] ?? null));
58
- });
59
-
60
- // One in-flight entry per name so concurrent callers dedupe. On failure the
61
- // entry is cleared (not cached) so a later render can retry.
62
- pending.forEach((name) => {
63
- inflight.set(
64
- name,
65
- response
66
- .then(() => cache.get(name) ?? null)
67
- .finally(() => inflight.delete(name))
68
- );
69
- });
70
- }
71
-
72
- function resolve(name: string): Promise<string | null> {
73
- if (cache.has(name)) return Promise.resolve(cache.get(name) ?? null);
74
- return inflight.get(name) ?? Promise.resolve(null);
75
- }
76
-
77
- /**
78
- * Read a single public (`NEXT_PUBLIC_*`) environment variable at runtime,
79
- * outside React (event handlers, third-party SDK init, …). Cached and
80
- * deduplicated across callers.
81
- *
82
- * @param name - Full variable name, including the `NEXT_PUBLIC_` prefix.
83
- * @returns The runtime value, or `null` when the variable is unset. Rejects if
84
- * the request fails, so wrap direct calls in `try`/`catch`. A failed request is
85
- * not cached — a later call retries.
86
- *
87
- * @example
88
- * ```tsx
89
- * import { getClientEnv } from '@akinon/next/hooks'
90
- *
91
- * const handleShare = async () => {
92
- * const baseUrl = await getClientEnv('NEXT_PUBLIC_URL')
93
- * navigator.clipboard.writeText(`${baseUrl}/product/123`)
94
- * }
95
- * ```
96
- */
97
- export async function getClientEnv(name: string): Promise<string | null> {
98
- request([name]);
99
- return resolve(name);
100
- }
101
-
102
- /**
103
- * Read several public (`NEXT_PUBLIC_*`) environment variables at runtime in a
104
- * single request, outside React.
105
- *
106
- * @param names - Full variable names, each including the `NEXT_PUBLIC_` prefix.
107
- * @returns A `{ [name]: value | null }` map. Rejects if the request fails.
108
- *
109
- * @example
110
- * ```ts
111
- * import { getClientEnvs } from '@akinon/next/hooks'
112
- *
113
- * const env = await getClientEnvs(['NEXT_PUBLIC_GTM_KEY', 'NEXT_PUBLIC_URL'])
114
- * // env['NEXT_PUBLIC_URL']
115
- * ```
116
- */
117
- export async function getClientEnvs(
118
- names: string[]
119
- ): Promise<Record<string, string | null>> {
120
- request(names);
121
- const values = await Promise.all(names.map((name) => resolve(name)));
122
- return names.reduce<Record<string, string | null>>((acc, name, index) => {
123
- acc[name] = values[index];
124
- return acc;
125
- }, {});
126
- }
127
-
128
- /**
129
- * Read a single public (`NEXT_PUBLIC_*`) environment variable at runtime from a
130
- * Client Component.
131
- *
132
- * @param name - Full variable name, including the `NEXT_PUBLIC_` prefix.
133
- * @returns `{ value, isLoading, error }`. `value` is `null` while loading, when
134
- * the variable is unset, or on failure.
135
- *
136
- * @example
137
- * ```tsx
138
- * 'use client'
139
- * import { useClientEnv } from '@akinon/next/hooks'
140
- *
141
- * export const StoreMap = () => {
142
- * const { value: mapApiKey, isLoading } = useClientEnv('NEXT_PUBLIC_MAP_API_KEY')
143
- *
144
- * if (isLoading) return <Spinner />
145
- * if (!mapApiKey) return null
146
- *
147
- * return <GoogleMap apiKey={mapApiKey} />
148
- * }
149
- * ```
150
- */
151
- export function useClientEnv(name: string) {
152
- const [value, setValue] = useState<string | null>(
153
- () => cache.get(name) ?? null
154
- );
155
- const [isLoading, setIsLoading] = useState(() => !cache.has(name));
156
- const [error, setError] = useState<Error | null>(null);
157
-
158
- useEffect(() => {
159
- let active = true;
160
-
161
- if (cache.has(name)) {
162
- setValue(cache.get(name) ?? null);
163
- setIsLoading(false);
164
- setError(null);
165
- return;
166
- }
167
-
168
- setIsLoading(true);
169
- setError(null);
170
-
171
- getClientEnv(name)
172
- .then((resolved) => {
173
- if (!active) return;
174
- setValue(resolved);
175
- setIsLoading(false);
176
- })
177
- .catch((err) => {
178
- if (!active) return;
179
- setError(err instanceof Error ? err : new Error(String(err)));
180
- setIsLoading(false);
181
- });
182
-
183
- return () => {
184
- active = false;
185
- };
186
- }, [name]);
187
-
188
- return { value, isLoading, error };
189
- }
190
-
191
- /**
192
- * Read several public (`NEXT_PUBLIC_*`) environment variables at runtime in a
193
- * single request from a Client Component.
194
- *
195
- * @param names - Full variable names, each including the `NEXT_PUBLIC_` prefix.
196
- * @returns `{ values, isLoading, error }` where `values` is a
197
- * `{ [name]: value | null }` map.
198
- *
199
- * @example
200
- * ```tsx
201
- * 'use client'
202
- * import { useClientEnvs } from '@akinon/next/hooks'
203
- *
204
- * const { values, isLoading } = useClientEnvs([
205
- * 'NEXT_PUBLIC_GTM_KEY',
206
- * 'NEXT_PUBLIC_URL'
207
- * ])
208
- *
209
- * const gtmKey = values['NEXT_PUBLIC_GTM_KEY']
210
- * ```
211
- */
212
- export function useClientEnvs(names: string[]) {
213
- // Stable serialization so the effect re-runs only when the set changes, not
214
- // on every render (a new array identity would otherwise loop it forever).
215
- const key = names.join(',');
216
-
217
- const [values, setValues] = useState<Record<string, string | null>>(() => {
218
- const initial: Record<string, string | null> = {};
219
- names.forEach((name) => {
220
- if (cache.has(name)) initial[name] = cache.get(name) ?? null;
221
- });
222
- return initial;
223
- });
224
- const [isLoading, setIsLoading] = useState(
225
- () => !names.every((name) => cache.has(name))
226
- );
227
- const [error, setError] = useState<Error | null>(null);
228
-
229
- useEffect(() => {
230
- let active = true;
231
- const list = key ? key.split(',') : [];
232
-
233
- if (list.every((name) => cache.has(name))) {
234
- const resolved: Record<string, string | null> = {};
235
- list.forEach((name) => (resolved[name] = cache.get(name) ?? null));
236
- setValues(resolved);
237
- setIsLoading(false);
238
- setError(null);
239
- return;
240
- }
241
-
242
- setIsLoading(true);
243
- setError(null);
244
-
245
- getClientEnvs(list)
246
- .then((resolved) => {
247
- if (!active) return;
248
- setValues(resolved);
249
- setIsLoading(false);
250
- })
251
- .catch((err) => {
252
- if (!active) return;
253
- setError(err instanceof Error ? err : new Error(String(err)));
254
- setIsLoading(false);
255
- });
256
-
257
- return () => {
258
- active = false;
259
- };
260
- // `key` is the stable serialization of `names`.
261
- // eslint-disable-next-line react-hooks/exhaustive-deps
262
- }, [key]);
263
-
264
- return { values, isLoading, error };
265
- }