Skip to content

Engine: Utilities

Pure helpers: class-name merging, price formatting and tax-aware cart pricing, CMS HTML sanitising, recently-viewed products and cookie consent storage.

Generated from packages/engine/src/utils/: 5 files, 30 exported symbols. Signatures and types are shown as written in the source.

@magenxcommerce/engine/utils/cart-pricing

packages/engine/src/utils/cart-pricing.ts

Cart price selection helpers.

Magento's cart always returns both tax-exclusive and tax-inclusive money fields. Which one a storefront should display depends on the merchant's Magento tax display setting, mirrored into config as tax.productPriceDisplay. These helpers pick the right field so cart, mini-cart, and checkout summaries stay consistent with the catalog.

isTaxInclusive function

isTaxInclusive(mode: ProductPriceDisplay): boolean

True when prices should be shown tax-inclusive (Magento "including").

selectCartSubtotal function

selectCartSubtotal(prices: CartPrices | null | undefined, mode: ProductPriceDisplay): MoneyType | null

Cart subtotal to display, tax-inclusive or -exclusive per mode.

selectRowTotal function

selectRowTotal(item: CartItem, mode: ProductPriceDisplay): MoneyType | null

Line-item row total to display, tax-inclusive or -exclusive per mode.

selectUnitPrice function

selectUnitPrice(item: CartItem, mode: ProductPriceDisplay): MoneyType | null

Per-unit price to show beside a cart line ("… each").

Derived from the line's row total (same tax basis as the figure shown next to it, and already inclusive of any selected custom-option costs) divided by quantity, so "each × qty" always reconciles with the row total. Reading the catalog price_range here instead — as the cart used to — ignores option costs and the configured tax basis, so the unit price and row total visibly disagree.

selectShippingAmount function

selectShippingAmount(address: CheckoutShippingAddress | null | undefined): MoneyType | null

Shipping charge of the address's selected method.

Magento's selected_shipping_method.amount is the address's stored shipping_amount, which the setShippingMethodsOnCart response can carry before totals are recollected — 0 (or the previous method's price) while grand_total in the same payload already includes the new charge. The matching rate in available_shipping_methods is priced fresh on every read, so it is preferred; the stored amount is the fallback when the rate is absent from the payload.

selectSetupFeesTotal function

selectSetupFeesTotal(items: ReadonlyArray<CartItem> | null | undefined, fallbackCurrency = "USD"): MoneyType | null

Total of one-time subscription setup fees across the cart.

Stripe subscription products carry a one-time initial_fee that Magento folds into grand_total but does NOT include in subtotal_*. Without a dedicated summary line the totals don't reconcile (subtotal + shipping ≠ grand_total) and the customer sees an unexplained jump to the total. This sums the per-line setup fees so cart/checkout summaries can itemize them. The fee is one-time per subscription line, so it is NOT multiplied by the line quantity (matching how Magento folds it into grand_total).

selectCartEstimatedTotal function

selectCartEstimatedTotal(prices: CartPrices | null | undefined, mode: ProductPriceDisplay, items?: ReadonlyArray<CartItem> | null): MoneyType | null

Pre-shipping order total to show on the cart ("estimated total").

Magento folds an auto-selected shipping method (e.g. flat rate) into grand_total even before the customer reaches checkout, so rendering grand_total on the cart contradicts the "Shipping — calculated at checkout" line and surprises the customer with a fee they never chose. This rebuilds the merchandise total (subtotal ± tax − discounts + one-time subscription setup fees) without shipping; shipping is added at checkout once a method is selected. Pass items to fold in subscription setup fees (also part of grand_total) so the estimate reconciles with checkout.

packages/engine/src/utils/cookie-consent.ts

GDPR / CCPA Cookie Consent -------------------------- Handles consent preference storage and retrieval via localStorage. Categories follow IAB-style granular consent: necessary (always true), analytics, marketing, and preferences.

@magenxcommerce/engine/utils/html

packages/engine/src/utils/html.ts

sanitizeCmsHtml function

sanitizeCmsHtml(html: string)

@magenxcommerce/engine/utils/recently-viewed

packages/engine/src/utils/recently-viewed.ts

RecentlyViewedItem interface

MemberTypeDescription
__typenamestring
idnumber
uidstring
skustring
namestring
url_keystring
price_rangePriceRange
image?{ url: string; label?: string | null } | null
stock_status?"IN_STOCK" | "OUT_OF_STOCK"
price_history?PriceHistory | null

toRecentlyViewedItem function

toRecentlyViewedItem(product: ProductInterface): RecentlyViewedItem

Picks the fields required for a RecentlyViewedItem from a full ProductInterface.

getRecentlyViewed function

getRecentlyViewed(): RecentlyViewedItem[]

addRecentlyViewed function

addRecentlyViewed(product: RecentlyViewedItem): void

@magenxcommerce/engine/utils/utils

packages/engine/src/utils/utils.ts

normalizeLocale function

normalizeLocale(locale: string): string

Converts Magento-style locale tags (e.g. "en_US") to BCP 47 (e.g. "en-US").

formatPrice function

formatPrice(amount: number, currency: string, locale = "en-US"): string

Formats a price value as a localised currency string.

@param
amount - Numeric price value.
@param
currency - ISO 4217 currency code (e.g. "EUR", "USD").
@param
locale - BCP 47 locale string (e.g. "en-US", "de-DE"). Defaults to "en-US"; callers should pass the active store view's locale (the theme's useStoreFormat() binds it to the URL locale for exactly this reason).

toErrorMessage function

toErrorMessage(err: unknown, fallback: string): string

Narrows an unknown thrown value to its message, falling back when it isn't an Error. Shared by the cart / wishlist contexts and the checkout helpers so the err instanceof Error ? err.message : fallback idiom lives in one place.

safeStorage const

const safeStorage

localStorage access that never throws. The native methods throw in private-browsing mode, when storage is disabled by the user, or when the quota is exceeded — which in a critical path (persisting order state during checkout, cart bootstrap) would abort the flow. These wrappers swallow those errors and the SSR case (localStorage undefined) so callers can treat storage as best-effort; reads return null on any failure (indistinguishable from a missing key, which every caller already handles).

formatMagentoDate function

formatMagentoDate(value: string | null | undefined, locale: string, options: Intl.DateTimeFormatOptions = { dateStyle: "medium" }): string

Formats a Magento date string (e.g. "2026-07-07 03:00:00") for display. Magento uses a space between date and time; we normalize it to ISO before parsing. Returns "" for an empty or unparseable value.

uniqueBy function

uniqueBy<T, K>(items: T[], getKey: (item: T) => K): T[]

getProductIdentityKey function

getProductIdentityKey(product: { id?: number | string | null; uid?: string | null; sku?: string | null; url_key?: string | null; }): string

decodeMagentoId function

decodeMagentoId(encoded: string | null | undefined): number | null

Decode a Magento GraphQL base64-encoded entity id (e.g. the id on CustomerOrder / OrderItemInterface) to its integer entity id.

Magento's SalesGraphQl encodes these ids as base64_encode((string) $id). The RMA create-return mutations want the raw integer (order_id, order_item_id), so the storefront decodes them here. Tolerates an id that is already a plain integer string (returns it as-is). Returns null when the value can't be resolved to a positive integer, so callers can skip it.