@decocms/apps-vtex 8.0.0 → 8.1.0-next.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.
Files changed (133) hide show
  1. package/package.json +7 -52
  2. package/src/index.ts +12 -15
  3. package/src/utils/constants.ts +2 -56
  4. package/src/utils/cookieSanitizer.ts +59 -59
  5. package/src/utils/operationRouter.ts +76 -72
  6. package/src/utils/types.ts +709 -1557
  7. package/src/vtexClient.ts +444 -0
  8. package/src/README.md +0 -6
  9. package/src/__tests__/client-segment-cookie.test.ts +0 -255
  10. package/src/__tests__/client-set-cookie-forward.test.ts +0 -257
  11. package/src/__tests__/schemas.test.ts +0 -71
  12. package/src/actions/address.ts +0 -250
  13. package/src/actions/analytics/sendEvent.ts +0 -86
  14. package/src/actions/auth.ts +0 -333
  15. package/src/actions/checkout.ts +0 -659
  16. package/src/actions/index.ts +0 -11
  17. package/src/actions/masterData.ts +0 -168
  18. package/src/actions/misc.ts +0 -188
  19. package/src/actions/newsletter.ts +0 -105
  20. package/src/actions/orders.ts +0 -34
  21. package/src/actions/profile.ts +0 -201
  22. package/src/actions/session.ts +0 -85
  23. package/src/actions/trigger.ts +0 -43
  24. package/src/actions/wishlist.ts +0 -114
  25. package/src/client.ts +0 -667
  26. package/src/commerceLoaders.ts +0 -267
  27. package/src/hooks/__tests__/createCart.render.test.ts +0 -114
  28. package/src/hooks/__tests__/createCart.test.ts +0 -92
  29. package/src/hooks/__tests__/createUseCart.test.ts +0 -184
  30. package/src/hooks/__tests__/createUseUser.test.ts +0 -48
  31. package/src/hooks/__tests__/createUseWishlist.test.ts +0 -87
  32. package/src/hooks/cartQuery.ts +0 -204
  33. package/src/hooks/createCart.ts +0 -427
  34. package/src/hooks/createUseCart.ts +0 -360
  35. package/src/hooks/createUseUser.ts +0 -153
  36. package/src/hooks/createUseWishlist.ts +0 -242
  37. package/src/hooks/index.ts +0 -25
  38. package/src/hooks/useAutocomplete.ts +0 -83
  39. package/src/hooks/useCart.ts +0 -243
  40. package/src/hooks/useUser.ts +0 -78
  41. package/src/hooks/useWishlist.ts +0 -119
  42. package/src/invoke.ts +0 -235
  43. package/src/loaders/ProductDetailsPage.ts +0 -1
  44. package/src/loaders/ProductList.ts +0 -1
  45. package/src/loaders/ProductListingPage.ts +0 -1
  46. package/src/loaders/address.ts +0 -115
  47. package/src/loaders/autocomplete.ts +0 -58
  48. package/src/loaders/brands.ts +0 -44
  49. package/src/loaders/cart/attachments.ts +0 -53
  50. package/src/loaders/cart/full.ts +0 -67
  51. package/src/loaders/cart/gifts.ts +0 -43
  52. package/src/loaders/cart/orderFormId.ts +0 -31
  53. package/src/loaders/cart/shipping.test.ts +0 -125
  54. package/src/loaders/cart/shipping.ts +0 -136
  55. package/src/loaders/cart/summary.ts +0 -36
  56. package/src/loaders/cart.ts +0 -52
  57. package/src/loaders/catalog.ts +0 -163
  58. package/src/loaders/collections.ts +0 -55
  59. package/src/loaders/index.ts +0 -20
  60. package/src/loaders/intelligentSearch/__tests__/productListingPage.test.ts +0 -51
  61. package/src/loaders/intelligentSearch/productDetailsPage.ts +0 -113
  62. package/src/loaders/intelligentSearch/productList.ts +0 -154
  63. package/src/loaders/intelligentSearch/productListingPage.ts +0 -526
  64. package/src/loaders/intelligentSearch/suggestions.ts +0 -46
  65. package/src/loaders/legacy/productDetailsPage.ts +0 -1
  66. package/src/loaders/legacy/productList.ts +0 -1
  67. package/src/loaders/legacy/relatedProductsLoader.ts +0 -81
  68. package/src/loaders/legacy.ts +0 -635
  69. package/src/loaders/logistics.ts +0 -111
  70. package/src/loaders/minicart.ts +0 -78
  71. package/src/loaders/navbar.ts +0 -26
  72. package/src/loaders/orders.ts +0 -92
  73. package/src/loaders/pageType.ts +0 -68
  74. package/src/loaders/paths/PDPDefaultPath.ts +0 -51
  75. package/src/loaders/payment.ts +0 -97
  76. package/src/loaders/productListFull.ts +0 -159
  77. package/src/loaders/profile.ts +0 -138
  78. package/src/loaders/promotion.ts +0 -30
  79. package/src/loaders/search.ts +0 -124
  80. package/src/loaders/session.ts +0 -83
  81. package/src/loaders/user.ts +0 -87
  82. package/src/loaders/wishlist.ts +0 -89
  83. package/src/loaders/wishlistProducts.ts +0 -69
  84. package/src/loaders/workflow/products.ts +0 -64
  85. package/src/loaders/workflow.ts +0 -316
  86. package/src/logo.png +0 -0
  87. package/src/manifest.gen.ts +0 -89
  88. package/src/middleware.ts +0 -240
  89. package/src/mod.ts +0 -157
  90. package/src/registry.ts +0 -9
  91. package/src/schemas.gen.ts +0 -3191
  92. package/src/schemas.ts +0 -30
  93. package/src/types.ts +0 -248
  94. package/src/utils/__tests__/cartProjection.test.ts +0 -118
  95. package/src/utils/__tests__/cookieSanitizer.test.ts +0 -162
  96. package/src/utils/__tests__/fetch.test.ts +0 -80
  97. package/src/utils/__tests__/fetchCache.test.ts +0 -155
  98. package/src/utils/__tests__/instrumentedFetch.test.ts +0 -158
  99. package/src/utils/__tests__/intelligentSearch.test.ts +0 -88
  100. package/src/utils/__tests__/minicart.test.ts +0 -184
  101. package/src/utils/__tests__/operationRouter.test.ts +0 -227
  102. package/src/utils/__tests__/resilience.test.ts +0 -205
  103. package/src/utils/__tests__/resourceRange.test.ts +0 -32
  104. package/src/utils/__tests__/simulationCache.test.ts +0 -40
  105. package/src/utils/__tests__/sitemap.test.ts +0 -185
  106. package/src/utils/__tests__/slugify.test.ts +0 -31
  107. package/src/utils/__tests__/transform.test.ts +0 -769
  108. package/src/utils/accountLoaders.ts +0 -203
  109. package/src/utils/authHelpers.ts +0 -85
  110. package/src/utils/batch.ts +0 -18
  111. package/src/utils/cartProjection.ts +0 -96
  112. package/src/utils/cookies.ts +0 -167
  113. package/src/utils/enrichment.ts +0 -560
  114. package/src/utils/fetch.ts +0 -107
  115. package/src/utils/fetchCache.ts +0 -199
  116. package/src/utils/index.ts +0 -19
  117. package/src/utils/instrumentedFetch.ts +0 -97
  118. package/src/utils/intelligentSearch.ts +0 -96
  119. package/src/utils/legacy.ts +0 -139
  120. package/src/utils/minicart.ts +0 -139
  121. package/src/utils/pickAndOmit.ts +0 -25
  122. package/src/utils/proxy.ts +0 -435
  123. package/src/utils/resilience.ts +0 -352
  124. package/src/utils/resourceRange.ts +0 -10
  125. package/src/utils/segment.ts +0 -152
  126. package/src/utils/similars.ts +0 -37
  127. package/src/utils/simulationCache.ts +0 -73
  128. package/src/utils/sitemap.ts +0 -282
  129. package/src/utils/slugCache.ts +0 -28
  130. package/src/utils/slugify.ts +0 -13
  131. package/src/utils/transform.ts +0 -1522
  132. package/src/utils/vtexId.ts +0 -138
  133. package/tsconfig.json +0 -7
