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): booleanTrue when prices should be shown tax-inclusive (Magento "including").
selectCartSubtotal function
selectCartSubtotal(prices: CartPrices | null | undefined, mode: ProductPriceDisplay): MoneyType | nullCart subtotal to display, tax-inclusive or -exclusive per mode.
selectRowTotal function
selectRowTotal(item: CartItem, mode: ProductPriceDisplay): MoneyType | nullLine-item row total to display, tax-inclusive or -exclusive per mode.
selectUnitPrice function
selectUnitPrice(item: CartItem, mode: ProductPriceDisplay): MoneyType | nullPer-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 | nullShipping 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 | nullTotal 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 | nullPre-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.
@magenxcommerce/engine/utils/cookie-consent
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.
ConsentCategory type
type ConsentCategory = "necessary" | "analytics" | "marketing" | "preferences"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.
CookieConsent interface
| Member | Type | Description |
|---|---|---|
necessary | true | Always true — required for the site to operate. |
analytics | boolean | Anonymised traffic & behaviour analytics (e.g. GA4). |
marketing | boolean | Ad targeting and remarketing. |
preferences | boolean | Personalisation / UX preferences (e.g. recently viewed). |
consentGiven | boolean | Whether the visitor has actively made a choice. |
consentDate | string | ISO-8601 timestamp of the consent action. |
version | string | Bump this whenever the consent form changes to force re-consent. |
CONSENT_STORAGE_KEY const
const CONSENT_STORAGE_KEY = "magenx_cookie_consent"CONSENT_VERSION const
const CONSENT_VERSION = "1.0"OPEN_PREFERENCES_EVENT const
const OPEN_PREFERENCES_EVENT = "magenx:open-cookie-preferences"Open-preferences custom event dispatched by the footer "Cookie Preferences" button.
getStoredConsent function
getStoredConsent(): CookieConsent | nullReturns the stored consent if it exists and matches the current version, otherwise null.
saveConsent function
saveConsent(choices: Pick<CookieConsent, "analytics" | "marketing" | "preferences">): CookieConsentPersists consent choices and returns the full stored object.
acceptAllConsent function
acceptAllConsent()Convenience helpers
declineAllConsent function
declineAllConsent()COOKIE_CATEGORIES const
const COOKIE_CATEGORIES: { id: ConsentCategory; name: string; description: string; required: boolean; }[]The four cookie categories displayed in the preferences dialog.
@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
| Member | Type | Description |
|---|---|---|
__typename | string | |
id | number | |
uid | string | |
sku | string | |
name | string | |
url_key | string | |
price_range | PriceRange | |
image? | { url: string; label?: string | null } | null | |
stock_status? | "IN_STOCK" | "OUT_OF_STOCK" | |
price_history? | PriceHistory | null |
toRecentlyViewedItem function
toRecentlyViewedItem(product: ProductInterface): RecentlyViewedItemPicks 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): stringConverts 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"): stringFormats a price value as a localised currency string.
toErrorMessage function
toErrorMessage(err: unknown, fallback: string): stringNarrows 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 safeStoragelocalStorage 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" }): stringFormats 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; }): stringdecodeMagentoId function
decodeMagentoId(encoded: string | null | undefined): number | nullDecode 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.