@decocms/apps-vtex 7.2.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.
Files changed (109) hide show
  1. package/package.json +67 -0
  2. package/src/README.md +6 -0
  3. package/src/__tests__/client-segment-cookie.test.ts +255 -0
  4. package/src/__tests__/client-set-cookie-forward.test.ts +257 -0
  5. package/src/actions/address.ts +250 -0
  6. package/src/actions/analytics/sendEvent.ts +86 -0
  7. package/src/actions/auth.ts +333 -0
  8. package/src/actions/checkout.ts +522 -0
  9. package/src/actions/index.ts +11 -0
  10. package/src/actions/masterData.ts +168 -0
  11. package/src/actions/misc.ts +188 -0
  12. package/src/actions/newsletter.ts +105 -0
  13. package/src/actions/orders.ts +34 -0
  14. package/src/actions/profile.ts +201 -0
  15. package/src/actions/session.ts +85 -0
  16. package/src/actions/trigger.ts +43 -0
  17. package/src/actions/wishlist.ts +114 -0
  18. package/src/client.ts +667 -0
  19. package/src/commerceLoaders.ts +261 -0
  20. package/src/hooks/__tests__/createUseCart.test.ts +184 -0
  21. package/src/hooks/__tests__/createUseUser.test.ts +48 -0
  22. package/src/hooks/__tests__/createUseWishlist.test.ts +87 -0
  23. package/src/hooks/createUseCart.ts +360 -0
  24. package/src/hooks/createUseUser.ts +153 -0
  25. package/src/hooks/createUseWishlist.ts +242 -0
  26. package/src/hooks/index.ts +19 -0
  27. package/src/hooks/useAutocomplete.ts +83 -0
  28. package/src/hooks/useCart.ts +243 -0
  29. package/src/hooks/useUser.ts +78 -0
  30. package/src/hooks/useWishlist.ts +119 -0
  31. package/src/index.ts +17 -0
  32. package/src/invoke.ts +181 -0
  33. package/src/loaders/ProductDetailsPage.ts +1 -0
  34. package/src/loaders/ProductList.ts +1 -0
  35. package/src/loaders/ProductListingPage.ts +1 -0
  36. package/src/loaders/address.ts +115 -0
  37. package/src/loaders/autocomplete.ts +58 -0
  38. package/src/loaders/brands.ts +44 -0
  39. package/src/loaders/cart.ts +52 -0
  40. package/src/loaders/catalog.ts +163 -0
  41. package/src/loaders/collections.ts +55 -0
  42. package/src/loaders/index.ts +19 -0
  43. package/src/loaders/intelligentSearch/__tests__/productListingPage.test.ts +20 -0
  44. package/src/loaders/intelligentSearch/productDetailsPage.ts +95 -0
  45. package/src/loaders/intelligentSearch/productList.ts +154 -0
  46. package/src/loaders/intelligentSearch/productListingPage.ts +506 -0
  47. package/src/loaders/intelligentSearch/suggestions.ts +46 -0
  48. package/src/loaders/legacy/productDetailsPage.ts +1 -0
  49. package/src/loaders/legacy/productList.ts +1 -0
  50. package/src/loaders/legacy/relatedProductsLoader.ts +81 -0
  51. package/src/loaders/legacy.ts +635 -0
  52. package/src/loaders/logistics.ts +111 -0
  53. package/src/loaders/minicart.ts +78 -0
  54. package/src/loaders/navbar.ts +26 -0
  55. package/src/loaders/orders.ts +92 -0
  56. package/src/loaders/pageType.ts +68 -0
  57. package/src/loaders/payment.ts +97 -0
  58. package/src/loaders/productListFull.ts +159 -0
  59. package/src/loaders/profile.ts +138 -0
  60. package/src/loaders/promotion.ts +30 -0
  61. package/src/loaders/search.ts +124 -0
  62. package/src/loaders/session.ts +83 -0
  63. package/src/loaders/user.ts +87 -0
  64. package/src/loaders/wishlist.ts +89 -0
  65. package/src/loaders/wishlistProducts.ts +69 -0
  66. package/src/loaders/workflow/products.ts +64 -0
  67. package/src/loaders/workflow.ts +316 -0
  68. package/src/logo.png +0 -0
  69. package/src/middleware.ts +240 -0
  70. package/src/mod.ts +152 -0
  71. package/src/registry.ts +9 -0
  72. package/src/types.ts +248 -0
  73. package/src/utils/__tests__/cookieSanitizer.test.ts +162 -0
  74. package/src/utils/__tests__/fetch.test.ts +80 -0
  75. package/src/utils/__tests__/fetchCache.test.ts +112 -0
  76. package/src/utils/__tests__/instrumentedFetch.test.ts +158 -0
  77. package/src/utils/__tests__/intelligentSearch.test.ts +88 -0
  78. package/src/utils/__tests__/minicart.test.ts +184 -0
  79. package/src/utils/__tests__/operationRouter.test.ts +227 -0
  80. package/src/utils/__tests__/resourceRange.test.ts +32 -0
  81. package/src/utils/__tests__/sitemap.test.ts +185 -0
  82. package/src/utils/__tests__/slugify.test.ts +31 -0
  83. package/src/utils/__tests__/transform.test.ts +698 -0
  84. package/src/utils/accountLoaders.ts +203 -0
  85. package/src/utils/authHelpers.ts +85 -0
  86. package/src/utils/batch.ts +18 -0
  87. package/src/utils/cookieSanitizer.ts +173 -0
  88. package/src/utils/cookies.ts +167 -0
  89. package/src/utils/enrichment.ts +560 -0
  90. package/src/utils/fetch.ts +107 -0
  91. package/src/utils/fetchCache.ts +222 -0
  92. package/src/utils/index.ts +19 -0
  93. package/src/utils/instrumentedFetch.ts +78 -0
  94. package/src/utils/intelligentSearch.ts +96 -0
  95. package/src/utils/legacy.ts +139 -0
  96. package/src/utils/minicart.ts +139 -0
  97. package/src/utils/operationRouter.ts +139 -0
  98. package/src/utils/pickAndOmit.ts +25 -0
  99. package/src/utils/proxy.ts +435 -0
  100. package/src/utils/resourceRange.ts +10 -0
  101. package/src/utils/segment.ts +152 -0
  102. package/src/utils/similars.ts +37 -0
  103. package/src/utils/sitemap.ts +282 -0
  104. package/src/utils/slugCache.ts +28 -0
  105. package/src/utils/slugify.ts +13 -0
  106. package/src/utils/transform.ts +1509 -0
  107. package/src/utils/types.ts +1884 -0
  108. package/src/utils/vtexId.ts +138 -0
  109. package/tsconfig.json +7 -0
