Repository navigation
fix: type safety, SWR caching, slug dedup, and PLP URL param persistence - #1
Conversation
… types Checkout actions were missing the `sc` (salesChannel) query parameter, which could cause ORD027 errors when items are only available in a specific sales channel. Also replaces `any` return types with a full `OrderForm` interface aligned with deco-cx/apps vtex/utils/types.ts. Changes: - checkout.ts: add scParam()/appendSc() helpers that read salesChannel from getVtexConfig() and append ?sc= to every checkout endpoint - checkout.ts: all functions now return Promise<OrderForm> instead of any - types.ts: add OrderForm, Totalizer, Message, MarketingData, ClientProfileData, StorePreferencesData, ShippingData, PaymentData interfaces matching the full VTEX Checkout API response shape Made-with: Cursor
- client.ts: add URL sanitization (UTM, map, ft params) ported from fetchVTEX.ts - checkout.ts: add salesChannel to getInstallments, fix simulateCart sc injection - inline-loaders: fix PDP (add sc, skuId, kitItems support), productList (add collection, SKU IDs, sort, hideUnavailableItems), relatedProducts (fix cross-selling types to match VTEX API), workflowProducts (fix collection via facet path), suggestions (use schema.org types via transform pipeline) - brands.ts: return schema.org Brand[] via toBrand() instead of raw VtexBrand - enrichment.ts: add withSimilars, withKitItems, withVariants, withReviews, withInventory, withBrands enrichers ported from product/extend.ts - masterData.ts: add searchDocumentsFull with REST-Range, fields, sort, pagination - New files: useAutocomplete.ts (React Query + debounce), wishlistProducts.ts (wishlist as ProductListingPage), resourceRange.ts - auth.ts, session.ts, wishlist.ts, vtexId.ts: use buildAuthCookieHeader constant - middleware.ts, segment.ts: improved cookie/segment handling Made-with: Cursor
- Configure knip to detect unused files, exports, and dependencies - Add scripts: lint:unused, lint:unused:fix, check (tsc + knip) - Add typescript and knip as devDependencies - Current result: zero issues Made-with: Cursor
- vtex/invoke.ts: use `as unknown as` for VtexFetchResult->OrderForm casts (TS2352)
- vtex/client.ts: add vtexCachedFetch with SWR in-memory cache via fetchCache
- vtex/inline-loaders/productDetailsPage.ts: use slug cache to deduplicate /search/{slug}/p calls
- vtex/inline-loaders/productListingPage.ts: read q/sort/filter.* from __pageUrl, persist URL
params across filter toggles and pagination links
- vtex/inline-loaders/relatedProducts.ts: use slugCache.resolveProductIdBySlug to avoid
duplicate slug lookups when multiple cross-selling sections render on the same PDP
- vtex/actions/masterData.ts: add uploadAttachment action for file uploads to MasterData
- vtex/utils/proxy.ts: fix redirect rewriting (vtexOrigin vs host-only replacement)
- knip.json: add vtex/*.ts to entry points and ignore @decocms/start peer dep false positive
Made-with: Cursor
There was a problem hiding this comment.
12 issues found across 42 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="vtex/utils/similars.ts">
<violation number="1" location="vtex/utils/similars.ts:25">
P2: Use the configured VTEX domain when building baseUrl. The current hardcoded `.com.br` ignores `config.domain`, so environments with a custom domain will generate broken product URLs for similars.</violation>
</file>
<file name="vtex/loaders/wishlistProducts.ts">
<violation number="1" location="vtex/loaders/wishlistProducts.ts:41">
P2: Clamp the computed page index to 0 before slicing; negative page values will cause `.slice()` to pull items from the end of the list.</violation>
</file>
<file name="vtex/utils/fetchCache.ts">
<violation number="1" location="vtex/utils/fetchCache.ts:48">
P2: Non-OK responses are thrown before caching, which makes the configured 404 TTL path unreachable.</violation>
</file>
<file name="vtex/actions/checkout.ts">
<violation number="1" location="vtex/actions/checkout.ts:403">
P2: `updateOrderFormProfile` is the only `vtexFetchWithCookies<OrderForm>` caller that skips `forceHttpsOnAssets`. The profile endpoint still returns a full OrderForm containing items, so image URLs can remain `http:`.</violation>
</file>
<file name="vtex/actions/auth.ts">
<violation number="1" location="vtex/actions/auth.ts:132">
P2: When `startAuthentication()` is called internally (no token provided), its `setCookies` are discarded. `sendEmailVerification` correctly merges both cookie sets, but `classicSignIn` and `resetPassword` lose the cookies from the first request. This could cause auth failures if the `startAuthentication` response sets cookies required by the caller.</violation>
</file>
<file name="vtex/inline-loaders/productListingPage.ts">
<violation number="1" location="vtex/inline-loaders/productListingPage.ts:242">
P2: `PS` is not validated before numeric conversion, so invalid input can propagate `count=NaN` to the search API.</violation>
<violation number="2" location="vtex/inline-loaders/productListingPage.ts:329">
P1: Pagination URLs drop active `filter.*` params, so moving between pages can clear selected filters.</violation>
</file>
<file name="vtex/utils/slugCache.ts">
<violation number="1" location="vtex/utils/slugCache.ts:18">
P2: Encode `linkText` before interpolating it into the request path to avoid malformed slug lookup URLs.</violation>
</file>
<file name="vtex/utils/enrichment.ts">
<violation number="1" location="vtex/utils/enrichment.ts:479">
P1: `inProductGroupWithID` is the product **group** ID, not a SKU ID. The `/api/logistics/pvt/inventory/skus/{skuId}` endpoint expects a SKU ID. Use `product.sku` instead to get the correct inventory data.</violation>
</file>
<file name="vtex/client.ts">
<violation number="1" location="vtex/client.ts:222">
P1: Set-Cookie collection logic is inverted: `getSetCookie()` should be the primary path, not the fallback. `Headers.forEach()` can merge multiple `Set-Cookie` headers into one concatenated string, making `setCookies.length > 0` and preventing the correct `getSetCookie()` branch from running. This will silently corrupt multi-cookie checkout responses (e.g. losing the session cookie).</violation>
</file>
<file name="vtex/actions/masterData.ts">
<violation number="1" location="vtex/actions/masterData.ts:136">
P2: Use the configured VTEX domain instead of hardcoding `.com.br` so attachments work in non-standard environments.</violation>
</file>
<file name="vtex/inline-loaders/relatedProducts.ts">
<violation number="1" location="vtex/inline-loaders/relatedProducts.ts:36">
P2: Do not convert cross-selling request failures into empty results; this masks API errors as valid empty recommendations.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
- similars.ts, masterData.ts: use config.domain instead of hardcoded .com.br - wishlistProducts.ts: clamp page index to 0 to prevent negative slice - fetchCache.ts: cache 404 responses (non-5xx) instead of throwing, enabling configured 404 TTL - checkout.ts: apply forceHttpsOnAssets to updateOrderFormProfile response - auth.ts: preserve setCookies from startAuthentication in classicSignIn and resetPassword; remove unused vtexFetchResponse import - productListingPage.ts: validate PS param before Number() to avoid NaN propagation; re-add active filter.* params to pagination links - slugCache.ts: encodeURIComponent linkText to prevent malformed URLs - enrichment.ts: use product.sku (SKU ID) instead of inProductGroupWithID (group ID) for inventory endpoint - client.ts: prefer getSetCookie() over forEach for Set-Cookie collection to avoid multi-cookie merge corruption - relatedProducts.ts: remove silent .catch(() => []) so cross-selling errors propagate to outer try-catch Made-with: Cursor
There was a problem hiding this comment.
4 issues found across 11 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="vtex/utils/fetchCache.ts">
<violation number="1" location="vtex/utils/fetchCache.ts:54">
P2: `fetchWithCache<T>` can now return `null` at runtime while still being typed as `Promise<T>`, breaking type safety for callers.</violation>
<violation number="2" location="vtex/utils/fetchCache.ts:96">
P1: Background revalidation stores non-cacheable 4xx responses, which can overwrite a good cached value with `null` data.</violation>
</file>
<file name="vtex/utils/enrichment.ts">
<violation number="1" location="vtex/utils/enrichment.ts:478">
P2: Guard missing SKU before calling the inventory endpoint to avoid invalid `/skus/` requests.</violation>
</file>
<file name="vtex/inline-loaders/productListingPage.ts">
<violation number="1" location="vtex/inline-loaders/productListingPage.ts:285">
P2: Validate and clamp the parsed `page` value to avoid propagating `NaN`/negative pages into search params and pageInfo.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
- fetchCache.ts: fix return type to Promise<T | null> to reflect runtime behavior for cached 4xx responses; fix background revalidation to only overwrite store when the fresh response is itself cacheable (prevents null replacing good data) - enrichment.ts: guard missing SKU before calling inventory endpoint to avoid malformed /skus/ requests - productListingPage.ts: clamp parsed page to >= 0 to prevent NaN/negative values propagating into search params and pageInfo - client.ts: propagate T | null from vtexCachedFetch, filter nulls from pageTypesFromPath, cast intelligentSearch (which throws on non-ok so never returns null) - productDetailsPage.ts: handle null kitItems with ?? [] fallback - relatedProducts.ts: update fetchCrossSelling return type to LegacyProduct[] | null Made-with: Cursor
There was a problem hiding this comment.
1 issue found across 6 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="vtex/utils/fetchCache.ts">
<violation number="1" location="vtex/utils/fetchCache.ts:103">
P2: Revalidation currently allows 404 responses to overwrite previously successful cache entries. Restrict overwrite to successful responses so transient 4xx does not replace good cached data.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
Made-with: Cursor
There was a problem hiding this comment.
1 issue found across 1 file (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="vtex/utils/fetchCache.ts">
<violation number="1" location="vtex/utils/fetchCache.ts:102">
P2: Revalidation now ignores cacheable 404 responses, so stale 404 entries never refresh and can trigger repeated network calls on every request.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
|
🎉 This PR is included in version 0.20.1 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
…eno prod)
Adds 21 unit tests across 3 files covering the surfaces this PR ports.
Tests pin behavior the Fresh/Deno production code (deco-cx/apps/magento)
established, so future refactors of the apps-start port can refactor
freely without drifting from prod.
magento/__tests__/client.test.ts (12 tests):
configureMagento / getMagentoConfig:
- throws before configure (no implicit defaults)
- returns the configured value after configure
magentoFetch — same-origin:
- attaches Authorization + x-origin-header + forced Referer
- resolves relative path against baseUrl
- authenticated:false drops Bearer (still attaches origin/referer)
- preserves caller-supplied Referer (no force-overwrite)
magentoFetch — cross-origin guard:
- strips Bearer (regression for cubic finding #1)
- strips x-origin-header (regression for cubic finding #2)
- strips forced Referer (regression for cubic finding #2)
- forwards caller-supplied headers through
- same-origin absolute URL still gets identity headers
magento/__tests__/features.test.ts (2 tests):
- returns the configured features object
- returns {} when features omitted
magento/__tests__/cart.test.ts (7 tests):
- returns null when no cookie (matches prod's `if (!cartId) return null`)
- reads dataservices_cart_id cookie (JSON-quoted form)
- reads dataservices_cart_id cookie (raw form, no quotes)
- props.cartId override beats the cookie
- URL-encodes cartId — regression for cubic finding #3 (path injection)
- 404 returns null (expired cookie)
- non-404 errors throw
- cart fetch attaches Bearer + x-origin-header (same-origin)
Drive-by fix: cart loader was hitting /:site/V1/carts/:cartId, but Magento
exposes the cart endpoint at /rest/:site/V1/carts/:cartId — the /rest/
prefix is mandatory and matches the legacy clientAdmin's typed key
`GET /rest/:site/V1/carts/:cartId`. Tests pin the corrected path.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…61) * feat(magento): initial scaffold port from deco-cx/apps to apps-start Starts the Magento app port to @decocms/apps following the same shape as vtex/ and shopify/. This first commit lands the configure surface and 2 reference loaders (features, cart) — enough to unblock real consumer sites; the remaining ~20 loaders/actions are itemized in magento/README.md and will follow in separate commits. Contents: - magento/client.ts — configureMagento({ baseUrl, apiKey, storeId, ... }) with module-global state, mirroring configureVtex. magentoFetch() helper attaches Bearer auth + Referer + optional x-origin-header on every call. initMagentoFromBlocks(blocks) resolves the CMS block's `__resolveType: "website/loaders/secret.ts"` references via env vars, same fallback granadobr-tanstack already uses in production. - magento/types.ts — MagentoCart + MagentoCartItem shapes used by the ported loaders. - magento/loaders/features.ts — returns the resolved Features block from the config. The simplest loader, used as the smoke test. - magento/loaders/cart.ts — fetches the customer's active cart by reading `dataservices_cart_id` cookie via @decocms/start/sdk/cookie and calling the Magento admin REST endpoint. Returns null for anonymous sessions (expected) and on 404 (expired cookie). - magento/middleware.ts — passthrough today; the legacy changeCardIdAfterCheckout reconciliation flow is deferred to a follow-up PR. - magento/index.ts — re-export entry, parallel to vtex/index.ts. - package.json — adds @decocms/apps/magento/* exports. Motivation: deco-sites/granadobr-tanstack (Granado, Brazilian cosmetics) just migrated from Fresh/Deno to TanStack Start. Its parity audit reported a HIGH severity finding: invoke(magento/loaders/features) failed: handler not found …because no @decocms/apps/magento/* resolver existed. The site is working around it with an in-site adapter that re-uses the legacy mod.ts shape; this PR begins the upstream fix so the next Magento storefront doesn't need to repeat the work. Companion issue: #60 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(magento): address 3 cubic-dev-ai review findings (all P1) 1. package.json: `magento/` was in `exports` but not `files`. npm publish excludes any path not listed under `files`, so the entire magento folder would be missing from the published tarball — every consumer site would get module-resolution errors. Added `magento/` to the array alongside commerce/shopify/vtex/etc. 2. magento/loaders/cart.ts: cartId comes from a request cookie (`dataservices_cart_id`) and was spliced into the admin REST path unencoded. Wrapped both `site` and `cartId` in encodeURIComponent so user input can't break out of the path segment to tack on query or fragment parts that would hit a different endpoint with the privileged Bearer token attached. 3. magento/client.ts: magentoFetch() accepted any `path` value, including absolute URLs to arbitrary hosts. The auth headers (Bearer, Referer, x-origin-header) were attached unconditionally, so a caller passing `https://attacker.example/...` would leak the Magento admin token. Now constructs a URL up front, compares its origin against the configured baseUrl, and force-disables `authenticated` when the request is cross-origin. Genuine third-party calls remain possible via the explicit `authenticated: false` opt-out. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(magento): biome formatting + add magento/** to lint includes Biome's includes array was missing magento/**, so the new package was skipped by lint entirely. Added it to the includes alongside the other apps. Also ran biome --write to convert space indentation to tab (project convention) across the 5 magento source files. Note: the test job also surfaces pre-existing lint errors in vtex/__tests__/ client-set-cookie-forward.test.ts and website/components/__tests__/ OneDollarStats.test.ts. Those are unrelated to this PR — they were already failing on main before any magento file was added. Splitting that into a separate PR. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(magento): strip ALL Magento-identity headers in cross-origin requests Cubic's second pass caught that the previous fix only suppressed the Bearer token but still leaked `x-origin-header` (an opaque secret) and a forced `Referer` pointing at the Magento storefront URL whenever a caller passed an absolute non-Magento URL. Now `buildHeaders` takes an explicit `attachMagentoIdentity` flag. `magentoFetch` sets it to `target.origin === baseUrl.origin`, so a cross-origin call gets only whatever headers the caller passed in their `opts.headers` — no Magento-side credentials, no origin-header secret, no forced Referer. Callers wanting a genuinely cross-origin GET should still flip `authenticated: false` at the call site for intent, but security no longer relies on that single flag being correct. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(magento): pin behavior parity with deco-cx/apps/magento (Fresh/Deno prod) Adds 21 unit tests across 3 files covering the surfaces this PR ports. Tests pin behavior the Fresh/Deno production code (deco-cx/apps/magento) established, so future refactors of the apps-start port can refactor freely without drifting from prod. magento/__tests__/client.test.ts (12 tests): configureMagento / getMagentoConfig: - throws before configure (no implicit defaults) - returns the configured value after configure magentoFetch — same-origin: - attaches Authorization + x-origin-header + forced Referer - resolves relative path against baseUrl - authenticated:false drops Bearer (still attaches origin/referer) - preserves caller-supplied Referer (no force-overwrite) magentoFetch — cross-origin guard: - strips Bearer (regression for cubic finding #1) - strips x-origin-header (regression for cubic finding #2) - strips forced Referer (regression for cubic finding #2) - forwards caller-supplied headers through - same-origin absolute URL still gets identity headers magento/__tests__/features.test.ts (2 tests): - returns the configured features object - returns {} when features omitted magento/__tests__/cart.test.ts (7 tests): - returns null when no cookie (matches prod's `if (!cartId) return null`) - reads dataservices_cart_id cookie (JSON-quoted form) - reads dataservices_cart_id cookie (raw form, no quotes) - props.cartId override beats the cookie - URL-encodes cartId — regression for cubic finding #3 (path injection) - 404 returns null (expired cookie) - non-404 errors throw - cart fetch attaches Bearer + x-origin-header (same-origin) Drive-by fix: cart loader was hitting /:site/V1/carts/:cartId, but Magento exposes the cart endpoint at /rest/:site/V1/carts/:cartId — the /rest/ prefix is mandatory and matches the legacy clientAdmin's typed key `GET /rest/:site/V1/carts/:cartId`. Tests pin the corrected path. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
VtexFetchResult<OrderForm>→OrderFormusandoas unknown asvtexCachedFetchcom cache in-memory (fetchCache) para GETs ao VTEX — IS queries e pageType chamadas agora deduplican e reutilizam respostas por 3minslugCache.resolveProductIdBySlugevita múltiplas chamadas/search/{slug}/pquando várias seções na mesma PDP precisam do productIdproductListingPagelêq,sortefilter.*de__pageUrl, preservando filtros através de paginação e toggles de facetsuploadAttachmentpara uploads de arquivos via base64vtex/*.tscomo entry points e ignora falso positivo de peer depTest plan
npm run typecheckpassa sem errosnpm run lint:unusedsem erros