@@ -1,526 +0,0 @@
1
- import {
2
- filtersFromPageTypes,
3
- getVtexConfig,
4
- intelligentSearch,
5
- type PageType,
6
- pageTypesFromPath,
7
- toFacetPath,
8
- } from "../../client";
9
- import { pickSku, toProduct } from "../../utils/transform";
10
- import type { Product as ProductVTEX, Sort } from "../../utils/types";
11
-
12
- export interface SelectedFacet {
13
- key: string;
14
- value: string;
15
- }
16
-
17
- /**
18
- * Friendly fuzzy labels for CMS UIs. Translate to the raw IS API value via
19
- * {@link mapLabelledFuzzyToFuzzy} before passing into a loader's `fuzzy` field.
20
- */
21
- export type LabelledFuzzy = "automatic" | "disabled" | "enabled";
22
-
23
- /**
24
- * Translate a friendly fuzzy label to the value the VTEX Intelligent Search
25
- * API expects. Returns `undefined` when the label is omitted so callers can
26
- * skip the param entirely.
27
- *
28
- * @example
29
- * intelligentSearch({ fuzzy: mapLabelledFuzzyToFuzzy(props.fuzzy) })
30
- */
31
- /**
32
- * Resolve the 0-indexed internal `page` from the CMS prop and/or the
33
- * 1-indexed URL `?page=` param.
34
- *
35
- * `props.page` may arrive as a string (e.g. auto-injected from a URL search
36
- * param upstream) — `Number.isFinite` does NOT coerce, so a bare
37
- * `Number.isFinite(propsPage)` check would silently treat `"3"` as invalid
38
- * and hard-default to page 0 (see #391). Coerce first, and treat a
39
- * non-finite coerced value as "absent" so it falls through to the URL
40
- * parse instead of hard-defaulting.
41
- */
42
- export function resolvePage(propsPage: number | string | undefined, pageFromUrl: string | null | undefined): number {
43
- const coercedPropsPage = propsPage !== undefined ? Number(propsPage) : undefined;
44
- const rawPage =
45
- coercedPropsPage !== undefined && Number.isFinite(coercedPropsPage)
46
- ? coercedPropsPage
47
- : pageFromUrl
48
- ? Number(pageFromUrl) - 1
49
- : 0;
50
- return Number.isFinite(rawPage) && rawPage >= 0 ? Math.floor(rawPage) : 0;
51
- }
52
-
53
- export const mapLabelledFuzzyToFuzzy = (label?: LabelledFuzzy): "0" | "1" | "auto" | undefined => {
54
- switch (label) {
55
- case "automatic":
56
- return "auto";
57
- case "enabled":
58
- return "1";
59
- case "disabled":
60
- return "0";
61
- default:
62
- return undefined;
63
- }
64
- };
65
-
66
- export interface PLPProps {
67
- /**
68
- * @title Query
69
- * @description Overrides the search term used to fetch the listing.
70
- */
71
- query?: string;
72
- /**
73
- * @title Items per page
74
- * @description Number of products per page to display.
75
- */
76
- count?: number;
77
- /**
78
- * @title Sorting
79
- * @description Order in which products are returned.
80
- */
81
- sort?: Sort;
82
- /**
83
- * @title Fuzzy
84
- * @description Controls Intelligent Search typo tolerance.
85
- */
86
- fuzzy?: LabelledFuzzy;
87
- /**
88
- * @title Page offset
89
- * @description Starting page (0-indexed) for the listing query.
90
- */
91
- page?: number;
92
- /**
93
- * @title Selected Facets
94
- * @description Override selected facets from the URL (e.g. force a collection).
95
- */
96
- selectedFacets?: SelectedFacet[];
97
- /**
98
- * @title Hide Unavailable Items
99
- * @description Do not return out-of-stock items.
100
- */
101
- hideUnavailableItems?: boolean;
102
- /** Injected by CMS resolve — the matched page path (e.g. "/pisos/piso-vinilico-clicado") */
103
- __pagePath?: string;
104
- /** Injected by CMS resolve — the full request URL (e.g. "https://site.com/s?q=telha&sort=price:asc") */
105
- __pageUrl?: string;
106
- }
107
-
108
- // -- Types matching VTEX IS API responses --
109
-
110
- interface ISPaginationItem {
111
- index: number;
112
- proxyUrl?: string;
113
- }
114
-
115
- interface ISPagination {
116
- count: number;
117
- current: ISPaginationItem;
118
- before: ISPaginationItem[];
119
- after: ISPaginationItem[];
120
- perPage: number;
121
- next: ISPaginationItem;
122
- previous: ISPaginationItem;
123
- first: ISPaginationItem;
124
- last: ISPaginationItem;
125
- }
126
-
127
- interface ISProductSearchResult {
128
- products: any[];
129
- recordsFiltered: number;
130
- pagination: ISPagination;
131
- correction?: { misspelled?: boolean };
132
- operator?: string;
133
- redirect?: string;
134
- }
135
-
136
- interface ISFacetValueBoolean {
137
- quantity: number;
138
- name: string;
139
- value: string;
140
- selected: boolean;
141
- }
142
-
143
- interface ISFacetValueRange {
144
- quantity: number;
145
- name: string;
146
- selected: boolean;
147
- range: { from: number; to: number };
148
- }
149
-
150
- interface ISFacet {
151
- key: string;
152
- name: string;
153
- type: "TEXT" | "PRICERANGE";
154
- hidden: boolean;
155
- quantity: number;
156
- values: Array<ISFacetValueBoolean | ISFacetValueRange>;
157
- }
158
-
159
- interface ISFacetsResult {
160
- facets: ISFacet[];
161
- }
162
-
163
- // Valid page types for filtering (matching original getValidTypesFromPageTypes)
164
- const VALID_PAGE_TYPES = new Set([
165
- "Brand",
166
- "Category",
167
- "Department",
168
- "SubCategory",
169
- "Collection",
170
- "Cluster",
171
- "Search",
172
- "FullText",
173
- "Product",
174
- ]);
175
-
176
- function getValidPageTypes(pageTypes: PageType[]): PageType[] {
177
- return pageTypes.filter((pt) => VALID_PAGE_TYPES.has(pt.pageType));
178
- }
179
-
180
- // -- Filter transformation (mirrors original toFilter + facetToToggle) --
181
-
182
- function formatRange(from: number, to: number): string {
183
- return `${from}:${to}`;
184
- }
185
-
186
- function isRangeValue(val: any): val is ISFacetValueRange {
187
- return Boolean(val.range);
188
- }
189
-
190
- function filtersToSearchParams(
191
- facets: SelectedFacet[],
192
- paramsToPersist?: URLSearchParams,
193
- ): URLSearchParams {
194
- const searchParams = new URLSearchParams(paramsToPersist);
195
- for (const { key, value } of facets) {
196
- searchParams.append(`filter.${key}`, value);
197
- }
198
- return searchParams;
199
- }
200
-
201
- function facetToToggle(
202
- selectedFacets: SelectedFacet[],
203
- key: string,
204
- paramsToPersist?: URLSearchParams,
205
- basePath = "",
206
- ) {
207
- return (item: ISFacetValueBoolean | ISFacetValueRange) => {
208
- const { quantity, selected } = item;
209
- const isRange = isRangeValue(item);
210
- const value = isRange
211
- ? formatRange(item.range.from, item.range.to)
212
- : (item as ISFacetValueBoolean).value;
213
- const label = isRange ? value : (item as ISFacetValueBoolean).name;
214
- const facet = { key, value };
215
-
216
- const filters = selected
217
- ? selectedFacets.filter((f) => f.key !== key || f.value !== value)
218
- : [...selectedFacets, facet];
219
-
220
- return {
221
- value,
222
- quantity,
223
- selected,
224
- url: `${basePath}?${filtersToSearchParams(filters, paramsToPersist)}`,
225
- label,
226
- };
227
- };
228
- }
229
-
230
- function toFilter(
231
- selectedFacets: SelectedFacet[],
232
- paramsToPersist?: URLSearchParams,
233
- basePath = "",
234
- ) {
235
- return (facet: ISFacet) => ({
236
- "@type": "FilterToggle" as const,
237
- key: facet.key,
238
- label: facet.name,
239
- quantity: facet.quantity,
240
- values: facet.values.map(facetToToggle(selectedFacets, facet.key, paramsToPersist, basePath)),
241
- });
242
- }
243
-
244
- // -- Breadcrumb from page types (mirrors original pageTypesToBreadcrumbList) --
245
-
246
- function pageTypesToBreadcrumb(pageTypes: PageType[]) {
247
- const filtered = pageTypes.filter(
248
- (pt) =>
249
- pt.pageType === "Category" || pt.pageType === "Department" || pt.pageType === "SubCategory",
250
- );
251
- return filtered.map((page, index) => {
252
- const position = index + 1;
253
- const slugParts = filtered.slice(0, position).map((x) => {
254
- const urlPath = x.url ? new URL(`http://${x.url}`).pathname : "";
255
- const segments = urlPath.split("/").filter(Boolean);
256
- return segments[segments.length - 1]?.toLowerCase() ?? "";
257
- });
258
- return {
259
- "@type": "ListItem" as const,
260
- name: page.name,
261
- item: `/${slugParts.join("/")}`,
262
- position,
263
- };
264
- });
265
- }
266
-
267
- // -- SEO from page types (mirrors original pageTypesToSeo) --
268
-
269
- function pageTypesToSeo(pageTypes: PageType[]) {
270
- const current = pageTypes[pageTypes.length - 1];
271
- if (!current) return undefined;
272
- return {
273
- title: current.title || current.name || "",
274
- description: current.metaTagDescription || "",
275
- };
276
- }
277
-
278
- // -- Build IS query params (mirrors original withDefaultParams) --
279
-
280
- function buildISParams(opts: {
281
- query: string;
282
- page: number;
283
- count: number;
284
- sort: string;
285
- fuzzy?: string;
286
- locale: string;
287
- hideUnavailableItems: boolean;
288
- }): Record<string, string> {
289
- const params: Record<string, string> = {
290
- page: String(opts.page + 1), // IS API is 1-indexed
291
- count: String(opts.count),
292
- query: opts.query,
293
- sort: opts.sort,
294
- locale: opts.locale,
295
- hideUnavailableItems: String(opts.hideUnavailableItems),
296
- };
297
- if (opts.fuzzy) params.fuzzy = opts.fuzzy;
298
- return params;
299
- }
300
-
301
- const INVALID_PLP_PREFIXES = [
302
- "/image/",
303
- "/.well-known/",
304
- "/assets/",
305
- "/favicon",
306
- "/_serverFn/",
307
- "/_build/",
308
- "/node_modules/",
309
- ];
310
-
311
- function isValidPLPPath(path: string): boolean {
312
- const lower = path.toLowerCase();
313
- if (INVALID_PLP_PREFIXES.some((p) => lower.startsWith(p))) return false;
314
- const ext = lower.split("/").pop()?.split(".")?.pop();
315
- if (
316
- ext &&
317
- [
318
- "png",
319
- "jpg",
320
- "jpeg",
321
- "gif",
322
- "svg",
323
- "webp",
324
- "ico",
325
- "css",
326
- "js",
327
- "woff",
328
- "woff2",
329
- "ttf",
330
- ].includes(ext)
331
- ) {
332
- return false;
333
- }
334
- return true;
335
- }
336
-
337
- /**
338
- * Mirrors the original deco-cx/apps PLP loader:
339
- *
340
- * 1. Resolve facets from CMS props or Page Type API
341
- * 2. Call product_search AND facets APIs in parallel (same params)
342
- * 3. Transform products to schema.org format
343
- * 4. Transform facets to FilterToggle format
344
- * 5. Build pagination from IS response
345
- */
346
- export default async function vtexProductListingPage(props: PLPProps): Promise<any | null> {
347
- const pageUrl = props.__pageUrl ? new URL(props.__pageUrl, "https://localhost") : null;
348
-
349
- const query = props.query ?? pageUrl?.searchParams.get("q") ?? "";
350
- const countFromUrl = pageUrl?.searchParams.get("PS");
351
- const rawCount = Number(countFromUrl ?? props.count ?? 12);
352
- const count = Number.isFinite(rawCount) && rawCount > 0 ? rawCount : 12;
353
- const sort = props.sort || pageUrl?.searchParams.get("sort") || "";
354
- // props.fuzzy is a friendly LabelledFuzzy ("automatic"|…) — translate it to the
355
- // raw IS API value. The URL param is already a raw value, so it passes through.
356
- const fuzzy =
357
- mapLabelledFuzzyToFuzzy(props.fuzzy) ?? pageUrl?.searchParams.get("fuzzy") ?? undefined;
358
- const page = resolvePage(props.page, pageUrl?.searchParams.get("page"));
359
-
360
- const { selectedFacets: cmsSelectedFacets, hideUnavailableItems = false, __pagePath } = props;
361
-
362
- try {
363
- // 1. Resolve selected facets (CMS + URL filter.* params, matching original)
364
- let facets: SelectedFacet[] =
365
- cmsSelectedFacets && cmsSelectedFacets.length > 0 ? [...cmsSelectedFacets] : [];
366
-
367
- // Extract filter.* params from URL (e.g. filter.category-1=telhas)
368
- if (pageUrl) {
369
- for (const [name, value] of pageUrl.searchParams.entries()) {
370
- const dotIndex = name.indexOf(".");
371
- if (dotIndex > 0 && name.slice(0, dotIndex) === "filter") {
372
- const key = name.slice(dotIndex + 1);
373
- if (key && !facets.some((f) => f.key === key && f.value === value)) {
374
- facets.push({ key, value });
375
- }
376
- }
377
- }
378
- }
379
-
380
- // Handle VTEX `map` query param (e.g. /1368?map=productClusterIds).
381
- // The `map` param tells IS how to interpret each path segment as a facet type.
382
- // Segments and map values are positionally matched (comma-separated).
383
- if (facets.length === 0 && pageUrl && __pagePath) {
384
- const mapParam = pageUrl.searchParams.get("map");
385
- if (mapParam) {
386
- const segments = __pagePath.split("/").filter(Boolean);
387
- const mapValues = mapParam.split(",");
388
- for (let i = 0; i < Math.min(segments.length, mapValues.length); i++) {
389
- const key = mapValues[i].trim();
390
- const value = decodeURIComponent(segments[i]);
391
- if (key && value) {
392
- facets.push({ key, value });
393
- }
394
- }
395
- }
396
- }
397
-
398
- let pageTypes: PageType[] = [];
399
-
400
- if (
401
- facets.length === 0 &&
402
- !query &&
403
- __pagePath &&
404
- __pagePath !== "/" &&
405
- __pagePath !== "/*" &&
406
- isValidPLPPath(__pagePath)
407
- ) {
408
- const allPageTypes = await pageTypesFromPath(__pagePath);
409
- pageTypes = getValidPageTypes(allPageTypes);
410
- facets = filtersFromPageTypes(pageTypes);
411
- }
412
-
413
- if (!facets.length && !query) {
414
- return null;
415
- }
416
-
417
- const facetPath = toFacetPath(facets);
418
- const config = getVtexConfig();
419
- const locale = config.locale ?? "pt-BR";
420
-
421
- const params = buildISParams({
422
- query,
423
- page,
424
- count,
425
- sort,
426
- fuzzy,
427
- locale,
428
- hideUnavailableItems,
429
- });
430
-
431
- const productEndpoint = facetPath ? `/product_search/${facetPath}` : "/product_search/";
432
-
433
- const facetsEndpoint = facetPath ? `/facets/${facetPath}` : "/facets/";
434
-
435
- // 2. Parallel calls — exactly like the original
436
- const [productsResult, facetsResult] = await Promise.all([
437
- intelligentSearch<ISProductSearchResult>(productEndpoint, params),
438
- intelligentSearch<ISFacetsResult>(facetsEndpoint, params),
439
- ]);
440
-
441
- const { products: vtexProducts, pagination, recordsFiltered } = productsResult;
442
-
443
- // 3. Transform products using shared transform pipeline (same as deco-cx/apps)
444
- const baseUrl = config.publicUrl
445
- ? `https://${config.publicUrl}`
446
- : `https://${config.account}.vtexcommercestable.com.br`;
447
-
448
- const schemaProducts = (vtexProducts as ProductVTEX[]).map((p) => {
449
- const sku = pickSku(p);
450
- return toProduct(p, sku, 0, { baseUrl, priceCurrency: "BRL" });
451
- });
452
-
453
- // Persist URL params (q, sort, filter.*) across filter toggles and pagination links
454
- const paramsToPersist = new URLSearchParams();
455
- if (pageUrl) {
456
- for (const [k, v] of pageUrl.searchParams.entries()) {
457
- if (k !== "page" && k !== "PS" && !k.startsWith("filter.")) {
458
- paramsToPersist.append(k, v);
459
- }
460
- }
461
- } else {
462
- if (query) paramsToPersist.set("q", query);
463
- if (sort) paramsToPersist.set("sort", sort);
464
- }
465
-
466
- // 4. Transform facets to filters (matching original toFilter)
467
- const visibleFacets = facetsResult.facets.filter((f) => !f.hidden);
468
- const basePath = __pagePath && __pagePath !== "/" ? __pagePath : "";
469
- const filters = visibleFacets.map(toFilter(facets, paramsToPersist, basePath));
470
-
471
- // 5. Build pagination (matching original logic)
472
- const currentPageoffset = 1;
473
- const hasNextPage = Boolean(pagination.next?.proxyUrl);
474
- const hasPreviousPage = page > 0;
475
-
476
- const nextPageParams = new URLSearchParams(paramsToPersist);
477
- const prevPageParams = new URLSearchParams(paramsToPersist);
478
-
479
- // Re-add active filter.* params so pagination links preserve selected filters
480
- for (const { key, value } of facets) {
481
- nextPageParams.append(`filter.${key}`, value);
482
- prevPageParams.append(`filter.${key}`, value);
483
- }
484
-
485
- if (hasNextPage) {
486
- nextPageParams.set("page", String(page + currentPageoffset + 1));
487
- }
488
- if (hasPreviousPage) {
489
- prevPageParams.set("page", String(page + currentPageoffset - 1));
490
- }
491
-
492
- const breadcrumbItems = pageTypesToBreadcrumb(pageTypes);
493
-
494
- return {
495
- "@type": "ProductListingPage",
496
- breadcrumb: {
497
- "@type": "BreadcrumbList",
498
- itemListElement: breadcrumbItems,
499
- numberOfItems: breadcrumbItems.length,
500
- },
501
- filters,
502
- products: schemaProducts,
503
- pageInfo: {
504
- nextPage: hasNextPage ? `${basePath}?${nextPageParams}` : undefined,
505
- previousPage: hasPreviousPage ? `${basePath}?${prevPageParams}` : undefined,
506
- currentPage: page + currentPageoffset,
507
- records: recordsFiltered,
508
- recordPerPage: pagination.perPage,
509
- },
510
- sortOptions: [
511
- { value: "", label: "relevance:desc" },
512
- { value: "price:desc", label: "price:desc" },
513
- { value: "price:asc", label: "price:asc" },
514
- { value: "orders:desc", label: "orders:desc" },
515
- { value: "name:desc", label: "name:desc" },
516
- { value: "name:asc", label: "name:asc" },
517
- { value: "release:desc", label: "release:desc" },
518
- { value: "discount:desc", label: "discount:desc" },
519
- ],
520
- seo: pageTypesToSeo(pageTypes),
521
- };
522
- } catch (error) {
523
- console.error("[VTEX] PLP error:", error);
524
- return null;
525
- }
526
- }
@@ -1,46 +0,0 @@
1
- /**
2
- * IS autocomplete suggestions loader.
3
- * Maps VTEX IS response to commerce Suggestion type.
4
- */
5
-
6
- import type { Product, Suggestion } from "@decocms/apps-commerce/types";
7
- import { getVtexConfig, intelligentSearch } from "../../client";
8
- import { pickSku, toProduct } from "../../utils/transform";
9
- import type { Product as ProductVTEX } from "../../utils/types";
10
-
11
- export interface SuggestionsProps {
12
- query?: string;
13
- count?: number;
14
- }
15
-
16
- export default async function vtexSuggestions(props: SuggestionsProps): Promise<Suggestion | null> {
17
- const query = props.query || "";
18
- if (!query.trim()) return { searches: [], products: [] };
19
-
20
- try {
21
- const data = await intelligentSearch<{
22
- searches: Array<{ term: string; count: number }>;
23
- products: ProductVTEX[];
24
- }>("/autocomplete_suggestions/", { query });
25
-
26
- const searches = (data.searches ?? []).map((s) => ({
27
- term: s.term,
28
- hits: s.count || 0,
29
- }));
30
-
31
- const config = getVtexConfig();
32
- const baseUrl = config.publicUrl
33
- ? `https://${config.publicUrl}`
34
- : `https://${config.account}.vtexcommercestable.${config.domain ?? "com.br"}`;
35
-
36
- const products: Product[] = (data.products ?? []).slice(0, props.count ?? 4).map((p) => {
37
- const sku = pickSku(p);
38
- return toProduct(p, sku, 0, { baseUrl, priceCurrency: "BRL" });
39
- });
40
-
41
- return { searches, products };
42
- } catch (error) {
43
- console.error("[VTEX] Suggestions error:", error);
44
- return null;
45
- }
46
- }
@@ -1 +0,0 @@
1
- export { default, type PDPProps } from "../intelligentSearch/productDetailsPage";
@@ -1 +0,0 @@
1
- export { default, type ProductListProps } from "../intelligentSearch/productList";
@@ -1,81 +0,0 @@
1
- /**
2
- * Related/cross-selling products loader using Legacy Catalog API + shared transform.
3
- * Maps VTEX catalog response to schema.org Product[] following deco-cx/apps pattern.
4
- *
5
- * Includes in-flight dedup for slug→productId resolution so multiple sections
6
- * on the same page (similars, suggestions, whoboughtalsobought, etc.) share a
7
- * single search/{slug}/p call instead of each doing their own.
8
- */
9
-
10
- import type { Product } from "@decocms/apps-commerce/types";
11
- import { getVtexConfig, vtexCachedFetch } from "../../client";
12
- import { resolveProductIdBySlug } from "../../utils/slugCache";
13
- import { pickSku, toProduct } from "../../utils/transform";
14
- import type { LegacyProduct } from "../../utils/types";
15
-
16
- export type CrossSellingType =
17
- | "similars"
18
- | "suggestions"
19
- | "accessories"
20
- | "whosawalsosaw"
21
- | "whosawalsobought"
22
- | "whoboughtalsobought"
23
- | "showtogether";
24
-
25
- export interface RelatedProductsProps {
26
- slug?: string;
27
- productId?: string;
28
- crossSelling?: CrossSellingType;
29
- count?: number;
30
- hideUnavailableItems?: boolean;
31
- }
32
-
33
- function fetchCrossSelling(
34
- type: CrossSellingType,
35
- productId: string,
36
- ): Promise<LegacyProduct[] | null> {
37
- return vtexCachedFetch<LegacyProduct[]>(
38
- `/api/catalog_system/pub/products/crossselling/${type}/${productId}`,
39
- );
40
- }
41
-
42
- export default async function vtexRelatedProducts(
43
- props: RelatedProductsProps,
44
- ): Promise<Product[] | null> {
45
- const { slug, crossSelling = "similars", count = 8 } = props;
46
-
47
- let productId = props.productId;
48
-
49
- if (!productId) {
50
- if (!slug) return null;
51
- const linkText = slug.replace(/\/p$/, "").replace(/^\//, "");
52
- productId = (await resolveProductIdBySlug(linkText)) ?? undefined;
53
- if (!productId) return null;
54
- }
55
-
56
- try {
57
- const related = await fetchCrossSelling(crossSelling, productId);
58
- if (!related?.length) return [];
59
-
60
- const config = getVtexConfig();
61
- const baseUrl = config.publicUrl
62
- ? `https://${config.publicUrl}`
63
- : `https://${config.account}.vtexcommercestable.${config.domain ?? "com.br"}`;
64
-
65
- let result = related.slice(0, count).map((p) => {
66
- const sku = pickSku(p);
67
- return toProduct(p, sku, 0, { baseUrl, priceCurrency: "BRL" });
68
- });
69
-
70
- if (props.hideUnavailableItems) {
71
- result = result.filter((p) =>
72
- p.offers?.offers?.some((o) => o.availability === "https://schema.org/InStock"),
73
- );
74
- }
75
-
76
- return result;
77
- } catch (error) {
78
- console.error("[VTEX] Related products error:", error);
79
- return null;
80
- }
81
- }