@decocms/apps 0.22.0 → 0.23.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/package.json +1 -1
- package/vtex/client.ts +27 -5
- package/vtex/invoke.ts +9 -1
- package/vtex/middleware.ts +10 -1
- package/vtex/utils/cookies.ts +62 -21
- package/vtex/utils/proxy.ts +19 -9
package/package.json
CHANGED
package/vtex/client.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import { type FetchCacheOptions, fetchWithCache } from "./utils/fetchCache";
|
|
7
|
+
import { SEGMENT_COOKIE_NAME, parseSegment } from "./utils/segment";
|
|
7
8
|
|
|
8
9
|
// ---------------------------------------------------------------------------
|
|
9
10
|
// URL sanitization (ported from deco-cx/apps vtex/utils/fetchVTEX.ts)
|
|
@@ -176,6 +177,22 @@ function authHeaders(): Record<string, string> {
|
|
|
176
177
|
return headers;
|
|
177
178
|
}
|
|
178
179
|
|
|
180
|
+
/**
|
|
181
|
+
* Read regionId from the current request's vtex_segment cookie.
|
|
182
|
+
* Returns null when no cookie provider is registered or no regionId is set.
|
|
183
|
+
*/
|
|
184
|
+
function extractRegionIdFromCookies(): string | null {
|
|
185
|
+
if (!_getCookieHeader) return null;
|
|
186
|
+
const cookies = _getCookieHeader();
|
|
187
|
+
if (!cookies) return null;
|
|
188
|
+
const match = cookies.match(
|
|
189
|
+
new RegExp(`(?:^|;\\s*)${SEGMENT_COOKIE_NAME}=([^;]+)`),
|
|
190
|
+
);
|
|
191
|
+
if (!match?.[1]) return null;
|
|
192
|
+
const segment = parseSegment(match[1]);
|
|
193
|
+
return segment?.regionId ?? null;
|
|
194
|
+
}
|
|
195
|
+
|
|
179
196
|
export async function vtexFetchResponse(
|
|
180
197
|
path: string,
|
|
181
198
|
init?: RequestInit,
|
|
@@ -293,7 +310,7 @@ export async function vtexFetchWithCookies<T>(
|
|
|
293
310
|
export async function intelligentSearch<T>(
|
|
294
311
|
path: string,
|
|
295
312
|
params?: Record<string, string>,
|
|
296
|
-
opts?: { cookieHeader?: string; locale?: string },
|
|
313
|
+
opts?: { cookieHeader?: string; locale?: string; regionId?: string },
|
|
297
314
|
): Promise<T> {
|
|
298
315
|
const url = new URL(`${isUrl()}${path}`);
|
|
299
316
|
if (params) {
|
|
@@ -309,6 +326,11 @@ export async function intelligentSearch<T>(
|
|
|
309
326
|
url.searchParams.set("locale", locale);
|
|
310
327
|
}
|
|
311
328
|
|
|
329
|
+
const regionId = opts?.regionId ?? extractRegionIdFromCookies();
|
|
330
|
+
if (regionId) {
|
|
331
|
+
url.searchParams.set("regionId", regionId);
|
|
332
|
+
}
|
|
333
|
+
|
|
312
334
|
const headers: Record<string, string> = { ...authHeaders() };
|
|
313
335
|
if (opts?.cookieHeader) {
|
|
314
336
|
headers.cookie = opts.cookieHeader;
|
|
@@ -316,8 +338,6 @@ export async function intelligentSearch<T>(
|
|
|
316
338
|
|
|
317
339
|
const fullUrl = url.toString();
|
|
318
340
|
|
|
319
|
-
// IS GET requests go through SWR cache (3 min TTL via status-based defaults).
|
|
320
|
-
// The doFetch callback throws on non-ok responses, so null is never returned.
|
|
321
341
|
return fetchWithCache<T>(fullUrl, async () => {
|
|
322
342
|
const response = await _fetch(fullUrl, { headers });
|
|
323
343
|
if (!response.ok) {
|
|
@@ -463,13 +483,15 @@ export function initVtexFromBlocks(blocks: Record<string, any>) {
|
|
|
463
483
|
console.warn("[VTEX] No vtex.json block found.");
|
|
464
484
|
return;
|
|
465
485
|
}
|
|
486
|
+
const appKey = typeof vtexBlock.appKey === "string" ? vtexBlock.appKey : undefined;
|
|
487
|
+
const appToken = typeof vtexBlock.appToken === "string" ? vtexBlock.appToken : undefined;
|
|
466
488
|
configureVtex({
|
|
467
489
|
account: vtexBlock.account,
|
|
468
490
|
publicUrl: vtexBlock.publicUrl,
|
|
469
491
|
salesChannel: vtexBlock.salesChannel || "1",
|
|
470
492
|
locale: vtexBlock.locale || vtexBlock.defaultLocale,
|
|
471
|
-
appKey
|
|
472
|
-
appToken
|
|
493
|
+
appKey,
|
|
494
|
+
appToken,
|
|
473
495
|
country: vtexBlock.country,
|
|
474
496
|
domain: vtexBlock.domain,
|
|
475
497
|
});
|
package/vtex/invoke.ts
CHANGED
|
@@ -42,7 +42,7 @@ import {
|
|
|
42
42
|
type UploadAttachmentOpts,
|
|
43
43
|
type CreateDocumentResult,
|
|
44
44
|
} from "./actions/masterData";
|
|
45
|
-
import { createSession } from "./actions/session";
|
|
45
|
+
import { createSession, editSession, type SessionData } from "./actions/session";
|
|
46
46
|
import { subscribe, type SubscribeProps } from "./actions/newsletter";
|
|
47
47
|
import { notifyMe, type NotifyMeProps } from "./actions/misc";
|
|
48
48
|
import type { OrderForm } from "./types";
|
|
@@ -168,6 +168,14 @@ export const invoke = {
|
|
|
168
168
|
{ unwrap: true },
|
|
169
169
|
),
|
|
170
170
|
|
|
171
|
+
editSession: createInvokeFn(
|
|
172
|
+
(input: { public: Record<string, { value: string }> }) =>
|
|
173
|
+
editSession(input.public),
|
|
174
|
+
{ unwrap: true },
|
|
175
|
+
) as unknown as (ctx: {
|
|
176
|
+
data: { public: Record<string, { value: string }> };
|
|
177
|
+
}) => Promise<SessionData>,
|
|
178
|
+
|
|
171
179
|
// -- MasterData -------------------------------------------------------
|
|
172
180
|
|
|
173
181
|
createDocument: createInvokeFn(
|
package/vtex/middleware.ts
CHANGED
|
@@ -52,6 +52,12 @@ export interface VtexRequestContext {
|
|
|
52
52
|
email?: string;
|
|
53
53
|
/** Sales channel derived from segment. */
|
|
54
54
|
salesChannel: string;
|
|
55
|
+
/**
|
|
56
|
+
* VTEX region ID from the segment cookie.
|
|
57
|
+
* Present when the user has set a postal code (CEP) for regionalization.
|
|
58
|
+
* Null when no region is set (anonymous default segment).
|
|
59
|
+
*/
|
|
60
|
+
regionId: string | null;
|
|
55
61
|
/** Whether this request carries price tables (B2B). */
|
|
56
62
|
hasCustomPricing: boolean;
|
|
57
63
|
/** Intelligent Search session cookie. */
|
|
@@ -123,6 +129,7 @@ export function extractVtexContext(request: Request): VtexRequestContext {
|
|
|
123
129
|
isLoggedIn: authInfo?.isLoggedIn ?? false,
|
|
124
130
|
email: authInfo?.email,
|
|
125
131
|
salesChannel: segment.channel ?? "1",
|
|
132
|
+
regionId: segment.regionId ?? null,
|
|
126
133
|
hasCustomPricing: Boolean(
|
|
127
134
|
segment.priceTables && segment.priceTables.length > 0,
|
|
128
135
|
),
|
|
@@ -217,7 +224,9 @@ export function buildSegmentSetCookie(
|
|
|
217
224
|
*/
|
|
218
225
|
export function vtexCacheKeySuffix(ctx: VtexRequestContext): string {
|
|
219
226
|
if (ctx.isLoggedIn) return "__vtex_auth";
|
|
220
|
-
|
|
227
|
+
const parts = [`sc=${ctx.salesChannel}`];
|
|
228
|
+
if (ctx.regionId) parts.push(`r=${ctx.regionId}`);
|
|
229
|
+
return `__vtex_${parts.join("_")}`;
|
|
221
230
|
}
|
|
222
231
|
|
|
223
232
|
// -------------------------------------------------------------------------
|
package/vtex/utils/cookies.ts
CHANGED
|
@@ -10,32 +10,73 @@ interface Cookie {
|
|
|
10
10
|
sameSite?: "Strict" | "Lax" | "None";
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
function parseSingleSetCookie(raw: string): Cookie | null {
|
|
14
|
+
const parts = raw.split(";").map((p) => p.trim());
|
|
15
|
+
const [nameValue, ...attrs] = parts;
|
|
16
|
+
const eqIdx = nameValue.indexOf("=");
|
|
17
|
+
if (eqIdx < 0) return null;
|
|
18
|
+
const cookie: Cookie = {
|
|
19
|
+
name: nameValue.slice(0, eqIdx),
|
|
20
|
+
value: nameValue.slice(eqIdx + 1),
|
|
21
|
+
};
|
|
22
|
+
for (const attr of attrs) {
|
|
23
|
+
const [k, v] = attr.split("=").map((s) => s.trim());
|
|
24
|
+
const lower = k.toLowerCase();
|
|
25
|
+
if (lower === "domain") cookie.domain = v;
|
|
26
|
+
else if (lower === "path") cookie.path = v;
|
|
27
|
+
else if (lower === "secure") cookie.secure = true;
|
|
28
|
+
else if (lower === "httponly") cookie.httpOnly = true;
|
|
29
|
+
else if (lower === "samesite") cookie.sameSite = v as Cookie["sameSite"];
|
|
30
|
+
}
|
|
31
|
+
return cookie;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Extract individual Set-Cookie values from a Headers object.
|
|
36
|
+
*
|
|
37
|
+
* Uses Headers.getSetCookie() (available in Cloudflare Workers and Node 18+)
|
|
38
|
+
* which returns each Set-Cookie as a separate string — unlike Headers.get()
|
|
39
|
+
* or Headers.forEach() which join multiple values with ", " and corrupt
|
|
40
|
+
* cookie strings that contain commas in Expires dates.
|
|
41
|
+
*/
|
|
13
42
|
function getSetCookies(headers: Headers): Cookie[] {
|
|
43
|
+
const rawCookies: string[] =
|
|
44
|
+
typeof headers.getSetCookie === "function"
|
|
45
|
+
? headers.getSetCookie()
|
|
46
|
+
: getRawSetCookiesFallback(headers);
|
|
47
|
+
|
|
14
48
|
const cookies: Cookie[] = [];
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const eqIdx = nameValue.indexOf("=");
|
|
20
|
-
if (eqIdx < 0) return;
|
|
21
|
-
const cookie: Cookie = {
|
|
22
|
-
name: nameValue.slice(0, eqIdx),
|
|
23
|
-
value: nameValue.slice(eqIdx + 1),
|
|
24
|
-
};
|
|
25
|
-
for (const attr of attrs) {
|
|
26
|
-
const [k, v] = attr.split("=").map((s) => s.trim());
|
|
27
|
-
const lower = k.toLowerCase();
|
|
28
|
-
if (lower === "domain") cookie.domain = v;
|
|
29
|
-
else if (lower === "path") cookie.path = v;
|
|
30
|
-
else if (lower === "secure") cookie.secure = true;
|
|
31
|
-
else if (lower === "httponly") cookie.httpOnly = true;
|
|
32
|
-
else if (lower === "samesite") cookie.sameSite = v as Cookie["sameSite"];
|
|
33
|
-
}
|
|
34
|
-
cookies.push(cookie);
|
|
35
|
-
});
|
|
49
|
+
for (const raw of rawCookies) {
|
|
50
|
+
const cookie = parseSingleSetCookie(raw);
|
|
51
|
+
if (cookie) cookies.push(cookie);
|
|
52
|
+
}
|
|
36
53
|
return cookies;
|
|
37
54
|
}
|
|
38
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Fallback for runtimes without Headers.getSetCookie().
|
|
58
|
+
* Splits the comma-joined string heuristically — not perfect for cookies
|
|
59
|
+
* with Expires containing commas, but better than the old approach.
|
|
60
|
+
*/
|
|
61
|
+
function getRawSetCookiesFallback(headers: Headers): string[] {
|
|
62
|
+
const joined = headers.get("set-cookie");
|
|
63
|
+
if (!joined) return [];
|
|
64
|
+
const results: string[] = [];
|
|
65
|
+
let current = "";
|
|
66
|
+
for (const segment of joined.split(",")) {
|
|
67
|
+
const trimmed = segment.trimStart();
|
|
68
|
+
const looksLikeNewCookie = /^[^=;]+=[^;]/.test(trimmed) && current.length > 0;
|
|
69
|
+
if (looksLikeNewCookie) {
|
|
70
|
+
results.push(current.trim());
|
|
71
|
+
current = trimmed;
|
|
72
|
+
} else {
|
|
73
|
+
current += (current ? "," : "") + segment;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (current.trim()) results.push(current.trim());
|
|
77
|
+
return results;
|
|
78
|
+
}
|
|
79
|
+
|
|
39
80
|
function setCookie(headers: Headers, cookie: Cookie): void {
|
|
40
81
|
let str = `${cookie.name}=${cookie.value}`;
|
|
41
82
|
if (cookie.domain) str += `; Domain=${cookie.domain}`;
|
package/vtex/utils/proxy.ts
CHANGED
|
@@ -104,10 +104,20 @@ function buildOriginUrl(
|
|
|
104
104
|
return new URL(`https://${originHost}${url.pathname}${url.search}`);
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
/**
|
|
108
|
+
* Copy headers excluding hop-by-hop and Set-Cookie.
|
|
109
|
+
*
|
|
110
|
+
* Set-Cookie is excluded intentionally: Headers.forEach / .set() joins
|
|
111
|
+
* multiple Set-Cookie values with ", " which corrupts cookies containing
|
|
112
|
+
* commas (e.g. Expires dates). proxySetCookie handles Set-Cookie
|
|
113
|
+
* separately using Headers.getSetCookie() for correct multi-cookie support.
|
|
114
|
+
*/
|
|
107
115
|
function filterHeaders(headers: Headers): Headers {
|
|
108
116
|
const filtered = new Headers();
|
|
109
117
|
headers.forEach((value, key) => {
|
|
110
|
-
|
|
118
|
+
const lower = key.toLowerCase();
|
|
119
|
+
if (lower === "set-cookie") return;
|
|
120
|
+
if (!HOP_BY_HOP_HEADERS.has(lower)) {
|
|
111
121
|
filtered.set(key, value);
|
|
112
122
|
}
|
|
113
123
|
});
|
|
@@ -148,7 +158,7 @@ export async function proxyToVtex(
|
|
|
148
158
|
}
|
|
149
159
|
}
|
|
150
160
|
|
|
151
|
-
if (config.appKey && config.appToken) {
|
|
161
|
+
if (typeof config.appKey === "string" && typeof config.appToken === "string") {
|
|
152
162
|
forwardHeaders.set("X-VTEX-API-AppKey", config.appKey);
|
|
153
163
|
forwardHeaders.set("X-VTEX-API-AppToken", config.appToken);
|
|
154
164
|
}
|
|
@@ -169,13 +179,13 @@ export async function proxyToVtex(
|
|
|
169
179
|
|
|
170
180
|
const responseHeaders = filterHeaders(new Headers(originResponse.headers));
|
|
171
181
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
new URL(request.url).origin
|
|
177
|
-
|
|
178
|
-
|
|
182
|
+
proxySetCookie(
|
|
183
|
+
originResponse.headers,
|
|
184
|
+
responseHeaders,
|
|
185
|
+
options?.rewriteCookieDomain !== false
|
|
186
|
+
? new URL(request.url).origin
|
|
187
|
+
: undefined,
|
|
188
|
+
);
|
|
179
189
|
|
|
180
190
|
if (originResponse.status >= 300 && originResponse.status < 400) {
|
|
181
191
|
const location = originResponse.headers.get("location");
|