@@ -0,0 +1,222 @@
1
+ /**
2
+ * SWR in-memory fetch cache for VTEX API responses.
3
+ *
4
+ * Inspired by deco-cx/deco runtime/fetch/fetchCache.ts.
5
+ * Provides in-flight deduplication + stale-while-revalidate for GET requests.
6
+ *
7
+ * Only caches on the server side. Keyed by full URL string.
8
+ */
9
+
10
+ const DEFAULT_MAX_ENTRIES = 500;
11
+ const MAX_RETRIES = 2;
12
+ const RETRY_DELAYS = [200, 400];
13
+ // Per-attempt timeout. Bounds how long a single hung `fetch()` can hold an
14
+ // inflight entry alive. Without this, a VTEX subrequest that never settles
15
+ // leaks the inflight Map slot forever and every subsequent request for the
16
+ // same cache key joins the zombie Promise, pinning memory until
17
+ // `exceededMemory` (observed in prod: 514 hard crashes / 24h on a PLP route).
18
+ const FETCH_TIMEOUT_MS = 10_000;
19
+
20
+ interface CacheEntry {
21
+ body: unknown;
22
+ status: number;
23
+ createdAt: number;
24
+ refreshing: boolean;
25
+ }
26
+
27
+ const TTL_BY_STATUS: Record<string, number> = {
28
+ "2xx": 180_000, // 3 min for success
29
+ "404": 10_000, // 10s for not found
30
+ "5xx": 0, // never cache server errors
31
+ };
32
+
33
+ function ttlForStatus(status: number): number {
34
+ if (status >= 200 && status < 300) return TTL_BY_STATUS["2xx"];
35
+ if (status === 404) return TTL_BY_STATUS["404"];
36
+ if (status >= 500) return TTL_BY_STATUS["5xx"];
37
+ return 0;
38
+ }
39
+
40
+ const store = new Map<string, CacheEntry>();
41
+ const inflight = new Map<string, Promise<CacheEntry>>();
42
+
43
+ function evictIfNeeded() {
44
+ if (store.size <= DEFAULT_MAX_ENTRIES) return;
45
+ const sorted = [...store.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);
46
+ const toRemove = sorted.slice(0, store.size - DEFAULT_MAX_ENTRIES);
47
+ for (const [key] of toRemove) store.delete(key);
48
+ }
49
+
50
+ function sleep(ms: number): Promise<void> {
51
+ return new Promise((resolve) => setTimeout(resolve, ms));
52
+ }
53
+
54
+ function isRetryable(response: Response): boolean {
55
+ return response.status >= 500 || response.status === 429;
56
+ }
57
+
58
+ /**
59
+ * Race a Promise against a timeout so callers' `.finally()` always runs.
60
+ * Critical for evicting the inflight Map entry when a `fetch()` hangs —
61
+ * without this, a never-settling Promise leaks the Map slot forever and
62
+ * every subsequent request for the same key joins the zombie Promise.
63
+ */
64
+ function withTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {
65
+ let timer: ReturnType<typeof setTimeout> | undefined;
66
+ const timeout = new Promise<never>((_, reject) => {
67
+ timer = setTimeout(() => {
68
+ reject(new Error(`${label} timed out after ${ms}ms`));
69
+ }, ms);
70
+ });
71
+ return Promise.race([work, timeout]).finally(() => {
72
+ clearTimeout(timer);
73
+ });
74
+ }
75
+
76
+ async function executeFetch(
77
+ url: string,
78
+ doFetch: () => Promise<Response>,
79
+ retry = true,
80
+ ): Promise<CacheEntry> {
81
+ let lastError: Error | undefined;
82
+
83
+ const attempts = retry ? MAX_RETRIES + 1 : 1;
84
+ for (let attempt = 0; attempt < attempts; attempt++) {
85
+ try {
86
+ const response = await doFetch();
87
+
88
+ if (isRetryable(response) && attempt < attempts - 1) {
89
+ console.warn(
90
+ `[vtex-fetch] ${response.status} on attempt ${attempt + 1}/${attempts} — ${url}`,
91
+ );
92
+ await sleep(RETRY_DELAYS[attempt] ?? 400);
93
+ continue;
94
+ }
95
+
96
+ if (response.status >= 500) {
97
+ throw new Error(
98
+ `fetchWithCache: ${response.status} ${response.statusText} after ${attempt + 1} attempt(s) — ${url}`,
99
+ );
100
+ }
101
+
102
+ const body = response.ok ? await response.json() : null;
103
+ return {
104
+ body,
105
+ status: response.status,
106
+ createdAt: Date.now(),
107
+ refreshing: false,
108
+ };
109
+ } catch (error) {
110
+ lastError = error instanceof Error ? error : new Error(String(error));
111
+
112
+ if (attempt < attempts - 1) {
113
+ console.warn(
114
+ `[vtex-fetch] attempt ${attempt + 1}/${attempts} failed — ${url}: ${lastError.message}`,
115
+ );
116
+ await sleep(RETRY_DELAYS[attempt] ?? 400);
117
+ }
118
+ }
119
+ }
120
+
121
+ throw lastError ?? new Error(`fetchWithCache: all ${attempts} attempts failed — ${url}`);
122
+ }
123
+
124
+ export interface FetchCacheOptions {
125
+ /**
126
+ * Custom TTL in ms. If provided, overrides status-based TTL.
127
+ */
128
+ ttl?: number;
129
+ }
130
+
131
+ /**
132
+ * Wrap a GET fetch call with SWR caching and in-flight dedup.
133
+ *
134
+ * Returns `null` for non-2xx responses that are cached (e.g. 404).
135
+ * 5xx responses throw so the caller can handle them explicitly.
136
+ *
137
+ * @param cacheKey - Unique key (typically the full URL)
138
+ * @param doFetch - The actual fetch call to execute
139
+ * @param opts - Optional overrides
140
+ * @returns Parsed JSON body, or null for cacheable error responses (e.g. 404)
141
+ */
142
+ export function fetchWithCache<T>(
143
+ cacheKey: string,
144
+ doFetch: () => Promise<Response>,
145
+ opts?: FetchCacheOptions,
146
+ ): Promise<T | null> {
147
+ const now = Date.now();
148
+ const entry = store.get(cacheKey);
149
+
150
+ if (entry) {
151
+ const maxAge = opts?.ttl ?? ttlForStatus(entry.status);
152
+ const isStale = now - entry.createdAt > maxAge;
153
+
154
+ if (!isStale) return Promise.resolve(entry.body as T | null);
155
+
156
+ if (isStale && !entry.refreshing) {
157
+ entry.refreshing = true;
158
+ // Background refresh: no retry — stale data is already being served.
159
+ // Timeout guards against a hung VTEX response leaving `refreshing`
160
+ // stuck true forever (which would silently disable revalidation).
161
+ withTimeout(
162
+ executeFetch(cacheKey, doFetch, false),
163
+ FETCH_TIMEOUT_MS,
164
+ `fetchCache stale-refresh ${cacheKey}`,
165
+ )
166
+ .then((fresh) => {
167
+ const ttl = opts?.ttl ?? ttlForStatus(fresh.status);
168
+ const existingWasSuccess = entry.status >= 200 && entry.status < 300;
169
+ const freshIsError = fresh.status >= 400;
170
+ const wouldDowngrade = existingWasSuccess && freshIsError;
171
+ if (ttl > 0 && !wouldDowngrade) {
172
+ store.set(cacheKey, fresh);
173
+ } else {
174
+ entry.refreshing = false;
175
+ }
176
+ })
177
+ .catch(() => {
178
+ entry.refreshing = false;
179
+ });
180
+ return Promise.resolve(entry.body as T | null);
181
+ }
182
+
183
+ return Promise.resolve(entry.body as T | null);
184
+ }
185
+
186
+ const existing = inflight.get(cacheKey);
187
+ if (existing) return existing.then((e) => e.body as T | null);
188
+
189
+ // Wrap with a timeout so the `.finally()` below always runs and evicts
190
+ // the inflight slot — even if `executeFetch` never settles. See the
191
+ // FETCH_TIMEOUT_MS comment at the top of this file for the leak this
192
+ // guards against.
193
+ const promise = withTimeout(
194
+ executeFetch(cacheKey, doFetch),
195
+ FETCH_TIMEOUT_MS,
196
+ `fetchCache ${cacheKey}`,
197
+ )
198
+ .then((fresh) => {
199
+ const ttl = opts?.ttl ?? ttlForStatus(fresh.status);
200
+ if (ttl > 0) {
201
+ store.set(cacheKey, fresh);
202
+ evictIfNeeded();
203
+ }
204
+ return fresh;
205
+ })
206
+ .finally(() => inflight.delete(cacheKey));
207
+
208
+ inflight.set(cacheKey, promise);
209
+ return promise.then((e) => e.body as T | null);
210
+ }
211
+
212
+ export function clearFetchCache() {
213
+ store.clear();
214
+ inflight.clear();
215
+ }
216
+
217
+ export function getFetchCacheStats() {
218
+ return {
219
+ entries: store.size,
220
+ inflight: inflight.size,
221
+ };
222
+ }
@@ -0,0 +1,19 @@
1
+ export type { PersonalDataOptions } from "./accountLoaders";
2
+ export { vtexAccountLoaders } from "./accountLoaders";
3
+ export * from "./batch";
4
+ export * from "./cookies";
5
+ export * from "./enrichment";
6
+ export * from "./fetchCache";
7
+ export * from "./intelligentSearch";
8
+ export * from "./legacy";
9
+ export * from "./pickAndOmit";
10
+ export * from "./proxy";
11
+ export * from "./resourceRange";
12
+ export * from "./segment";
13
+ export * from "./similars";
14
+ export * from "./sitemap";
15
+ export * from "./slugCache";
16
+ export * from "./slugify";
17
+ export * from "./transform";
18
+ export * from "./types";
19
+ export * from "./vtexId";
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Pre-wired instrumented fetch factory for VTEX.
3
+ *
4
+ * Bundles the three pieces a storefront would otherwise have to wire
5
+ * by hand:
6
+ *
7
+ * 1. The `createInstrumentedFetch` boundary from `@decocms/start`
8
+ * (spans, traceparent injection, URL redaction, cache-header
9
+ * span attributes).
10
+ * 2. The `vtexOperationRouter` URL→operation mapping so unannotated
11
+ * callsites still get semantic span names + histogram labels.
12
+ * 3. An `onComplete` callback that records every call into the
13
+ * canonical `http.client.request.duration` histogram via the
14
+ * framework's `recordCommerceMetric(...)` helper in
15
+ * `@decocms/start/sdk/observability` — `provider`, `operation`,
16
+ * `status_class`, and `cached` labels.
17
+ *
18
+ * Sites opt in once at startup:
19
+ *
20
+ * ```ts
21
+ * import { setVtexFetch } from "@decocms/apps/vtex";
22
+ * import { createVtexFetch } from "@decocms/apps/vtex";
23
+ *
24
+ * setVtexFetch(createVtexFetch());
25
+ * ```
26
+ *
27
+ * Sites that need to wrap a custom underlying fetch (cookie passthrough,
28
+ * proxy, retry, etc.) pass it as `baseFetch`. The instrumentation
29
+ * still applies — `createInstrumentedFetch` preserves the wrapped
30
+ * behavior.
31
+ */
32
+
33
+ import {
34
+ createInstrumentedFetch,
35
+ type InstrumentedFetch,
36
+ } from "@decocms/blocks/sdk/instrumentedFetch";
37
+ import { recordCommerceMetric } from "@decocms/blocks/sdk/observability";
38
+ import { vtexOperationRouter } from "./operationRouter";
39
+
40
+ export interface CreateVtexFetchOptions {
41
+ /**
42
+ * Underlying fetch to wrap. Defaults to `globalThis.fetch`.
43
+ * Pass an existing custom fetch (e.g. one that injects auth cookies
44
+ * or routes through a proxy) to preserve its behavior while adding
45
+ * the VTEX instrumentation layer on top.
46
+ */
47
+ baseFetch?: typeof fetch;
48
+ /**
49
+ * Disable the `http.client.request.duration` histogram emission for
50
+ * VTEX calls. The framework's span and structured logs still emit.
51
+ * Useful when the consumer wants to record its own histogram with a
52
+ * custom shape. Default: false.
53
+ */
54
+ disableHistogram?: boolean;
55
+ }
56
+
57
+ /**
58
+ * Construct a pre-wired VTEX `InstrumentedFetch`. Pass the result to
59
+ * `setVtexFetch(...)`. See module docstring for details.
60
+ */
61
+ export function createVtexFetch(options: CreateVtexFetchOptions = {}): InstrumentedFetch {
62
+ const { baseFetch, disableHistogram = false } = options;
63
+ return createInstrumentedFetch({
64
+ name: "vtex",
65
+ baseFetch,
66
+ resolveOperation: vtexOperationRouter,
67
+ onComplete: disableHistogram
68
+ ? undefined
69
+ : ({ operation, status, durationMs, cached }) => {
70
+ recordCommerceMetric(durationMs, {
71
+ provider: "vtex",
72
+ operation,
73
+ status_class: `${Math.floor(status / 100)}xx`,
74
+ cached,
75
+ });
76
+ },
77
+ });
78
+ }
@@ -0,0 +1,96 @@
1
+ import { vtexFetch } from "../client";
2
+ import type { PageType, SelectedFacet, SimulationBehavior, Sort } from "./types";
3
+
4
+ export const SESSION_COOKIE = "vtex_is_session";
5
+ export const ANONYMOUS_COOKIE = "vtex_is_anonymous";
6
+
7
+ export const withDefaultFacets = (allFacets: readonly SelectedFacet[]) => {
8
+ return [...allFacets];
9
+ };
10
+
11
+ export const toPath = (facets: SelectedFacet[]) =>
12
+ facets.map(({ key, value }) => (key ? `${key}/${value}` : value)).join("/");
13
+
14
+ interface Params {
15
+ query: string;
16
+ page: number;
17
+ count: number;
18
+ sort: Sort;
19
+ fuzzy: string;
20
+ locale: string;
21
+ hideUnavailableItems: boolean;
22
+ simulationBehavior: SimulationBehavior;
23
+ }
24
+
25
+ export const withDefaultParams = ({
26
+ query = "",
27
+ page = 0,
28
+ count = 12,
29
+ sort = "",
30
+ fuzzy = "auto",
31
+ locale = "pt-BR",
32
+ hideUnavailableItems,
33
+ simulationBehavior = "default",
34
+ }: Partial<Params>) => ({
35
+ page: page + 1,
36
+ count,
37
+ query,
38
+ sort,
39
+ ...(fuzzy ? { fuzzy } : {}),
40
+ locale,
41
+ hideUnavailableItems: hideUnavailableItems ?? false,
42
+ simulationBehavior,
43
+ });
44
+
45
+ export const isFilterParam = (keyFilter: string): boolean => keyFilter.startsWith("filter.");
46
+
47
+ /**
48
+ * Valid VTEX Intelligent Search sort values.
49
+ * Anything else (e.g. "orders:desc)" with a trailing paren from legacy URLs)
50
+ * causes IS API to return 400.
51
+ */
52
+ export const VALID_IS_SORTS = new Set([
53
+ "",
54
+ "orders:desc",
55
+ "price:asc",
56
+ "price:desc",
57
+ "name:asc",
58
+ "name:desc",
59
+ "release:desc",
60
+ "discount:desc",
61
+ ]);
62
+
63
+ /** Sanitize an IS sort parameter — returns empty string for invalid values. */
64
+ export function sanitizeISSort(sort: string): string {
65
+ return VALID_IS_SORTS.has(sort) ? sort : "";
66
+ }
67
+
68
+ const segmentsFromTerm = (term: string) => term.split("/").filter(Boolean);
69
+
70
+ const segmentsFromSearchParams = (url: string) => {
71
+ const searchParams = new URLSearchParams(url).entries();
72
+
73
+ const categories = Array.from(searchParams)
74
+ .sort()
75
+ .reduce((acc, [key, value]) => {
76
+ if (key.includes("filter.category")) {
77
+ acc.push(value);
78
+ }
79
+
80
+ return acc;
81
+ }, [] as string[]);
82
+
83
+ return categories.length ? categories : segmentsFromTerm(url);
84
+ };
85
+
86
+ export const pageTypesFromUrl = async (url: string): Promise<PageType[]> => {
87
+ const segments = segmentsFromSearchParams(url);
88
+
89
+ return await Promise.all(
90
+ segments.map((_, index) =>
91
+ vtexFetch<PageType>(
92
+ `/api/catalog_system/pub/portal/pagetype/${segments.slice(0, index + 1).join("/")}`,
93
+ ),
94
+ ),
95
+ );
96
+ };
@@ -0,0 +1,139 @@
1
+ import type { Seo } from "@decocms/apps-commerce/types";
2
+ import { vtexFetch } from "../client";
3
+ import type { WrappedSegment } from "./segment";
4
+ import { slugify } from "./slugify";
5
+ import type { PageType } from "./types";
6
+
7
+ const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
8
+
9
+ export const toSegmentParams = ({ payload: segment }: WrappedSegment) =>
10
+ Object.fromEntries(
11
+ Object.entries({
12
+ utmi_campaign: segment.utmi_campaign ?? undefined,
13
+ utm_campaign: segment.utm_campaign ?? undefined,
14
+ utm_source: segment.utm_source ?? undefined,
15
+ sc: segment.channel ?? undefined,
16
+ }).filter(([_, v]) => v !== undefined),
17
+ );
18
+
19
+ const PAGE_TYPE_TO_MAP_PARAM = {
20
+ Brand: "b",
21
+ Category: "c",
22
+ Department: "c",
23
+ SubCategory: "c",
24
+ Collection: "productClusterIds",
25
+ Cluster: "productClusterIds",
26
+ Search: "ft",
27
+ FullText: "ft",
28
+ Product: "p",
29
+ NotFound: null,
30
+ };
31
+
32
+ const segmentsFromTerm = (term: string) => term.split("/").filter(Boolean);
33
+
34
+ export const getValidTypesFromPageTypes = (pagetypes: PageType[]) => {
35
+ return pagetypes.filter((type) => PAGE_TYPE_TO_MAP_PARAM[type.pageType]);
36
+ };
37
+
38
+ export const pageTypesFromPathname = async (term: string): Promise<PageType[]> => {
39
+ const segments = segmentsFromTerm(term);
40
+
41
+ return await Promise.all(
42
+ segments.map((_, index) =>
43
+ vtexFetch<PageType>(
44
+ `/api/catalog_system/pub/portal/pagetype/${segments.slice(0, index + 1).join("/")}`,
45
+ ),
46
+ ),
47
+ );
48
+ };
49
+
50
+ export const getMapAndTerm = (pageTypes: PageType[]) => {
51
+ const term = pageTypes
52
+ .map((type, index) =>
53
+ type.url ? segmentsFromTerm(new URL(`http://${type.url}`).pathname)[index] : null,
54
+ )
55
+ .filter(Boolean)
56
+ .join("/");
57
+
58
+ const map = pageTypes
59
+ .map((type) => PAGE_TYPE_TO_MAP_PARAM[type.pageType])
60
+ .filter(Boolean)
61
+ .join(",");
62
+
63
+ if (map === "ft" && term === "s") {
64
+ return ["", ""];
65
+ }
66
+
67
+ return [map, term];
68
+ };
69
+
70
+ export const pageTypesToBreadcrumbList = (pages: PageType[], baseUrl: string) => {
71
+ const filteredPages = pages.filter(
72
+ ({ pageType }) =>
73
+ pageType === "Category" || pageType === "Department" || pageType === "SubCategory",
74
+ );
75
+
76
+ return filteredPages.map((page, index) => {
77
+ const position = index + 1;
78
+ const slug = filteredPages.slice(0, position).map((x) => slugify(x.name!));
79
+
80
+ return {
81
+ "@type": "ListItem" as const,
82
+ name: page.name!,
83
+ item: new URL(`/${slug.join("/")}`, baseUrl).href,
84
+ position,
85
+ };
86
+ });
87
+ };
88
+
89
+ export const pageTypesToSeo = (
90
+ pages: PageType[],
91
+ baseUrl: string,
92
+ currentPage?: number,
93
+ ): Seo | null => {
94
+ const current = pages.at(-1);
95
+ const url = new URL(baseUrl);
96
+ const fullTextSearch = url.searchParams.get("q");
97
+ const hasMapTermOrSkuId = !!(url.searchParams.get("map") || url.searchParams.get("skuId"));
98
+
99
+ if (
100
+ (!current || current.pageType === "Search" || current.pageType === "FullText") &&
101
+ fullTextSearch
102
+ ) {
103
+ return {
104
+ title: capitalize(fullTextSearch),
105
+ description: capitalize(fullTextSearch),
106
+ canonical: url.href,
107
+ noIndexing: hasMapTermOrSkuId,
108
+ };
109
+ }
110
+
111
+ if (!current) {
112
+ return null;
113
+ }
114
+
115
+ return {
116
+ title: current.title || current.name || "",
117
+ description: current.metaTagDescription!,
118
+ noIndexing: hasMapTermOrSkuId,
119
+ canonical: toCanonical(
120
+ new URL(
121
+ current.url && current.pageType !== "Collection"
122
+ ? current.url.replace(/^[^/]*\//, "/").toLowerCase()
123
+ : url,
124
+ url,
125
+ ),
126
+ currentPage,
127
+ ),
128
+ };
129
+ };
130
+
131
+ function toCanonical(url: URL, page?: number) {
132
+ if (typeof page === "number") {
133
+ url.searchParams.set("page", `${page}`);
134
+ }
135
+
136
+ return url.href;
137
+ }
138
+
139
+ export { isFilterParam } from "./intelligentSearch";
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Map a VTEX OrderForm to the canonical `Minicart` contract.
3
+ *
4
+ * Pure function — no I/O, fully unit-testable. Pricing is converted from
5
+ * VTEX's native cents to major units (the canonical unit for `Minicart`).
6
+ *
7
+ * Locale and currency come from `orderForm.storePreferencesData` and follow
8
+ * VTEX's `storePreferencesData.countryCode` / `currencyCode` semantics.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { vtexOrderFormToMinicart } from "@decocms/apps/vtex/utils/minicart";
13
+ * import { getCart } from "@decocms/apps/vtex/loaders/cart";
14
+ *
15
+ * const orderForm = await getCart(orderFormId);
16
+ * const minicart = vtexOrderFormToMinicart(orderForm, {
17
+ * freeShippingTarget: 0,
18
+ * checkoutHref: "/checkout",
19
+ * });
20
+ * ```
21
+ */
22
+
23
+ import type { Minicart, MinicartItem } from "@decocms/apps-commerce/types";
24
+ import type { OrderForm, OrderFormItem, Totalizer } from "../types";
25
+
26
+ export interface VtexOrderFormToMinicartOptions {
27
+ /** Free-shipping threshold in major units. `0` disables the progress bar. */
28
+ freeShippingTarget?: number;
29
+ /** Override the OrderForm's `clientPreferencesData.locale` (BCP-47, e.g. `"pt-BR"`). */
30
+ locale?: string;
31
+ /** Where the checkout button sends the user. Default: `/checkout`. */
32
+ checkoutHref?: string;
33
+ /** Whether the UI should expose the coupon input. Default: `true`. */
34
+ enableCoupon?: boolean;
35
+ }
36
+
37
+ const CENTS_PER_MAJOR = 100;
38
+
39
+ /** Convert VTEX cents to major units. Always returns a finite number. */
40
+ function fromCents(cents: number | undefined | null): number {
41
+ if (cents == null || !Number.isFinite(cents)) return 0;
42
+ return cents / CENTS_PER_MAJOR;
43
+ }
44
+
45
+ function findTotalizer(totalizers: Totalizer[] | undefined, id: string): number {
46
+ if (!totalizers) return 0;
47
+ const t = totalizers.find((x) => x.id === id);
48
+ return t?.value ?? 0;
49
+ }
50
+
51
+ /**
52
+ * Locale heuristic. VTEX exposes `clientPreferencesData.locale` when set, but
53
+ * otherwise we synthesize one from `storePreferencesData.countryCode` so the UI
54
+ * always has a usable value for `Intl.NumberFormat`.
55
+ */
56
+ function inferLocale(orderForm: OrderForm, override?: string): string {
57
+ if (override) return override;
58
+ const explicit = orderForm.clientPreferencesData?.locale;
59
+ if (explicit) return explicit;
60
+
61
+ const country = orderForm.storePreferencesData?.countryCode;
62
+ if (country === "BRA" || country === "BR") return "pt-BR";
63
+ if (country === "USA" || country === "US") return "en-US";
64
+ return "en-US";
65
+ }
66
+
67
+ function vtexItemToMinicartItem(item: OrderFormItem, index: number, coupon?: string): MinicartItem {
68
+ const sellingPrice = fromCents(item.sellingPrice ?? item.price);
69
+ const listPrice = fromCents(item.listPrice ?? item.price);
70
+ const discount = Math.max(0, listPrice - sellingPrice);
71
+
72
+ return {
73
+ // AnalyticsItem identifier — VTEX uses productId; sites map to numeric SKU
74
+ // when needed via `Number(item.item_id)` (see bagaggio Minicart).
75
+ item_id: item.id,
76
+ item_group_id: item.productId,
77
+ item_name: item.name ?? item.skuName ?? "",
78
+ item_variant: item.skuName,
79
+ item_brand: item.additionalInfo?.brandName ?? undefined,
80
+ item_url: item.detailUrl,
81
+ coupon,
82
+ affiliation: item.seller,
83
+ index,
84
+ // Cart-required fields
85
+ image: item.imageUrl?.replace(/^http:/, "https:") ?? "",
86
+ listPrice,
87
+ price: sellingPrice,
88
+ quantity: item.quantity,
89
+ discount: Number(discount.toFixed(2)),
90
+ // Platform-specific
91
+ seller: item.seller,
92
+ attachments: item.attachments as MinicartItem["attachments"],
93
+ attachmentOfferings: item.attachmentOfferings as MinicartItem["attachmentOfferings"],
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Map a VTEX `OrderForm` to the canonical platform-agnostic `Minicart`.
99
+ *
100
+ * @param orderForm - Result from `getCart()` or `getOrCreateCart()`.
101
+ * @param opts - Storefront-level overrides (free-shipping target, checkout href, ...).
102
+ */
103
+ export function vtexOrderFormToMinicart(
104
+ orderForm: OrderForm,
105
+ opts: VtexOrderFormToMinicartOptions = {},
106
+ ): Minicart<OrderForm> {
107
+ const totalizers = orderForm.totalizers;
108
+ const subtotal = fromCents(findTotalizer(totalizers, "Items"));
109
+ const discountsRaw = findTotalizer(totalizers, "Discounts");
110
+ const discounts = Math.abs(fromCents(discountsRaw));
111
+ const shippingRaw = findTotalizer(totalizers, "Shipping");
112
+ const shipping = totalizers?.some((t) => t.id === "Shipping")
113
+ ? fromCents(shippingRaw)
114
+ : undefined;
115
+ const total = fromCents(orderForm.value);
116
+
117
+ const coupon = orderForm.marketingData?.coupon;
118
+ const items = (orderForm.items ?? []).map((item, index) =>
119
+ vtexItemToMinicartItem(item, index, coupon),
120
+ );
121
+
122
+ return {
123
+ original: orderForm,
124
+ storefront: {
125
+ items,
126
+ subtotal,
127
+ discounts,
128
+ shipping,
129
+ total,
130
+ coupon,
131
+ locale: inferLocale(orderForm, opts.locale),
132
+ currency: orderForm.storePreferencesData?.currencyCode ?? "BRL",
133
+ enableCoupon: opts.enableCoupon ?? true,
134
+ freeShippingTarget: opts.freeShippingTarget ?? 0,
135
+ checkoutHref: opts.checkoutHref ?? "/checkout",
136
+ postalCode: orderForm.shippingData?.address?.postalCode ?? undefined,
137
+ },
138
+ };
139
+ }