@simpleapps-com/augur-hooks 2026.11.6 → 2026.11.8

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/stuartjackson/Projects/simpleapps/atlas/repo/packages/augur-hooks/dist/index.cjs","../src/provider.tsx","../src/stores/items-filters-store.ts","../src/hooks/use-debounce.ts","../src/hooks/use-format-price.ts","../src/hooks/use-stock.ts","../src/hooks/use-cart-actions.ts","../src/hooks/use-modal-lifecycle.ts","../src/hooks/use-cart-initialization.ts","../src/hooks/use-cart-pricing.ts","../src/hooks/use-pagination-prefetch.ts","../src/persistence/use-persistence.ts","../src/persistence/create-persister.ts","../src/persistence/serializer.ts","../src/persistence/apply-limits.ts","../src/persistence/use-storage-monitor.ts","../src/user-write-clearing.ts"],"names":["useMemo","useEffect","useQuery","useQueryClient","cleanMoney","useCallback","useState","minutes","toMillis"],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;AC/CA,8BAAmE;AAOnE;AACE;AACA;AACA;AAAA,uDACK;AAiEK,+CAAA;AA1CZ,IAAM,gBAAA,EAAkB,kCAAA,IAAiC,CAAA;AACzD,IAAM,sBAAA,EAAwB,kCAAA,KAA4C,CAAS,CAAA;AACnF,IAAM,kBAAA,EAAoB,kCAAA,KAAuC,CAAS,CAAA;AAC1E,IAAM,oBAAA,EAAsB,kCAAA,IAA2B,CAAA;AACvD,IAAM,iBAAA,EAAmB,kCAAA,KAA2C,CAAS,CAAA;AAiBtE,SAAS,kBAAA,CAAmB,EAAE,GAAA,EAAK,IAAA,EAAM,K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ACpB,IAAA;AACF,EAAA;AACmB,EAAA;AACrB;AAQgB;AAII,EAAA;AACC,EAAA;AACL,IAAA;AACb,EAAA;AACH;AAcgB;AACP,EAAA;AACc,IAAA;AAErB,EAAA;AACF;AhBu9BwB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/stuartjackson/Projects/simpleapps/atlas/repo/packages/augur-hooks/dist/index.cjs","sourcesContent":[null,"import { createContext, useContext, useMemo, type ReactNode } from \"react\";\nimport type {\n AugurAuthContext,\n AugurSiteConfig,\n CacheConfig,\n DeepQueryOptions,\n} from \"@simpleapps-com/augur-core\";\nimport {\n createOptionsProxy,\n createQueryActionProxy,\n createKeysOnlyProxy,\n} from \"@simpleapps-com/augur-core\";\nimport type { OptionsProxyConfig } from \"@simpleapps-com/augur-core\";\nimport type { AugurAPI } from \"@simpleapps-com/augur-api\";\nimport { useLatest } from \"./hooks/use-latest\";\nimport { getRegisteredQueryAction } from \"./query-action-registry\";\n\n/** The augur-api SDK instance, as `useAugurApi()` returns it (the SDK is a peer dependency). */\nexport type AugurApiClient = AugurAPI;\n\ninterface AugurHooksProviderProps {\n /** SDK client instance. When omitted, `useAugurOptions()` returns a keys-only\n * proxy — consumers MUST override queryFn with a server action at each call site.\n * Any object is accepted (a site's test double included); hooks read it as the SDK. */\n api?: object;\n /** Optional auth context — hooks fall back to these values when not passed directly. */\n auth?: AugurAuthContext;\n /** Optional cache configuration — controls edge and Redis caching per tier. */\n cache?: CacheConfig;\n /** Optional site configuration — hooks read defaults and formatting from this. */\n site?: AugurSiteConfig;\n children: ReactNode;\n}\n\nconst AugurApiContext = createContext<object | null>(null);\nconst AugurAuthReactContext = createContext<AugurAuthContext | undefined>(undefined);\nconst AugurCacheContext = createContext<CacheConfig | undefined>(undefined);\nconst AugurOptionsContext = createContext<unknown>(null);\nconst AugurSiteContext = createContext<AugurSiteConfig | undefined>(undefined);\n\n/**\n * Provides the augur-api SDK instance, proxy options, and auth to all hooks.\n *\n * ```tsx\n * <AugurHooksProvider api={api} auth={authContext} cache={cacheConfig}>\n * <App />\n * </AugurHooksProvider>\n * ```\n *\n * Components use `useAugurOptions()` to get the proxy:\n * ```tsx\n * const q = useAugurOptions();\n * const { data } = useQuery(q.items.invMast.get(42));\n * ```\n */\nexport function AugurHooksProvider({ api, auth, cache, site, children }: AugurHooksProviderProps) {\n const proxyConfig: OptionsProxyConfig | undefined = cache\n ? { cache: { static: cache.static, semiStatic: cache.semiStatic } }\n : undefined;\n\n // The proxy is rebuilt when the api changes; the cache config is read at that point, not\n // watched (it is a new object on every render).\n const proxyConfigRef = useLatest(proxyConfig);\n const options = useMemo(() => {\n const config = proxyConfigRef.current;\n if (api) return createOptionsProxy(api, config);\n const registeredAction = getRegisteredQueryAction();\n if (registeredAction) return createQueryActionProxy(registeredAction, config);\n return createKeysOnlyProxy(config);\n }, [api, proxyConfigRef]);\n\n return (\n <AugurApiContext.Provider value={api ?? null}>\n <AugurAuthReactContext.Provider value={auth}>\n <AugurCacheContext.Provider value={cache}>\n <AugurSiteContext.Provider value={site}>\n <AugurOptionsContext.Provider value={options}>{children}</AugurOptionsContext.Provider>\n </AugurSiteContext.Provider>\n </AugurCacheContext.Provider>\n </AugurAuthReactContext.Provider>\n </AugurApiContext.Provider>\n );\n}\n\n/**\n * Returns the deep proxy for creating TanStack Query options.\n *\n * When an `api` prop is provided to the provider, every path returns\n * full query options (queryKey, queryFn, staleTime, gcTime).\n *\n * When no `api` is provided (server-only JWT sites), returns a keys-only\n * proxy — queryKey, staleTime, and gcTime are generated normally, but\n * queryFn throws unless overridden. This lets B2B sites use the proxy\n * for deterministic keys and cache tiers while routing data through\n * server actions.\n *\n * @example\n * ```tsx\n * // With api (direct SDK access):\n * const q = useAugurOptions();\n * const { data } = useQuery(q.items.invMast.get(42));\n *\n * // Without api (server-only JWT):\n * const q = useAugurOptions();\n * const { data } = useQuery({\n * ...q.items.invMast.doc.get(42),\n * queryFn: () => getItemAction(42), // server action\n * });\n * ```\n */\nexport function useAugurOptions<T = DeepQueryOptions<AugurAPI>>(): T {\n const options = useContext(AugurOptionsContext);\n if (!options) {\n throw new Error(\n \"useAugurOptions must be used within an <AugurHooksProvider>. \" +\n \"Wrap your app with <AugurHooksProvider>.\",\n );\n }\n return options as T;\n}\n\n/**\n * Returns the augur-api SDK instance from context, or null if not provided.\n * Used internally by hooks that need the SDK for fallback queries.\n */\nexport function useAugurApiOptional(): AugurApiClient | null {\n return useContext(AugurApiContext) as AugurApiClient | null;\n}\n\n/**\n * Returns the augur-api SDK instance from context.\n * Throws if called outside of `<AugurHooksProvider>` or when no api is provided.\n */\nexport function useAugurApi(): AugurApiClient {\n const api = useContext(AugurApiContext) as AugurApiClient | null;\n if (!api) {\n throw new Error(\n \"useAugurApi must be used within an <AugurHooksProvider>. \" +\n \"Wrap your app with <AugurHooksProvider api={apiInstance}>.\",\n );\n }\n return api;\n}\n\n/**\n * Returns the provider-level auth context, if any.\n * Used internally by hooks to fall back to provider auth when\n * auth fields are not passed directly as hook parameters.\n */\nexport function useAugurAuth(): AugurAuthContext | undefined {\n return useContext(AugurAuthReactContext);\n}\n\n/**\n * Returns the provider-level cache configuration, if any.\n * Used internally by hooks to enable edge/Redis caching.\n */\nexport function useAugurCache(): CacheConfig | undefined {\n return useContext(AugurCacheContext);\n}\n\n/**\n * Returns the site configuration from the nearest `AugurHooksProvider`.\n * Returns `undefined` when no `site` prop is provided.\n */\nexport function useAugurSite(): AugurSiteConfig | undefined {\n return useContext(AugurSiteContext);\n}\n","import { create } from \"zustand\";\nimport { devtools } from \"zustand/middleware\";\nimport type { TItemsFilters } from \"@simpleapps-com/augur-utils\";\n\n/** Default filter values used when the store is first created or reset. */\nconst DEFAULT_FILTER_STATE: TItemsFilters = {\n filters: [],\n limit: 12,\n offset: 0,\n sortBy: \"asc\",\n q: \"\",\n page: 1,\n};\n\n/** Zustand state shape for item list filtering, sorting, and pagination. */\ninterface ItemsFiltersState {\n /** Snapshot of the initial defaults; useful for \"reset filters\" UIs. */\n initialFiltersState: TItemsFilters;\n /** Current active filter/sort/pagination state. */\n itemsFilters: TItemsFilters;\n /** Replace the entire filter state. */\n setItemsFilters: (itemFilters: TItemsFilters) => void;\n}\n\n/** Zustand store for item list filters, sorting, and pagination state. */\nexport const useItemFiltersStore = create<ItemsFiltersState>()(\n devtools(\n (set) => ({\n initialFiltersState: DEFAULT_FILTER_STATE,\n itemsFilters: DEFAULT_FILTER_STATE,\n setItemsFilters: (state) => set({ itemsFilters: state }, false, \"setItemsFilters\"),\n }),\n {\n name: \"ItemsFiltersStore\",\n enabled: process.env[\"NODE_ENV\"] === \"development\",\n },\n ),\n);\n","import { useEffect, useState } from \"react\";\n\n/**\n * Debounces a rapidly-changing value.\n * Returns the latest value only after `delay` ms of inactivity.\n */\nexport function useDebounce<T>(value: T, delay: number = 500): T {\n const [debouncedValue, setDebouncedValue] = useState<T>(value);\n\n useEffect(() => {\n const handler = setTimeout(() => {\n setDebouncedValue(value);\n }, delay);\n\n return () => {\n clearTimeout(handler);\n };\n }, [value, delay]);\n\n return debouncedValue;\n}\n","import type { AugurSiteFormatting } from \"@simpleapps-com/augur-core\";\nimport { cleanMoney } from \"@simpleapps-com/augur-utils\";\nimport { useAugurSite } from \"../provider\";\nimport { zeroLabelShown } from \"../rules\";\n\n/** Options for configuring the useFormatPrice hook. */\nexport interface UseFormatPriceOptions {\n /** BCP 47 locale tag. Overrides site.formatting.locale. */\n locale?: string;\n /** ISO 4217 currency code. Overrides site.formatting.currency. */\n currency?: string;\n /** Decimal digits. Overrides site.formatting.precision. */\n precision?: number;\n /** Label returned when the effective value is 0 (e.g. \"Call for Price\"). */\n zeroLabel?: string;\n}\n\n/** Per-call options passed to the returned formatPrice function. */\nexport interface FormatPriceCallOptions {\n /** Override decimal digits for this call only. */\n precision?: number;\n /** Multiply the value by this quantity before formatting. */\n quantity?: number;\n}\n\nfunction normaliseOptions(\n optionsOrLocale: UseFormatPriceOptions | string | undefined,\n legacyCurrency: string | undefined,\n): UseFormatPriceOptions {\n if (typeof optionsOrLocale === \"string\") {\n return { locale: optionsOrLocale, currency: legacyCurrency };\n }\n return optionsOrLocale ?? {};\n}\n\nfunction resolveFormatting(\n opts: UseFormatPriceOptions,\n siteFormatting: AugurSiteFormatting | undefined,\n) {\n const site: Partial<AugurSiteFormatting> = siteFormatting ?? {};\n return {\n locale: opts.locale ?? site.locale ?? \"en-US\",\n currency: opts.currency ?? site.currency ?? \"USD\",\n precision: opts.precision ?? site.precision ?? 2,\n zeroLabel: opts.zeroLabel ?? site.zeroLabel,\n };\n}\n\n/**\n * Hook that returns a price formatter.\n * Reads defaults from site config when params are omitted.\n *\n * Supports both the new options-object signature and the legacy positional\n * `(locale?, currency?)` signature for backwards compatibility.\n */\nexport function useFormatPrice(\n optionsOrLocale?: UseFormatPriceOptions | string,\n legacyCurrency?: string,\n) {\n const site = useAugurSite();\n const opts = normaliseOptions(optionsOrLocale, legacyCurrency);\n const {\n locale,\n currency,\n precision: basePrecision,\n zeroLabel,\n } = resolveFormatting(opts, site?.formatting);\n\n const formatPrice = (price: number, callOptions?: FormatPriceCallOptions): string => {\n // cleanMoney drops float noise so a line formats to the same cent as the cart total (GH #496).\n const effectiveValue = cleanMoney(price * (callOptions?.quantity ?? 1));\n\n if (zeroLabelShown(effectiveValue === 0, zeroLabel !== undefined)) {\n return zeroLabel as string;\n }\n\n const precision = callOptions?.precision ?? basePrecision;\n\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n minimumFractionDigits: precision,\n maximumFractionDigits: precision,\n }).format(effectiveValue);\n };\n\n return { formatPrice };\n}\n","import { useMemo } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport type { ResolvedStock, TStock } from \"@simpleapps-com/augur-utils\";\nimport { resolveStock } from \"@simpleapps-com/augur-utils\";\nimport { useAugurOptions } from \"../provider\";\nimport { stockEnabled, stockRetryDelay } from \"../rules\";\n\nexport interface UseStockOptions {\n enabled?: boolean;\n /** Override the default queryFn (e.g. with a custom server action). */\n queryFn?: () => Promise<TStock>;\n /** Company key to extract stock for a specific company. */\n companyKey?: string;\n /** Whether to round the quantity. */\n round?: boolean;\n /** Threshold below which stock is considered \"low\". */\n lowStockThreshold?: number;\n /** Whether to include the quantity in the resolved output. */\n showQuantity?: boolean;\n}\n\n/** Raw stock, its resolved form, and query state returned by useStock. */\ninterface StockResult {\n stock: TStock | null;\n resolved: ResolvedStock | null;\n loading: boolean;\n error: Error | null;\n}\n\n/**\n * Fetches full TStock data and resolves it into a normalized stock object.\n *\n * Uses the proxy from AugurHooksProvider context. Works with:\n * - Direct SDK (api prop on provider)\n * - Server actions (auto-detected via queryAction registration)\n * - Custom queryFn override\n */\nexport function useStock(invMastUid: number | string, options: UseStockOptions = {}): StockResult {\n const proxy = useAugurOptions();\n\n const resolvedQueryFn = options.queryFn;\n\n // Use the proxy for query options (works with SDK, server actions, or keys-only)\n const proxyOpts = proxy.items.invMast.stock.get(Number(invMastUid));\n\n const query = useQuery({\n ...proxyOpts,\n ...(resolvedQueryFn ? { queryFn: resolvedQueryFn } : {}),\n enabled: stockEnabled(options.enabled, !!invMastUid),\n retry: 3,\n retryDelay: stockRetryDelay,\n });\n\n // Every proxy resolves to the unwrapped SDK data (augur-core unwrapBaseResponse).\n const stockData = (query.data as TStock | undefined) ?? null;\n\n const resolved = useMemo(\n () =>\n resolveStock({\n stock: stockData,\n companyKey: options.companyKey,\n round: options.round,\n lowStockThreshold: options.lowStockThreshold,\n showQuantity: options.showQuantity,\n }),\n [stockData, options.companyKey, options.round, options.lowStockThreshold, options.showQuantity],\n );\n\n return {\n stock: stockData,\n resolved,\n loading: query.isLoading,\n error: query.error as Error | null,\n };\n}\n","import { useCallback } from \"react\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { TCartLine } from \"@simpleapps-com/augur-utils\";\nimport { lineHasQuantity } from \"@simpleapps-com/augur-utils\";\nimport { hasNumberFrom } from \"@atlas/utils/lists\";\nimport {\n addAccepted,\n indexOfUidFrom,\n indexOfUnitFrom,\n keepsAfterReverse,\n qtyOrZero,\n requiredCartUid,\n rollsBack,\n sendsPrice,\n toastShown,\n} from \"../rules\";\nimport { useCartStore, useCartHdrUid, useCartLines, useSetCartLines } from \"../stores/cart-store\";\n\ntype CartLineInput = {\n invMastUid: number;\n quantity: number;\n unitOfMeasure: string;\n cartHdrUid?: number | string | undefined;\n};\n\n/**\n * One cart line as `updateCartLines` sends it: `lineNo` 0, so the server's `update()` matches it\n * by item and unit of measure (a line number can be stale after a remove renumbers the cart), and\n * `unitPrice` only when the line has one (the route stores a sent `null` as 0.0). atlas#89.\n */\nexport type CartLineUpdate = Omit<TCartLine, \"unitPrice\"> & { unitPrice?: number };\n\n/** Site-specific callbacks injected into useCartActions. Each resolves `true` on success. */\nexport interface CartActionCallbacks {\n /** Add items to cart via API. `true` = success, `false` = failure. */\n addToCart: (\n cartHdrUid: number,\n items: Array<{\n cartHdrUid: number;\n invMastUid: number;\n quantity: number;\n unitOfMeasure: string;\n }>,\n ) => Promise<boolean>;\n /** Update cart lines via API (the one changed line). `true` = success, `false` = failure. */\n updateCartLines: (cartHdrUid: number, lines: CartLineUpdate[]) => Promise<boolean>;\n /** Delete all items from cart via API. `true` = success, `false` = failure. */\n deleteItemsFromCart: (cartHdrUid: number) => Promise<boolean>;\n /** Optional toast notification callback. */\n toast?: {\n info?: (message: string) => void;\n error?: (message: string) => void;\n success?: (message: string) => void;\n };\n}\n\ninterface CartActionOptions {\n showToast?: boolean;\n itemId?: string;\n /**\n * The line's unit of measure, for an item in the cart in more than one; without it, the unit of\n * the item's first line. `updateQuantity` and `removeFromCart` change only that line.\n */\n unitOfMeasure?: string;\n onSuccess?: () => void;\n onError?: (error: Error) => void;\n}\n\n/** Actions and state returned by useCartActions. */\ninterface CartActions {\n addToCart: (item: CartLineInput, options?: CartActionOptions) => Promise<boolean>;\n updateQuantity: (\n invMastUid: number,\n newQuantity: number,\n options?: CartActionOptions,\n ) => Promise<boolean>;\n removeFromCart: (invMastUid: number, options?: CartActionOptions) => Promise<boolean>;\n clearCart: (options?: Omit<CartActionOptions, \"itemId\" | \"unitOfMeasure\">) => Promise<boolean>;\n isInCart: (invMastUid: number) => boolean;\n getItemQuantity: (invMastUid: number) => number;\n cartHdrUid: number | string | undefined;\n cartLines: TCartLine[];\n invalidateCartCache: () => void;\n}\n\n/** A store cart uid as a number, or undefined when unset (NaN is no uid, as `!num` treated it). */\nfunction cartUidOf(cartHdrUid: string | number | undefined): number | undefined {\n const num = typeof cartHdrUid === \"string\" ? Number(cartHdrUid) : cartHdrUid;\n return num === undefined || Number.isNaN(num) ? undefined : num;\n}\n\nfunction requireCartUid(cartHdrUid: string | number | undefined): number {\n const uid = requiredCartUid(cartUidOf(cartHdrUid));\n if (uid === null) throw new Error(\"Cart UID is not set\");\n return uid;\n}\n\n/** The store's LIVE cart (not a render closure), so concurrent ops stack; throws with no cart UID. */\nfunction liveCart(): { uid: number; lines: TCartLine[] } {\n const { cartHdrUid, cartLines } = useCartStore.getState();\n return { uid: requireCartUid(cartHdrUid), lines: cartLines };\n}\n\nfunction buildOptimisticAdd(\n cartLines: TCartLine[],\n item: CartLineInput,\n cartHdrUid: number,\n itemId: string,\n): TCartLine[] {\n const existingIndex = indexOfUidFrom(uidsOf(cartLines), item.invMastUid, 0);\n\n if (existingIndex >= 0) {\n return cartLines.map((line, index) =>\n index === existingIndex\n ? { ...line, quantity: qtyOrZero(line.quantity) + item.quantity }\n : line,\n );\n }\n\n return [\n ...cartLines,\n {\n cartHdrUid,\n invMastUid: item.invMastUid,\n invMastUidCount: 1,\n isAssembly: \"N\",\n itemId,\n lineNo: cartLines.length + 1,\n lineNote: null,\n quantity: item.quantity,\n unitOfMeasure: item.unitOfMeasure,\n key: null,\n unitPrice: null,\n },\n ];\n}\n\n// --- Targeted optimistic-rollback helpers ---------------------------------\n// Each reverses ONLY its own op's delta against the LIVE store state (passed\n// in from useCartStore.getState()), never a stale render-closure snapshot,\n// and only while the store still holds the op's cart (settleCartOp).\n\n/**\n * Reverse an optimistic add.\n * @invariant only the FIRST line with the item loses q (buildOptimisticAdd added to the first\n * only; atlas#89 finding 7), dropped iff nothing is left; other lines untouched.\n */\nfunction reverseAdd(cartLines: TCartLine[], invMastUid: number, quantity: number): TCartLine[] {\n const index = indexOfUidFrom(uidsOf(cartLines), invMastUid, 0);\n if (index < 0) return cartLines;\n const line = cartLines[index] as TCartLine;\n if (!keepsAfterReverse(line.quantity, quantity)) {\n return [...cartLines.slice(0, index), ...cartLines.slice(index + 1)];\n }\n return cartLines.map((l, i) =>\n i === index ? { ...l, quantity: qtyOrZero(l.quantity) - quantity } : l,\n );\n}\n\n/** The line an update or remove changes, as an index (or −1): item and unit of measure. */\ninterface Target {\n invMastUid: number;\n unit: string;\n}\n\n/**\n * The target line's index: the first line with the item in `unitOfMeasure`, or in the unit of the\n * item's first line when none is given.\n */\nfunction targetOf(\n cartLines: TCartLine[],\n invMastUid: number,\n unitOfMeasure: string | undefined,\n): Target | null {\n const first = indexOfUidFrom(uidsOf(cartLines), invMastUid, 0);\n if (first < 0) return null;\n const unit = unitOfMeasure ?? unitOf(cartLines[first] as TCartLine);\n if (indexOfUnitFrom(uidsOf(cartLines), unitsOf(cartLines), invMastUid, unit, 0) < 0) return null;\n return { invMastUid, unit };\n}\n\n/** Whether a line is the target's: same item and unit of measure. */\nfunction isTarget(line: TCartLine, target: Target): boolean {\n return (\n indexOfUnitFrom([line.invMastUid], [unitOf(line)], target.invMastUid, target.unit, 0) === 0\n );\n}\n\n/** The target's first line (it exists: `targetOf` found it). */\nfunction targetLine(cartLines: TCartLine[], target: Target): TCartLine {\n const index = indexOfUnitFrom(\n uidsOf(cartLines),\n unitsOf(cartLines),\n target.invMastUid,\n target.unit,\n 0,\n );\n return cartLines[index] as TCartLine;\n}\n\n/**\n * Reverse an optimistic quantity set.\n * @invariant the target's lines go back to their pre-op quantity; other lines untouched.\n */\nfunction reverseQuantity(\n cartLines: TCartLine[],\n target: Target,\n previousQuantity: TCartLine[\"quantity\"],\n): TCartLine[] {\n return cartLines.map((line) =>\n isTarget(line, target) ? { ...line, quantity: previousQuantity } : line,\n );\n}\n\n/**\n * Reverse an optimistic remove by re-inserting the removed line.\n * @invariant re-adds removedLine iff no line of its item and unit is there now (a concurrent op\n * may have re-added it; never duplicate).\n */\nfunction restoreRemoved(\n cartLines: TCartLine[],\n target: Target,\n removedLine: TCartLine,\n): TCartLine[] {\n if (\n indexOfUnitFrom(uidsOf(cartLines), unitsOf(cartLines), target.invMastUid, target.unit, 0) >= 0\n ) {\n return cartLines;\n }\n return [...cartLines, removedLine];\n}\n\n/**\n * Reverse an optimistic clear by restoring snapshot lines missing from live state.\n * @invariant result ⊇ live ∧ result ⊇ snapshot (by invMastUid); concurrent adds\n * that landed after the clear are preserved, cleared lines are restored.\n */\nfunction mergeRestore(cartLines: TCartLine[], snapshot: TCartLine[]): TCartLine[] {\n const merged = [...cartLines];\n for (const line of snapshot) {\n if (!hasNumberFrom(uidsOf(merged), line.invMastUid, 0)) merged.push(line);\n }\n return merged;\n}\n\n/** The line as `updateCartLines` sends it: the quantity, `lineNo` 0, a price only when set. */\nfunction sentLine(line: TCartLine, quantity: number): CartLineUpdate {\n const { unitPrice, ...rest } = line;\n const sent: CartLineUpdate = { ...rest, quantity, lineNo: 0 };\n if (sendsPrice(unitPrice)) sent.unitPrice = unitPrice as number;\n return sent;\n}\n\n/** Each line's item uid, in order. */\nfunction uidsOf(cartLines: TCartLine[]): number[] {\n return cartLines.map((line) => line.invMastUid);\n}\n\n/** A line's unit of measure, null as \"\". */\nfunction unitOf(line: TCartLine): string {\n return line.unitOfMeasure ?? \"\";\n}\n\n/** Each line's unit of measure, in order. */\nfunction unitsOf(cartLines: TCartLine[]): string[] {\n return cartLines.map(unitOf);\n}\n\n/** Calls `notify[kind]` as a method when toasts are on, it is set, and there is a message. */\nfunction sendToast(\n notify: CartActionCallbacks[\"toast\"],\n kind: \"info\" | \"error\",\n showToast: boolean,\n message: string | undefined,\n): void {\n if (toastShown(showToast, message !== undefined)) notify?.[kind]?.(message as string);\n}\n\n/** One cart op after its optimistic update: the server call and how it settles. */\ninterface CartOp {\n /** The cart the op ran on. */\n cartUid: number;\n call: () => Promise<boolean>;\n /** The error a falsy result becomes (what `onError` receives). */\n failure: string;\n /** The success toast, if the op has one. */\n infoMessage?: string;\n errorMessage: string;\n showToast: boolean;\n /** Undoes this op's own optimistic change against the live store. */\n rollback: () => void;\n}\n\n/**\n * Runs the server call. On success: the info toast, `onSuccess`, true. On a falsy result or a\n * throw: the rollback (only while the store still holds the op's cart), the error toast,\n * `onError`, false. Either way the op stops counting as in flight and the cart queries are\n * invalidated, so the live cart refetches and its data reaches the store (atlas#89).\n */\nasync function settleCartOp(\n op: CartOp,\n options: CartActionOptions,\n notify: CartActionCallbacks[\"toast\"],\n invalidate: () => void,\n): Promise<boolean> {\n const { endCartOp } = useCartStore.getState();\n try {\n const success = await op.call();\n if (!success) throw new Error(op.failure);\n } catch (error) {\n if (rollsBack(cartUidOf(useCartStore.getState().cartHdrUid), op.cartUid)) op.rollback();\n endCartOp();\n invalidate();\n sendToast(notify, \"error\", op.showToast, op.errorMessage);\n options.onError?.(error as Error);\n return false;\n }\n endCartOp();\n invalidate();\n sendToast(notify, \"info\", op.showToast, op.infoMessage);\n options.onSuccess?.();\n return true;\n}\n\n/**\n * Optimistic cart actions hook with automatic rollback on failure.\n *\n * Accepts site-specific server action callbacks so the hook itself\n * has no dependency on any particular server action implementation.\n *\n * @example\n * ```tsx\n * import { useCartActions } from \"@simpleapps-com/augur-hooks\";\n * import { addToCart, updateCartLines, deleteItemsFromCart } from \"@/lib/actions/commerce\";\n * import { toast } from \"react-toastify\";\n *\n * const cart = useCartActions({\n * addToCart, updateCartLines, deleteItemsFromCart,\n * toast: { info: toast.info, error: toast.error },\n * });\n *\n * await cart.addToCart({ invMastUid: 123, quantity: 1, unitOfMeasure: \"EA\" });\n * ```\n */\nexport function useCartActions(callbacks: CartActionCallbacks): CartActions {\n const queryClient = useQueryClient();\n const cartHdrUid = useCartHdrUid();\n const cartLines = useCartLines();\n const setCartLines = useSetCartLines();\n const notify = callbacks.toast;\n\n // Every cart's lines (the live cart's query refetches) and the render's also-bought.\n const invalidateCartCache = useCallback(() => {\n void queryClient.invalidateQueries({ queryKey: [\"cartLines\"] });\n void queryClient.invalidateQueries({\n queryKey: [\"cart-also-bought\", cartHdrUid],\n });\n }, [queryClient, cartHdrUid]);\n\n const addToCart = useCallback(\n async (item: CartLineInput, options: CartActionOptions = {}): Promise<boolean> => {\n const { showToast = true, itemId = \"\" } = options;\n // A cart line MUST have its unit of measure and its quantity: augur enforces neither (atlas#93).\n const quantity = Number.isFinite(item.quantity) ? item.quantity : null;\n if (!addAccepted(item.unitOfMeasure, quantity)) {\n sendToast(notify, \"error\", showToast, \"Choose a quantity and a unit of measure.\");\n options.onError?.(new Error(\"Quantity and unit of measure are required\"));\n return false;\n }\n const { uid, lines: liveLines } = liveCart();\n\n useCartStore.getState().beginCartOp();\n setCartLines(buildOptimisticAdd(liveLines, item, uid, itemId));\n\n return settleCartOp(\n {\n cartUid: uid,\n call: () =>\n callbacks.addToCart(uid, [\n {\n cartHdrUid: uid,\n invMastUid: item.invMastUid,\n quantity: item.quantity,\n unitOfMeasure: item.unitOfMeasure,\n },\n ]),\n failure: \"Failed to add item to cart\",\n infoMessage: `${item.quantity} x ${itemId || \"Item\"} added to cart`,\n errorMessage: \"Failed to add item to cart. Please try again.\",\n showToast,\n rollback: () =>\n setCartLines(\n reverseAdd(useCartStore.getState().cartLines, item.invMastUid, item.quantity),\n ),\n },\n options,\n notify,\n invalidateCartCache,\n );\n },\n [setCartLines, invalidateCartCache, callbacks, notify],\n );\n\n const updateQuantity = useCallback(\n async (\n invMastUid: number,\n newQuantity: number,\n options: CartActionOptions = {},\n ): Promise<boolean> => {\n const { showToast = false, unitOfMeasure } = options;\n // A cart line MUST have a quantity (AugurHooks.UpdateAccepted): NaN reaches augur as null,\n // which it writes as 0, deleting the line.\n if (!lineHasQuantity(Number.isFinite(newQuantity) ? newQuantity : null)) {\n sendToast(notify, \"error\", showToast, \"Choose a quantity.\");\n options.onError?.(new Error(\"Quantity is required\"));\n return false;\n }\n const { uid, lines: liveLines } = liveCart();\n const target = targetOf(liveLines, invMastUid, unitOfMeasure);\n // Not in the cart: nothing to change (the page offers this only on a line it shows).\n if (target === null) return true;\n const line = targetLine(liveLines, target);\n const previousQuantity = line.quantity;\n\n useCartStore.getState().beginCartOp();\n setCartLines(\n liveLines.map((l) => (isTarget(l, target) ? { ...l, quantity: newQuantity } : l)),\n );\n\n return settleCartOp(\n {\n cartUid: uid,\n call: () => callbacks.updateCartLines(uid, [sentLine(line, newQuantity)]),\n failure: \"Failed to update quantity\",\n errorMessage: \"Failed to update quantity. Please try again.\",\n showToast,\n rollback: () =>\n setCartLines(\n reverseQuantity(useCartStore.getState().cartLines, target, previousQuantity),\n ),\n },\n options,\n notify,\n invalidateCartCache,\n );\n },\n [setCartLines, invalidateCartCache, callbacks, notify],\n );\n\n const removeFromCart = useCallback(\n async (invMastUid: number, options: CartActionOptions = {}): Promise<boolean> => {\n const { showToast = true, itemId = \"\", unitOfMeasure } = options;\n const { uid, lines: liveLines } = liveCart();\n const target = targetOf(liveLines, invMastUid, unitOfMeasure);\n // Not in the cart: nothing to remove.\n if (target === null) return true;\n const removedLine = targetLine(liveLines, target);\n\n useCartStore.getState().beginCartOp();\n setCartLines(liveLines.filter((l) => !isTarget(l, target)));\n\n return settleCartOp(\n {\n cartUid: uid,\n call: () => callbacks.updateCartLines(uid, [sentLine(removedLine, 0)]),\n failure: \"Failed to remove item\",\n infoMessage: `${itemId || \"Item\"} removed from cart`,\n errorMessage: \"Failed to remove item. Please try again.\",\n showToast,\n rollback: () =>\n setCartLines(restoreRemoved(useCartStore.getState().cartLines, target, removedLine)),\n },\n options,\n notify,\n invalidateCartCache,\n );\n },\n [setCartLines, invalidateCartCache, callbacks, notify],\n );\n\n const clearCart = useCallback(\n async (options: Omit<CartActionOptions, \"itemId\" | \"unitOfMeasure\"> = {}): Promise<boolean> => {\n const { showToast = true } = options;\n const { uid, lines: snapshot } = liveCart();\n useCartStore.getState().beginCartOp();\n setCartLines([]);\n\n return settleCartOp(\n {\n cartUid: uid,\n call: () => callbacks.deleteItemsFromCart(uid),\n failure: \"Failed to clear cart\",\n infoMessage: \"Cart cleared\",\n errorMessage: \"Failed to clear cart. Please try again.\",\n showToast,\n rollback: () => setCartLines(mergeRestore(useCartStore.getState().cartLines, snapshot)),\n },\n options,\n notify,\n invalidateCartCache,\n );\n },\n [setCartLines, invalidateCartCache, callbacks, notify],\n );\n\n const isInCart = useCallback(\n (invMastUid: number): boolean => {\n return cartLines.some((line) => line.invMastUid === invMastUid);\n },\n [cartLines],\n );\n\n const getItemQuantity = useCallback(\n (invMastUid: number): number => {\n return cartLines.find((line) => line.invMastUid === invMastUid)?.quantity ?? 0;\n },\n [cartLines],\n );\n\n return {\n addToCart,\n updateQuantity,\n removeFromCart,\n clearCart,\n isInCart,\n getItemQuantity,\n cartHdrUid,\n cartLines,\n invalidateCartCache,\n };\n}\n","\"use client\";\nimport { useEffect, useState } from \"react\";\nimport { bodyOverflow, closesOnKey } from \"../rules\";\n\n/**\n * Shared modal lifecycle hook -- scroll lock, Escape key, client-side hydration gate.\n *\n * Locks body scroll when the modal is open and restores it on close.\n * Listens for Escape key to trigger onClose. Returns isClient for\n * hydration-safe conditional rendering.\n */\nexport function useModalLifecycle(isOpen: boolean, onClose: () => void) {\n const [isClient, setIsClient] = useState(false);\n\n useEffect(() => {\n setIsClient(true);\n }, []);\n\n // Scroll lock\n useEffect(() => {\n document.body.style.overflow = bodyOverflow(isOpen);\n return () => {\n document.body.style.overflow = \"auto\";\n };\n }, [isOpen]);\n\n // Escape key\n useEffect(() => {\n const handleEscape = (e: KeyboardEvent) => {\n if (closesOnKey(e.key, isOpen)) onClose();\n };\n document.addEventListener(\"keydown\", handleEscape);\n return () => document.removeEventListener(\"keydown\", handleEscape);\n }, [isOpen, onClose]);\n\n return { isClient };\n}\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport type { TCartLine } from \"@simpleapps-com/augur-utils\";\nimport { acceptsLookup, cartIdle, initStepOf } from \"../rules\";\nimport {\n useCartHdrUid,\n useCartStore,\n useSetCartHdrUid,\n useSetCartLines,\n useClearCart,\n} from \"../stores/cart-store\";\nimport { useAugurAuth } from \"../provider\";\n\nconst MAX_RETRY_ATTEMPTS = 7;\nconst RETRY_DELAY_MS = 1000;\n/** After a lookup's attempts all fail, it starts again this much later (atlas#89 finding 17). */\nconst LOOKUP_RESTART_MS = 30_000;\n\n/** Before another lookup attempt: wait 1 s × 1.5^attempt (at most 10 s); none after the last. */\nasync function waitBeforeRetry(attempt: number): Promise<void> {\n if (attempt >= MAX_RETRY_ATTEMPTS) return;\n const delay = Math.min(RETRY_DELAY_MS * Math.pow(1.5, attempt), 10000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n}\n\n/** Session info passed from the consumer's auth system. */\nexport interface CartSessionInfo {\n /** Auth status: \"loading\" | \"authenticated\" | \"unauthenticated\" */\n status: \"loading\" | \"authenticated\" | \"unauthenticated\";\n /** User's ID (e.g., Joomla user ID). Undefined if not authenticated. */\n userId?: string | number;\n /** Cart header UID from the auth session, if available. */\n cartHdrUid?: number | string;\n}\n\n/** Site-specific callbacks injected into useCartInitialization. */\nexport interface CartInitCallbacks {\n /** Look up or create a cart header. Returns { cartHdrUid, cartToken? }. */\n cartHdrLookup: (\n userId: string | number,\n cartToken: string,\n ) => Promise<{ cartHdrUid: number; cartToken?: string | null } | false | null | undefined>;\n /** Fetch cart line items for a given cart header UID. */\n getCartLines: (cartHdrUid: number) => Promise<TCartLine[] | undefined>;\n /** Get the current cart token. Defaults to localStorage.getItem(\"cartToken\"). */\n getCartToken?: () => string | null;\n /** Save cart token. Defaults to localStorage.setItem(\"cartToken\", token). */\n saveCartToken?: (token: string) => void;\n /** Generate a new unique cart token. Defaults to crypto.randomUUID(). */\n generateCartToken?: () => string;\n}\n\nconst defaultGetCartToken = () => localStorage.getItem(\"cartToken\");\nconst defaultSaveCartToken = (token: string) => localStorage.setItem(\"cartToken\", token);\nconst defaultGenerateCartToken = () => crypto.randomUUID();\n\n/** A cart uid as text, so a session's \"42\" and a store's 42 compare equal. */\nfunction cartKey(uid: number | string | undefined): string | undefined {\n return uid === undefined ? undefined : String(uid);\n}\n\n/**\n * Initialize cart state from session (authenticated) or cookie (guest).\n * Call once in the root layout.\n *\n * - A signed-in session's `cartHdrUid` is the cart, also when the store holds a guest cart.\n * - A signed-in session with no `cartHdrUid` looks the user's cart up (`cartHdrLookup(userId, …)`).\n * - A guest looks a cart up with its token (`cartHdrLookup(\"0\", …)`); a lookup's answer is used\n * only while the shopper is still in the state it was started for, with no cart set.\n * - A lookup whose attempts all fail starts again 30 s later.\n * - The cart's lines reach the store on every fetch while no cart op is in flight.\n *\n * @example\n * ```tsx\n * import { useCartInitialization } from \"@simpleapps-com/augur-hooks\";\n * import { useSession } from \"next-auth/react\";\n * import { cartHdrLookup, getCartLines } from \"@/lib/actions/commerce\";\n *\n * function CartInitializer() {\n * const { data: session, status } = useSession();\n *\n * // Minimal setup — token storage defaults to localStorage,\n * // token generation defaults to crypto.randomUUID().\n * useCartInitialization(\n * {\n * status,\n * userId: session?.user?.id,\n * cartHdrUid: session?.user?.cartHdrUid,\n * },\n * { cartHdrLookup, getCartLines },\n * );\n *\n * return null;\n * }\n * ```\n */\nexport function useCartInitialization(session: CartSessionInfo, callbacks: CartInitCallbacks) {\n const getCartToken = callbacks.getCartToken ?? defaultGetCartToken;\n const saveCartToken = callbacks.saveCartToken ?? defaultSaveCartToken;\n const generateCartToken = callbacks.generateCartToken ?? defaultGenerateCartToken;\n\n const auth = useAugurAuth();\n const cartHdrUid = useCartHdrUid();\n const setCartHdrUid = useSetCartHdrUid();\n const setCartLines = useSetCartLines();\n const clearCart = useClearCart();\n const queryClient = useQueryClient();\n\n // Merge session with provider auth — session fields take priority\n const effectiveStatus = session.status;\n const effectiveUserId = session.userId ?? auth?.userId;\n const effectiveCartHdrUid = session.cartHdrUid ?? auth?.cartHdrUid;\n const effectiveSession = useMemo<CartSessionInfo>(\n () => ({ status: effectiveStatus, userId: effectiveUserId, cartHdrUid: effectiveCartHdrUid }),\n [effectiveStatus, effectiveUserId, effectiveCartHdrUid],\n );\n\n const retryCountRef = useRef(0);\n const isInitializingRef = useRef(false);\n const prevStatusRef = useRef(effectiveSession.status);\n // The status now, for a lookup that answers after the session changed.\n const statusRef = useRef(effectiveSession.status);\n statusRef.current = effectiveSession.status;\n // Bumped 30 s after a lookup gave up, so the init effect runs (and looks up) again.\n const [lookupRound, setLookupRound] = useState(0);\n const restartTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n\n useEffect(() => () => clearTimeout(restartTimerRef.current), []);\n\n // Auto-clear cart on logout (authenticated → unauthenticated)\n useEffect(() => {\n const prevStatus = prevStatusRef.current;\n prevStatusRef.current = effectiveSession.status;\n\n if (prevStatus === \"authenticated\" && effectiveSession.status === \"unauthenticated\") {\n clearCart();\n queryClient.removeQueries({ queryKey: [\"cartLines\"] });\n queryClient.removeQueries({ queryKey: [\"cart-also-bought\"] });\n }\n }, [effectiveSession.status, clearCart, queryClient]);\n\n // Initialize cart header\n useEffect(() => {\n const step = initStepOf(\n effectiveSession.status === \"loading\",\n effectiveSession.status === \"authenticated\",\n !!effectiveSession.cartHdrUid,\n cartKey(cartHdrUid) === cartKey(effectiveSession.cartHdrUid),\n !!cartHdrUid,\n effectiveSession.userId !== undefined,\n isInitializingRef.current,\n );\n\n if (step.kind === \"stay\") return;\n\n if (step.kind === \"session\") {\n setCartHdrUid(effectiveSession.cartHdrUid);\n return;\n }\n\n // A lookup: the user's cart (signed in, no cart on the session) or a guest cart.\n const forUser = step.kind === \"user\";\n const lookupUserId = forUser ? (effectiveSession.userId as string | number) : \"0\";\n isInitializingRef.current = true;\n retryCountRef.current = 0;\n\n const lookUpCart = async () => {\n const existingToken = getCartToken();\n const cartToken =\n existingToken && typeof existingToken === \"string\" ? existingToken : generateCartToken();\n let lastError: unknown;\n\n while (retryCountRef.current < MAX_RETRY_ATTEMPTS) {\n try {\n const cartHdr = await callbacks.cartHdrLookup(lookupUserId, cartToken);\n\n if (cartHdr && cartHdr.cartHdrUid !== 0) {\n // The answer applies only if the shopper is still where it started, with no cart.\n const stillApplies = acceptsLookup(\n forUser,\n statusRef.current === \"authenticated\",\n !!useCartStore.getState().cartHdrUid,\n );\n if (stillApplies) {\n saveCartToken(cartToken);\n setCartHdrUid(cartHdr.cartHdrUid);\n }\n isInitializingRef.current = false;\n return;\n }\n\n retryCountRef.current++;\n await waitBeforeRetry(retryCountRef.current);\n } catch (error) {\n // Retries are expected; only the final failure is logged (below).\n lastError = error;\n retryCountRef.current++;\n await waitBeforeRetry(retryCountRef.current);\n }\n }\n\n console.error(`Cart initialization failed after ${MAX_RETRY_ATTEMPTS} attempts`, lastError);\n isInitializingRef.current = false;\n // Without a cart every action throws: look again later rather than never.\n restartTimerRef.current = setTimeout(() => setLookupRound((n) => n + 1), LOOKUP_RESTART_MS);\n };\n\n void lookUpCart();\n }, [\n effectiveSession,\n cartHdrUid,\n setCartHdrUid,\n callbacks,\n getCartToken,\n saveCartToken,\n generateCartToken,\n lookupRound,\n ]);\n\n // Fetch cart lines when cartHdrUid is available. No structural sharing: a refetch that equals\n // the last data still reaches the sync below, so a store a rollback left wrong is corrected.\n const { data: cartLinesData } = useQuery({\n queryKey: [\"cartLines\", cartHdrUid],\n queryFn: async () => (await callbacks.getCartLines(Number(cartHdrUid))) ?? [],\n enabled: !!cartHdrUid,\n structuralSharing: false,\n });\n\n // Sync cart lines to the Zustand store, while no cart op is in flight (one landing mid-op\n // would wipe its optimistic change; that op's settle refetches).\n useEffect(() => {\n if (cartLinesData && cartIdle(useCartStore.getState().pendingCartOps)) {\n setCartLines(cartLinesData);\n }\n }, [cartLinesData, setCartLines]);\n\n return {\n cartHdrUid,\n isInitializing: isInitializingRef.current,\n retryCount: retryCountRef.current,\n };\n}\n","import { useMemo } from \"react\";\nimport { useQueries } from \"@tanstack/react-query\";\nimport type { DerivedPrice, TPriceData } from \"@simpleapps-com/augur-utils\";\nimport {\n cleanMoney,\n derivePrice,\n linePriceAt,\n priceQueryRuns,\n priceQueryUnit,\n pricingLoadingFrom,\n pricingSettledFrom,\n} from \"@simpleapps-com/augur-utils\";\nimport { lineUnitPrice } from \"../rules\";\nimport { useCartLines } from \"../stores/cart-store\";\nimport { useAugurOptions, useAugurAuth, useAugurSite } from \"../provider\";\n\nexport interface CartPriceData {\n unitPrice: number;\n priceData: Record<string, unknown> | null;\n}\n\nexport interface CartPricingResult {\n /**\n * Map of itemId -> price data. An item on more than one line (two units of measure) holds its\n * last line's price: read a line's own price with `getLineUnitPrice` / `linePrices`.\n */\n prices: Record<string, CartPriceData>;\n /** Each cart line's own price data, in cart order (null until it loads). */\n linePrices: (CartPriceData | null)[];\n /**\n * Unit price for an item (0 if not found). Per item: for an item on more than one line, use\n * `getLineUnitPrice`.\n */\n getUnitPrice: (itemId: string) => number;\n /** `getUnitPrice(itemId)` × quantity. Per item, as `getUnitPrice`. */\n getItemTotal: (itemId: string, quantity: number) => number;\n /**\n * Unit price of the cart line at `index`, fetched at that line's quantity (0 past the cart or not\n * priced). Each line keeps its own price, so one item on two lines can show two.\n */\n getLineUnitPrice: (index: number) => number;\n /** The line's total: `getLineUnitPrice(index)` × its quantity (0 without a quantity). */\n getLineTotal: (index: number) => number;\n /** Cart subtotal: the sum of every line's own total. */\n subtotal: number;\n /** True if any price that is fetched is still loading */\n isLoading: boolean;\n /**\n * True once every price that is fetched has loaded. A line whose price is never fetched (no\n * quantity, no itemId, no customer) doesn't hold it back.\n */\n isSuccess: boolean;\n /** True if any price failed to load */\n isError: boolean;\n}\n\ninterface UseCartPricingOptions {\n customerId?: string | number;\n /**\n * Override per-line price fetching (e.g. with a custom server action, such as augur-server's\n * `getItemPrice`). `unitOfMeasure` is the line's unit (undefined when it has none): pass it to the\n * price engine, which otherwise prices the item's default selling unit (a CASE/6 line as one EACH).\n */\n queryFn?: (\n itemId: string,\n customerId: string | number,\n quantity: number,\n unitOfMeasure?: string,\n ) => Promise<TPriceData>;\n}\n\n/**\n * derivePrice for a known quantity, or null when it refuses the input (negative or non-finite\n * quantity or unitPrice: its RangeError), so one bad line degrades instead of throwing during render\n * and crashing the cart (GH #496). Any other error is a bug and is rethrown.\n */\nfunction derivedOrRefused(priceData: TPriceData, quantity: number): DerivedPrice | null {\n try {\n return derivePrice({ priceData, quantity });\n } catch (error) {\n if (error instanceof RangeError) return null;\n throw error;\n }\n}\n\n/**\n * Unit price for one cart line (the proved `lineUnitPrice`): only a line with a quantity that\n * derivePrice prices has one; no quantity (null, or non-finite at runtime), loading,\n * callForPrice and a refused input all give 0.\n */\nfunction deriveLineUnitPrice(priceData: TPriceData, quantity: number | null): number {\n const hasQuantity = typeof quantity === \"number\" && Number.isFinite(quantity);\n const derived = hasQuantity ? derivedOrRefused(priceData, quantity as number) : null;\n const priced = derived?.state === \"priced\";\n return lineUnitPrice(hasQuantity, priced, priced ? derived.unitPrice : 0);\n}\n\n/**\n * Extended price for one line. A non-finite quantity (NaN, ±Infinity, or null\n * at runtime) contributes 0, so one bad line cannot turn the whole subtotal\n * into NaN (GH #496). The product is passed through cleanMoney to drop float noise.\n */\nfunction lineTotal(unitPrice: number, quantity: number | null): number {\n return Number.isFinite(quantity) ? cleanMoney(unitPrice * (quantity as number)) : 0;\n}\n\n/**\n * Centralized hook for cart/checkout pricing.\n *\n * Fetches prices for ALL cart items with their actual quantities\n * to support quantity-based price breaks. React Query dedupes\n * identical calls across components.\n *\n * Uses the proxy from AugurHooksProvider context. Works with:\n * - Direct SDK (api prop on provider)\n * - Server actions (auto-detected via queryAction registration)\n * - Custom queryFn override\n */\nexport function useCartPricing(options: UseCartPricingOptions = {}): CartPricingResult {\n const proxy = useAugurOptions();\n const auth = useAugurAuth();\n const site = useAugurSite();\n const cartLines = useCartLines();\n const customerId = options.customerId ?? auth?.customerId ?? site?.defaults?.customerId;\n\n const priceFn = options.queryFn;\n\n // Whether each line's price is fetched: a customer, an itemId and a quantity (proved rule). augur\n // never stores a null quantity (models/AugurCommerceCartLine.dfy RoutesWriteQuantity); the type\n // allows one, and such a line is simply not priced.\n const runs = cartLines.map((line) => priceQueryRuns(!!customerId, !!line.itemId, line.quantity));\n\n const priceQueries = useQueries({\n queries: cartLines.map((line, index) => {\n // Only the query key reads this for a line without a quantity: its query never runs.\n const quantity = line.quantity ?? 0;\n const enabled = runs[index] === true;\n // Priced in the line's own unit (proved rule): the engine prices no unit as the default one.\n const unitOfMeasure = priceQueryUnit(line.unitOfMeasure) ?? undefined;\n if (priceFn) {\n return {\n queryKey: [\n \"price\",\n line.itemId?.toUpperCase() || \"\",\n customerId,\n quantity,\n unitOfMeasure ?? \"\",\n ],\n queryFn: () => priceFn(line.itemId, customerId!, quantity, unitOfMeasure),\n refetchOnReconnect: true,\n refetchOnWindowFocus: false,\n meta: { persist: true },\n enabled,\n };\n }\n\n // Use the proxy — works with SDK, server actions, or keys-only\n const proxyOpts = proxy.pricing.priceEngine.list({\n itemId: line.itemId?.toUpperCase() || \"\",\n customerId: Number(customerId),\n quantity,\n unitOfMeasure,\n });\n\n return {\n ...proxyOpts,\n enabled,\n refetchOnReconnect: true,\n refetchOnWindowFocus: false,\n meta: { persist: true },\n };\n }),\n });\n\n // Each line's own price (atlas#93), in cart order: fetched at its own quantity, so one item on two\n // lines (two units of measure) keeps two prices. null until its data loads.\n const linePrices = useMemo(\n () =>\n cartLines.map((line, index): CartPriceData | null => {\n // Every proxy resolves to the unwrapped SDK data (augur-core unwrapBaseResponse).\n const priceData = priceQueries[index]?.data as TPriceData | undefined;\n if (!priceData) return null;\n return {\n unitPrice: deriveLineUnitPrice(priceData, line.quantity),\n priceData: priceData as Record<string, unknown>,\n };\n }),\n [cartLines, priceQueries],\n );\n\n const lineUnitPrices = useMemo(() => linePrices.map((p) => p?.unitPrice ?? 0), [linePrices]);\n\n // By itemId, kept for compatibility: an item on more than one line holds its last line's price.\n const prices = useMemo(() => {\n const map: Record<string, CartPriceData> = {};\n cartLines.forEach((line, index) => {\n const linePrice = linePrices[index];\n if (linePrice) map[line.itemId.toUpperCase()] = linePrice;\n });\n return map;\n }, [cartLines, linePrices]);\n\n const getUnitPrice = useMemo(() => {\n return (itemId: string): number => {\n return prices[itemId?.toUpperCase()]?.unitPrice ?? 0;\n };\n }, [prices]);\n\n const getItemTotal = useMemo(() => {\n return (itemId: string, quantity: number): number => {\n return lineTotal(getUnitPrice(itemId), quantity);\n };\n }, [getUnitPrice]);\n\n // The proved linePriceAt: line `index`'s own price, 0 past the cart.\n const getLineUnitPrice = useMemo(() => {\n return (index: number): number => linePriceAt(lineUnitPrices, index);\n }, [lineUnitPrices]);\n\n const getLineTotal = useMemo(() => {\n return (index: number): number =>\n lineTotal(linePriceAt(lineUnitPrices, index), cartLines[index]?.quantity ?? null);\n }, [cartLines, lineUnitPrices]);\n\n const subtotal = useMemo(() => {\n return cartLines.reduce(\n (sum, line, index) =>\n cleanMoney(sum + lineTotal(linePriceAt(lineUnitPrices, index), line.quantity)),\n 0,\n );\n }, [cartLines, lineUnitPrices]);\n\n // Over the queries that run only (proved rules): a query that never runs stays pending and idle,\n // so counting it left isSuccess false for good with no spinner.\n const isLoading = pricingLoadingFrom(\n priceQueries.map((q) => q.isLoading),\n runs,\n 0,\n );\n const isSuccess = pricingSettledFrom(\n priceQueries.map((q) => q.isSuccess),\n runs,\n 0,\n );\n const isError = priceQueries.some((q) => q.isError);\n\n return {\n prices,\n linePrices,\n getUnitPrice,\n getItemTotal,\n getLineUnitPrice,\n getLineTotal,\n subtotal,\n isLoading,\n isSuccess,\n isError,\n };\n}\n","import { minutes, toMillis } from \"@simpleapps-com/augur-utils\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { useCallback } from \"react\";\nimport type { QueryKey } from \"@tanstack/react-query\";\nimport type { Millis } from \"../duration\";\n\ninterface UsePaginationPrefetchOptions {\n /** Query key for the paginated data */\n queryKey: QueryKey;\n /** Function to fetch a page of data */\n queryFn: (offset: number) => Promise<unknown>;\n /** Number of items per page */\n pageSize: number;\n /** Custom query key builder. Receives the base key and offset, returns the full key. Default: [...queryKey, offset]. */\n queryKeyFn?: (baseKey: QueryKey, offset: number) => QueryKey;\n /** Stale time (defaults to 10 minutes) */\n staleTime?: Millis;\n /** GC time (defaults to 30 minutes) */\n gcTime?: Millis;\n enabled?: boolean;\n}\n\n/**\n * Prefetch adjacent pages on hover for instant pagination.\n * Accepts a generic queryFn so it works with any paginated resource.\n */\nexport const usePaginationPrefetch = ({\n queryKey,\n queryFn,\n pageSize,\n queryKeyFn,\n staleTime = toMillis(minutes(10)),\n gcTime = toMillis(minutes(30)),\n enabled = true,\n}: UsePaginationPrefetchOptions) => {\n const queryClient = useQueryClient();\n\n const prefetchPage = useCallback(\n async (page: number) => {\n if (!enabled) return;\n\n const offset = (page - 1) * pageSize;\n\n // prefetchQuery never rejects: query-core swallows fetch errors, and the\n // real query surfaces them when the page is actually opened.\n await queryClient.prefetchQuery({\n queryKey: queryKeyFn ? queryKeyFn(queryKey, offset) : [...queryKey, offset],\n queryFn: () => queryFn(offset),\n staleTime,\n gcTime,\n });\n },\n [queryKey, queryFn, pageSize, queryKeyFn, staleTime, gcTime, queryClient, enabled],\n );\n\n const handlePaginationHover = useCallback(\n (page: number) => {\n const timeoutId = setTimeout(() => prefetchPage(page), 150);\n return () => clearTimeout(timeoutId);\n },\n [prefetchPage],\n );\n\n return {\n prefetchPage,\n handlePaginationHover,\n };\n};\n","import { hours, toMillis } from \"@simpleapps-com/augur-utils\";\nimport { useState, useEffect, useMemo } from \"react\";\nimport { shouldPersistOf } from \"../rules\";\nimport type { PersistenceConfig } from \"../types\";\nimport { createPersister } from \"./create-persister\";\nimport { useStorageMonitor } from \"./use-storage-monitor\";\n\n/**\n * Version of the persisted query-data format, prefixed to every buster.\n * Bump it when the shape the proxies resolve to changes, so caches written by\n * older package versions are discarded without each site bumping its own buster.\n * \"augur-2\": the direct-SDK options proxy unwraps BaseResponse (2.5.0).\n */\nexport const PERSISTED_DATA_FORMAT = \"augur-2\";\n\n/**\n * Returns a fully configured `persistOptions` object for use with\n * `PersistQueryClientProvider` from `@tanstack/react-query-persist-client`.\n *\n * Handles:\n * - SSR-safe persister creation (no-op on server)\n * - Map → Record serialization for localStorage compatibility\n * - Selective persistence (only successful queries matching persistableKeys)\n * - Per-key-prefix LRU eviction (via `limits`)\n * - Throttled writes to localStorage\n * - Hydration safety (maxAge: 0 until client mount)\n * - Storage monitoring with automatic eviction when over threshold\n * - Dev mode auto-buster (invalidates cache on each restart)\n *\n * @example\n * ```tsx\n * import { useAugurPersistence } from \"@simpleapps-com/augur-hooks\";\n *\n * function Providers({ children }) {\n * const [queryClient] = useState(() => new QueryClient({ ... }));\n * const persistOptions = useAugurPersistence({\n * key: \"my-site-cache\",\n * buster: \"1.0.0\",\n * persistableKeys: [\"price\", \"categories\", \"invMast\"],\n * limits: { invMast: 100 },\n * });\n *\n * return (\n * <PersistQueryClientProvider client={queryClient} persistOptions={persistOptions}>\n * <augur.Provider api={api} auth={auth}>\n * {children}\n * </augur.Provider>\n * </PersistQueryClientProvider>\n * );\n * }\n * ```\n */\nexport function useAugurPersistence(config: PersistenceConfig) {\n const [persister] = useState(() => createPersister(config));\n const [isMounted, setIsMounted] = useState(false);\n\n useEffect(() => {\n setIsMounted(true);\n }, []);\n\n useStorageMonitor(config);\n\n const isDev = typeof process !== \"undefined\" && process.env?.[\"NODE_ENV\"] === \"development\";\n\n const { persistableKeys } = config;\n\n const dehydrateOptions = useMemo(\n () => ({\n shouldDehydrateQuery: (query: {\n queryKey: readonly unknown[];\n state: { status: string };\n }) => {\n const key = query.queryKey;\n const hasHead = Array.isArray(key) && key.length > 0;\n return shouldPersistOf(\n hasHead,\n query.state.status === \"success\",\n hasHead && persistableKeys.includes(key[0] as string),\n );\n },\n }),\n [persistableKeys],\n );\n\n return {\n persister,\n maxAge: isMounted ? (config.maxAge ?? toMillis(hours(24))) : 0,\n buster: isDev ? String(Date.now()) : `${PERSISTED_DATA_FORMAT}:${config.buster ?? \"\"}`,\n dehydrateOptions,\n };\n}\n","import { seconds, toMillis } from \"@simpleapps-com/augur-utils\";\nimport type { Persister, PersistedClient } from \"@tanstack/react-query-persist-client\";\nimport type { PersistenceConfig } from \"../types\";\nimport { serialize, deserialize } from \"./serializer\";\nimport { applyLimits } from \"./apply-limits\";\n\n/** No-op persister for SSR environments where localStorage is unavailable. */\nconst noopPersister: Persister = {\n persistClient: async () => {},\n restoreClient: async () => undefined,\n removeClient: async () => {},\n};\n\n/**\n * Creates an SSR-safe localStorage persister with throttled writes and LRU limiting.\n *\n * On the server (typeof window === \"undefined\"), returns a no-op persister.\n * On the client, writes are throttled to avoid performance degradation.\n */\nexport function createPersister(config: PersistenceConfig): Persister {\n if (typeof window === \"undefined\") return noopPersister;\n\n const throttleMs = config.throttleMs ?? toMillis(seconds(1));\n const limits = config.limits ?? {};\n let timer: ReturnType<typeof setTimeout> | undefined;\n // The latest client handed to persistClient. Only the timer reads it, and persistClient\n // sets it before it starts the timer, so it is always assigned when read.\n let pending!: PersistedClient;\n\n function write(client: PersistedClient) {\n try {\n const limited = applyLimits(client, limits);\n window.localStorage.setItem(config.key, serialize(limited));\n } catch {\n /* quota exceeded — silently skip */\n }\n }\n\n return {\n persistClient(client: PersistedClient) {\n pending = client;\n if (!timer) {\n timer = setTimeout(() => {\n timer = undefined;\n write(pending);\n }, throttleMs);\n }\n },\n\n restoreClient() {\n try {\n const raw = window.localStorage.getItem(config.key);\n if (!raw) return undefined;\n return deserialize(raw);\n } catch {\n return undefined;\n }\n },\n\n removeClient() {\n window.localStorage.removeItem(config.key);\n },\n };\n}\n","import type { PersistedClient } from \"@tanstack/react-query-persist-client\";\n\n/**\n * Serializes a PersistedClient to a JSON string.\n * Converts Map instances to plain objects for localStorage compatibility.\n */\nexport function serialize(data: PersistedClient): string {\n return JSON.stringify(data, (_key, value) => {\n if (value instanceof Map) return Object.fromEntries(value);\n return value;\n });\n}\n\n/**\n * Deserializes a JSON string back to a PersistedClient.\n */\nexport function deserialize(data: string): PersistedClient {\n return JSON.parse(data) as PersistedClient;\n}\n","import type { PersistedClient } from \"@tanstack/react-query-persist-client\";\n\ninterface QueryEntry {\n queryKey: readonly unknown[];\n queryHash: string;\n state: { dataUpdatedAt?: number };\n}\n\n/**\n * Applies per-key-prefix LRU limits to the queries in a PersistedClient.\n * For each prefix in `limits`, keeps only the N most-recently-updated queries.\n * Returns a shallow copy with trimmed queries; does not mutate the input.\n */\nexport function applyLimits(\n data: PersistedClient,\n limits: Record<string, number>,\n): PersistedClient {\n const queries = data.clientState?.queries;\n if (!queries || Object.keys(limits).length === 0) return data;\n\n const entries = queries as unknown as QueryEntry[];\n const unlimited: QueryEntry[] = [];\n const groups = new Map<string, QueryEntry[]>();\n\n for (const q of entries) {\n const prefix = Array.isArray(q.queryKey) ? q.queryKey[0] : undefined;\n if (typeof prefix === \"string\" && prefix in limits) {\n const group = groups.get(prefix) ?? [];\n group.push(q);\n groups.set(prefix, group);\n } else {\n unlimited.push(q);\n }\n }\n\n const kept: QueryEntry[] = [];\n for (const [prefix, group] of groups) {\n const limit = limits[prefix]!;\n const sorted = [...group].sort(\n (a, b) => (b.state.dataUpdatedAt ?? 0) - (a.state.dataUpdatedAt ?? 0),\n );\n kept.push(...sorted.slice(0, limit));\n }\n\n return {\n ...data,\n clientState: {\n ...data.clientState,\n queries: [...unlimited, ...kept] as unknown as typeof queries,\n },\n };\n}\n","import { minutes, toMillis } from \"@simpleapps-com/augur-utils\";\nimport { useEffect } from \"react\";\nimport { useLatest } from \"../hooks/use-latest\";\nimport type { PersistenceConfig } from \"../types\";\n\nconst CHECK_INTERVAL = toMillis(minutes(5));\n\n/**\n * Monitors total localStorage size and evicts limited query families\n * when the threshold is exceeded.\n *\n * Eviction strategy: remove queries whose key prefix appears in `limits`,\n * starting with the largest family. If parsing fails, clears the entire\n * persistence key as a fallback.\n */\nexport function useStorageMonitor(config: PersistenceConfig): void {\n const { key, limits = {}, maxStorageMB = 3 } = config;\n // A new array each render: the effect restarts when the number of limited families\n // changes, and takes the keys as of that render.\n const limitKeysRef = useLatest(Object.keys(limits));\n const limitCount = limitKeysRef.current.length;\n\n useEffect(() => {\n const limitKeys = limitKeysRef.current;\n if (typeof window === \"undefined\" || limitKeys.length === 0) return;\n\n function evict() {\n const storage = window.localStorage;\n let totalSize = 0;\n\n for (const k of Object.keys(storage)) {\n const v = storage.getItem(k);\n if (v) totalSize += k.length + v.length;\n }\n\n // UTF-16: each char = 2 bytes\n const usedMB = (totalSize * 2) / 1024 / 1024;\n if (usedMB <= maxStorageMB) return;\n\n try {\n const raw = storage.getItem(key);\n if (!raw) return;\n const parsed = JSON.parse(raw);\n if (!parsed.clientState?.queries) return;\n\n // Remove all queries whose prefix is in limits\n parsed.clientState.queries = parsed.clientState.queries.filter(\n (q: { queryKey?: unknown[] }) => {\n if (!Array.isArray(q.queryKey)) return true;\n const prefix = q.queryKey[0];\n return typeof prefix !== \"string\" || !limitKeys.includes(prefix);\n },\n );\n\n storage.setItem(key, JSON.stringify(parsed));\n } catch {\n // Corrupted data — clear entirely\n storage.removeItem(key);\n }\n }\n\n evict();\n const id = setInterval(evict, CHECK_INTERVAL);\n return () => clearInterval(id);\n }, [key, maxStorageMB, limitCount, limitKeysRef]);\n}\n","import { clearedBy } from \"@simpleapps-com/augur-core\";\nimport type { Mutation, MutationCacheConfig, QueryClient } from \"@tanstack/react-query\";\nimport { keyPathFrom, leadingTextsFrom } from \"./rules\";\n\n/**\n * A React Query key's method path: its leading text segments, joined by \".\" (augur-core keys a\n * query `[...path, ...args]` and a mutation `path`). How many lead is the proved leadingTextsFrom;\n * the join is the proved keyPathFrom (model KeyPathFrom), which reads only those first `n`, all text.\n */\nexport function keyPathOf(key: readonly unknown[] | undefined): string {\n const segments = key ?? [];\n const n = leadingTextsFrom(\n segments.map((s) => typeof s === \"string\"),\n 0,\n );\n return keyPathFrom(segments as string[], n);\n}\n\n/**\n * After the user's own write succeeds, clears the browser's cached reads that share a user\n * namespace with it (augur-core `clearedBy`, atlas#102): a wishlist write refetches the\n * wishlists and their lines; a favorites write leaves the wishlists alone; a catalogue write\n * clears nothing. User data is never cached on the server, so this is the only copy to clear.\n */\nexport function clearUserReadsOnWrite(\n queryClient: QueryClient,\n mutationKey: readonly unknown[] | undefined,\n): Promise<void> {\n const writePath = keyPathOf(mutationKey);\n return queryClient.invalidateQueries({\n predicate: (query) => clearedBy(writePath, keyPathOf(query.queryKey)),\n });\n}\n\n/**\n * The `MutationCache` config a site gives its browser QueryClient so the user's own writes clear\n * their cached reads. Works for mutations keyed by their SDK method path (augur-core's options\n * proxy keys them so) and reads keyed by it.\n *\n * @example\n * ```ts\n * const queryClient: QueryClient = new QueryClient({\n * mutationCache: new MutationCache(userWriteClearing(() => queryClient)),\n * });\n * ```\n */\nexport function userWriteClearing(getQueryClient: () => QueryClient): MutationCacheConfig {\n return {\n onSuccess: (_data, _variables, _context, mutation: Mutation<unknown, unknown, unknown>) =>\n clearUserReadsOnWrite(getQueryClient(), mutation.options.mutationKey),\n };\n}\n"]}
1
+ {"version":3,"sources":["/Users/stuartjackson/Projects/simpleapps/atlas/repo/packages/augur-hooks/dist/index.cjs","../src/provider.tsx","../src/stores/items-filters-store.ts","../src/hooks/use-debounce.ts","../src/hooks/use-format-price.ts","../src/hooks/use-stock.ts","../src/hooks/use-cart-actions.ts","../src/hooks/use-modal-lifecycle.ts","../src/hooks/use-cart-initialization.ts","../src/hooks/use-cart-pricing.ts","../src/hooks/use-pagination-prefetch.ts","../src/persistence/use-persistence.ts","../src/persistence/create-persister.ts","../src/persistence/serializer.ts","../src/persistence/apply-limits.ts","../src/persistence/use-storage-monitor.ts","../src/user-write-clearing.ts"],"names":["useMemo","useEffect","useQuery","useQueryClient","cleanMoney","useCallback","useState","minutes","toMillis"],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;AC/CA,8BAAmE;AAOnE;AACE;AACA;AACA;AAAA,uDACK;AAiEK,+CAAA;AA1CZ,IAAM,gBAAA,EAAkB,kCAAA,IAAiC,CAAA;AACzD,IAAM,sBAAA,EAAwB,kCAAA,KAA4C,CAAS,CAAA;AACnF,IAAM,kBAAA,EAAoB,kCAAA,KAAuC,CAAS,CAAA;AAC1E,IAAM,oBAAA,EAAsB,kCAAA,IAA2B,CAAA;AACvD,IAAM,iBAAA,EAAmB,kCAAA,KAA2C,CAAS,CAAA;AAiBtE,SAAS,kBAAA,CAAmB,EAAE,GAAA,EAAK,IAAA,EAAM,KAAA,EAAO,IAAA,EAAM,SAAS,CAAA,EAA4B;AAChG,EAAA,MAAM,YAAA,EAA8C,MAAA,EAChD,EAAE,KAAA,EAAO,EAAE,MAAA,EAAQ,KAAA,CAAM,MAAA,EAAQ,UAAA,EAAY,KAAA,CAAM,WAAW,EAAE,EAAA,EAChE,KAAA,CAAA;AAIJ,EAAA,MAAM,eAAA,EAAiB,yCAAA,WAAqB,CAAA;AAC5C,EAAA,MAAM,QAAA,EAAU,4BAAA,CAAQ,EAAA,GAAM;AAC5B,IAAA,MAAM,OAAA,EAAS,cAAA,CAAe,OAAA;AAC9B,IAAA,GAAA,CAAI,GAAA,EAAK,OAAO,2CAAA,GAAmB,EAAK,MAAM,CAAA;AAC9C,IAAA,MAAM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EAAA;AAEH,EAAA;AACI,IAAA;AACP,IAAA;AAEM,IAAA;AACC,MAAA;AACA,MAAA;AAEA,MAAA;AACJ,QAAA;AACH,QAAA;AACT,MAAA;AAGgB,MAAA;AACF,MAAA;AAEV,MAAA;AACU,QAAA;AACF,QAAA;AACK,QAAA;AACH,QAAA;AAGL,QAAA;AAC4B,UAAA;AACpB,YAAA;AACL,YAAA;AACC,YAAA;AACT,UAAA;AACF,QAAA;AAEgB,QAAA;AACV,MAAA;AAEE,QAAA;AACV,MAAA;AACF,IAAA;AAEM,IAAA;AACK,IAAA;AACE,IAAA;AACN,EAAA;AACX;Afs5BwB;AACA;AW38BX;AAuCG;AACMF,EAAAA;AACF,EAAA;AAEF,EAAA;AACG,IAAA;AACd,EAAA;AAEa,EAAA;AAEG,EAAA;AAEb,EAAA;AAEF,EAAA;AACG,IAAA;AACL,MAAA;AAIc,QAAA;AACI,QAAA;AACT,QAAA;AACL,UAAA;AACY,UAAA;AACD,UAAA;AACb,QAAA;AACF,MAAA;AACF,IAAA;AACgB,IAAA;AAClB,EAAA;AAEO,EAAA;AACL,IAAA;AACqB,IAAA;AACL,IAAA;AAChB,IAAA;AACF,EAAA;AACF;AX85BwB;AACA;AgBz/Bf;AAS8D;AACpD,EAAA;AACP,EAAA;AACY,IAAA;AACpB,IAAA;AACF,EAAA;AACmB,EAAA;AACrB;AAQgB;AAII,EAAA;AACC,EAAA;AACL,IAAA;AACb,EAAA;AACH;AAcgB;AACP,EAAA;AACc,IAAA;AAErB,EAAA;AACF;AhB29BwB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/stuartjackson/Projects/simpleapps/atlas/repo/packages/augur-hooks/dist/index.cjs","sourcesContent":[null,"import { createContext, useContext, useMemo, type ReactNode } from \"react\";\nimport type {\n AugurAuthContext,\n AugurSiteConfig,\n CacheConfig,\n DeepQueryOptions,\n} from \"@simpleapps-com/augur-core\";\nimport {\n createOptionsProxy,\n createQueryActionProxy,\n createKeysOnlyProxy,\n} from \"@simpleapps-com/augur-core\";\nimport type { OptionsProxyConfig } from \"@simpleapps-com/augur-core\";\nimport type { AugurAPI } from \"@simpleapps-com/augur-api\";\nimport { useLatest } from \"./hooks/use-latest\";\nimport { getRegisteredQueryAction } from \"./query-action-registry\";\n\n/** The augur-api SDK instance, as `useAugurApi()` returns it (the SDK is a peer dependency). */\nexport type AugurApiClient = AugurAPI;\n\ninterface AugurHooksProviderProps {\n /** SDK client instance. When omitted, `useAugurOptions()` returns a keys-only\n * proxy — consumers MUST override queryFn with a server action at each call site.\n * Any object is accepted (a site's test double included); hooks read it as the SDK. */\n api?: object;\n /** Optional auth context — hooks fall back to these values when not passed directly. */\n auth?: AugurAuthContext;\n /** Optional cache configuration — controls edge and Redis caching per tier. */\n cache?: CacheConfig;\n /** Optional site configuration — hooks read defaults and formatting from this. */\n site?: AugurSiteConfig;\n children: ReactNode;\n}\n\nconst AugurApiContext = createContext<object | null>(null);\nconst AugurAuthReactContext = createContext<AugurAuthContext | undefined>(undefined);\nconst AugurCacheContext = createContext<CacheConfig | undefined>(undefined);\nconst AugurOptionsContext = createContext<unknown>(null);\nconst AugurSiteContext = createContext<AugurSiteConfig | undefined>(undefined);\n\n/**\n * Provides the augur-api SDK instance, proxy options, and auth to all hooks.\n *\n * ```tsx\n * <AugurHooksProvider api={api} auth={authContext} cache={cacheConfig}>\n * <App />\n * </AugurHooksProvider>\n * ```\n *\n * Components use `useAugurOptions()` to get the proxy:\n * ```tsx\n * const q = useAugurOptions();\n * const { data } = useQuery(q.items.invMast.get(42));\n * ```\n */\nexport function AugurHooksProvider({ api, auth, cache, site, children }: AugurHooksProviderProps) {\n const proxyConfig: OptionsProxyConfig | undefined = cache\n ? { cache: { static: cache.static, semiStatic: cache.semiStatic } }\n : undefined;\n\n // The proxy is rebuilt when the api changes; the cache config is read at that point, not\n // watched (it is a new object on every render).\n const proxyConfigRef = useLatest(proxyConfig);\n const options = useMemo(() => {\n const config = proxyConfigRef.current;\n if (api) return createOptionsProxy(api, config);\n const registeredAction = getRegisteredQueryAction();\n if (registeredAction) return createQueryActionProxy(registeredAction, config);\n return createKeysOnlyProxy(config);\n }, [api, proxyConfigRef]);\n\n return (\n <AugurApiContext.Provider value={api ?? null}>\n <AugurAuthReactContext.Provider value={auth}>\n <AugurCacheContext.Provider value={cache}>\n <AugurSiteContext.Provider value={site}>\n <AugurOptionsContext.Provider value={options}>{children}</AugurOptionsContext.Provider>\n </AugurSiteContext.Provider>\n </AugurCacheContext.Provider>\n </AugurAuthReactContext.Provider>\n </AugurApiContext.Provider>\n );\n}\n\n/**\n * Returns the deep proxy for creating TanStack Query options.\n *\n * When an `api` prop is provided to the provider, every path returns\n * full query options (queryKey, queryFn, staleTime, gcTime).\n *\n * When no `api` is provided (server-only JWT sites), returns a keys-only\n * proxy — queryKey, staleTime, and gcTime are generated normally, but\n * queryFn throws unless overridden. This lets B2B sites use the proxy\n * for deterministic keys and cache tiers while routing data through\n * server actions.\n *\n * @example\n * ```tsx\n * // With api (direct SDK access):\n * const q = useAugurOptions();\n * const { data } = useQuery(q.items.invMast.get(42));\n *\n * // Without api (server-only JWT):\n * const q = useAugurOptions();\n * const { data } = useQuery({\n * ...q.items.invMast.doc.get(42),\n * queryFn: () => getItemAction(42), // server action\n * });\n * ```\n */\nexport function useAugurOptions<T = DeepQueryOptions<AugurAPI>>(): T {\n const options = useContext(AugurOptionsContext);\n if (!options) {\n throw new Error(\n \"useAugurOptions must be used within an <AugurHooksProvider>. \" +\n \"Wrap your app with <AugurHooksProvider>.\",\n );\n }\n return options as T;\n}\n\n/**\n * Returns the augur-api SDK instance from context, or null if not provided.\n * Used internally by hooks that need the SDK for fallback queries.\n */\nexport function useAugurApiOptional(): AugurApiClient | null {\n return useContext(AugurApiContext) as AugurApiClient | null;\n}\n\n/**\n * Returns the augur-api SDK instance from context.\n * Throws if called outside of `<AugurHooksProvider>` or when no api is provided.\n */\nexport function useAugurApi(): AugurApiClient {\n const api = useContext(AugurApiContext) as AugurApiClient | null;\n if (!api) {\n throw new Error(\n \"useAugurApi must be used within an <AugurHooksProvider>. \" +\n \"Wrap your app with <AugurHooksProvider api={apiInstance}>.\",\n );\n }\n return api;\n}\n\n/**\n * Returns the provider-level auth context, if any.\n * Used internally by hooks to fall back to provider auth when\n * auth fields are not passed directly as hook parameters.\n */\nexport function useAugurAuth(): AugurAuthContext | undefined {\n return useContext(AugurAuthReactContext);\n}\n\n/**\n * Returns the provider-level cache configuration, if any.\n * Used internally by hooks to enable edge/Redis caching.\n */\nexport function useAugurCache(): CacheConfig | undefined {\n return useContext(AugurCacheContext);\n}\n\n/**\n * Returns the site configuration from the nearest `AugurHooksProvider`.\n * Returns `undefined` when no `site` prop is provided.\n */\nexport function useAugurSite(): AugurSiteConfig | undefined {\n return useContext(AugurSiteContext);\n}\n","import { create } from \"zustand\";\nimport { devtools } from \"zustand/middleware\";\nimport type { TItemsFilters } from \"@simpleapps-com/augur-utils\";\n\n/** Default filter values used when the store is first created or reset. */\nconst DEFAULT_FILTER_STATE: TItemsFilters = {\n filters: [],\n limit: 12,\n offset: 0,\n sortBy: \"asc\",\n q: \"\",\n page: 1,\n};\n\n/** Zustand state shape for item list filtering, sorting, and pagination. */\ninterface ItemsFiltersState {\n /** Snapshot of the initial defaults; useful for \"reset filters\" UIs. */\n initialFiltersState: TItemsFilters;\n /** Current active filter/sort/pagination state. */\n itemsFilters: TItemsFilters;\n /** Replace the entire filter state. */\n setItemsFilters: (itemFilters: TItemsFilters) => void;\n}\n\n/** Zustand store for item list filters, sorting, and pagination state. */\nexport const useItemFiltersStore = create<ItemsFiltersState>()(\n devtools(\n (set) => ({\n initialFiltersState: DEFAULT_FILTER_STATE,\n itemsFilters: DEFAULT_FILTER_STATE,\n setItemsFilters: (state) => set({ itemsFilters: state }, false, \"setItemsFilters\"),\n }),\n {\n name: \"ItemsFiltersStore\",\n enabled: process.env[\"NODE_ENV\"] === \"development\",\n },\n ),\n);\n","import { useEffect, useState } from \"react\";\n\n/**\n * Debounces a rapidly-changing value.\n * Returns the latest value only after `delay` ms of inactivity.\n */\nexport function useDebounce<T>(value: T, delay: number = 500): T {\n const [debouncedValue, setDebouncedValue] = useState<T>(value);\n\n useEffect(() => {\n const handler = setTimeout(() => {\n setDebouncedValue(value);\n }, delay);\n\n return () => {\n clearTimeout(handler);\n };\n }, [value, delay]);\n\n return debouncedValue;\n}\n","import type { AugurSiteFormatting } from \"@simpleapps-com/augur-core\";\nimport { cleanMoney } from \"@simpleapps-com/augur-utils\";\nimport { useAugurSite } from \"../provider\";\nimport { zeroLabelShown } from \"../rules\";\n\n/** Options for configuring the useFormatPrice hook. */\nexport interface UseFormatPriceOptions {\n /** BCP 47 locale tag. Overrides site.formatting.locale. */\n locale?: string;\n /** ISO 4217 currency code. Overrides site.formatting.currency. */\n currency?: string;\n /** Decimal digits. Overrides site.formatting.precision. */\n precision?: number;\n /** Label returned when the effective value is 0 (e.g. \"Call for Price\"). */\n zeroLabel?: string;\n}\n\n/** Per-call options passed to the returned formatPrice function. */\nexport interface FormatPriceCallOptions {\n /** Override decimal digits for this call only. */\n precision?: number;\n /** Multiply the value by this quantity before formatting. */\n quantity?: number;\n}\n\nfunction normaliseOptions(\n optionsOrLocale: UseFormatPriceOptions | string | undefined,\n legacyCurrency: string | undefined,\n): UseFormatPriceOptions {\n if (typeof optionsOrLocale === \"string\") {\n return { locale: optionsOrLocale, currency: legacyCurrency };\n }\n return optionsOrLocale ?? {};\n}\n\nfunction resolveFormatting(\n opts: UseFormatPriceOptions,\n siteFormatting: AugurSiteFormatting | undefined,\n) {\n const site: Partial<AugurSiteFormatting> = siteFormatting ?? {};\n return {\n locale: opts.locale ?? site.locale ?? \"en-US\",\n currency: opts.currency ?? site.currency ?? \"USD\",\n precision: opts.precision ?? site.precision ?? 2,\n zeroLabel: opts.zeroLabel ?? site.zeroLabel,\n };\n}\n\n/**\n * Hook that returns a price formatter.\n * Reads defaults from site config when params are omitted.\n *\n * Supports both the new options-object signature and the legacy positional\n * `(locale?, currency?)` signature for backwards compatibility.\n */\nexport function useFormatPrice(\n optionsOrLocale?: UseFormatPriceOptions | string,\n legacyCurrency?: string,\n) {\n const site = useAugurSite();\n const opts = normaliseOptions(optionsOrLocale, legacyCurrency);\n const {\n locale,\n currency,\n precision: basePrecision,\n zeroLabel,\n } = resolveFormatting(opts, site?.formatting);\n\n const formatPrice = (price: number, callOptions?: FormatPriceCallOptions): string => {\n // cleanMoney drops float noise so a line formats to the same cent as the cart total (GH #496).\n const effectiveValue = cleanMoney(price * (callOptions?.quantity ?? 1));\n\n if (zeroLabelShown(effectiveValue === 0, zeroLabel !== undefined)) {\n return zeroLabel as string;\n }\n\n const precision = callOptions?.precision ?? basePrecision;\n\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n minimumFractionDigits: precision,\n maximumFractionDigits: precision,\n }).format(effectiveValue);\n };\n\n return { formatPrice };\n}\n","import { useMemo } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport type { ResolvedStock, TStock } from \"@simpleapps-com/augur-utils\";\nimport { resolveStock } from \"@simpleapps-com/augur-utils\";\nimport { useAugurOptions } from \"../provider\";\nimport { stockEnabled, stockRetryDelay } from \"../rules\";\n\nexport interface UseStockOptions {\n enabled?: boolean;\n /** Override the default queryFn (e.g. with a custom server action). */\n queryFn?: () => Promise<TStock>;\n /** Company key to extract stock for a specific company. */\n companyKey?: string;\n /** Whether to round the quantity. */\n round?: boolean;\n /** Threshold below which stock is considered \"low\". */\n lowStockThreshold?: number;\n /** Whether to include the quantity in the resolved output. */\n showQuantity?: boolean;\n}\n\n/** Raw stock, its resolved form, and query state returned by useStock. */\ninterface StockResult {\n stock: TStock | null;\n resolved: ResolvedStock | null;\n loading: boolean;\n error: Error | null;\n}\n\n/**\n * Fetches full TStock data and resolves it into a normalized stock object.\n *\n * Uses the proxy from AugurHooksProvider context. Works with:\n * - Direct SDK (api prop on provider)\n * - Server actions (auto-detected via queryAction registration)\n * - Custom queryFn override\n */\nexport function useStock(invMastUid: number | string, options: UseStockOptions = {}): StockResult {\n const proxy = useAugurOptions();\n\n const resolvedQueryFn = options.queryFn;\n\n // Use the proxy for query options (works with SDK, server actions, or keys-only)\n const proxyOpts = proxy.items.invMast.stock.get(Number(invMastUid));\n\n const query = useQuery({\n ...proxyOpts,\n ...(resolvedQueryFn ? { queryFn: resolvedQueryFn } : {}),\n enabled: stockEnabled(options.enabled, !!invMastUid),\n retry: 3,\n retryDelay: stockRetryDelay,\n });\n\n // Every proxy resolves to the unwrapped SDK data (augur-core unwrapBaseResponse).\n const stockData = (query.data as TStock | undefined) ?? null;\n\n const resolved = useMemo(\n () =>\n resolveStock({\n stock: stockData,\n companyKey: options.companyKey,\n round: options.round,\n lowStockThreshold: options.lowStockThreshold,\n showQuantity: options.showQuantity,\n }),\n [stockData, options.companyKey, options.round, options.lowStockThreshold, options.showQuantity],\n );\n\n return {\n stock: stockData,\n resolved,\n loading: query.isLoading,\n error: query.error as Error | null,\n };\n}\n","import { useCallback } from \"react\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { TCartLine } from \"@simpleapps-com/augur-utils\";\nimport { lineHasQuantity } from \"@simpleapps-com/augur-utils\";\nimport { hasNumberFrom } from \"@atlas/utils/lists\";\nimport {\n addAccepted,\n indexOfUidFrom,\n indexOfUnitFrom,\n keepsAfterReverse,\n qtyOrZero,\n requiredCartUid,\n rollsBack,\n sendsPrice,\n toastShown,\n} from \"../rules\";\nimport { useCartStore, useCartHdrUid, useCartLines, useSetCartLines } from \"../stores/cart-store\";\n\ntype CartLineInput = {\n invMastUid: number;\n quantity: number;\n unitOfMeasure: string;\n cartHdrUid?: number | string | undefined;\n};\n\n/**\n * One cart line as `updateCartLines` sends it: `lineNo` 0, so the server's `update()` matches it\n * by item and unit of measure (a line number can be stale after a remove renumbers the cart), and\n * `unitPrice` only when the line has one (the route stores a sent `null` as 0.0). atlas#89.\n */\nexport type CartLineUpdate = Omit<TCartLine, \"unitPrice\"> & { unitPrice?: number };\n\n/** Site-specific callbacks injected into useCartActions. Each resolves `true` on success. */\nexport interface CartActionCallbacks {\n /** Add items to cart via API. `true` = success, `false` = failure. */\n addToCart: (\n cartHdrUid: number,\n items: Array<{\n cartHdrUid: number;\n invMastUid: number;\n quantity: number;\n unitOfMeasure: string;\n }>,\n ) => Promise<boolean>;\n /** Update cart lines via API (the one changed line). `true` = success, `false` = failure. */\n updateCartLines: (cartHdrUid: number, lines: CartLineUpdate[]) => Promise<boolean>;\n /** Delete all items from cart via API. `true` = success, `false` = failure. */\n deleteItemsFromCart: (cartHdrUid: number) => Promise<boolean>;\n /** Optional toast notification callback. */\n toast?: {\n info?: (message: string) => void;\n error?: (message: string) => void;\n success?: (message: string) => void;\n };\n}\n\ninterface CartActionOptions {\n showToast?: boolean;\n itemId?: string;\n /**\n * The line's unit of measure, for an item in the cart in more than one; without it, the unit of\n * the item's first line. `updateQuantity` and `removeFromCart` change only that line.\n */\n unitOfMeasure?: string;\n onSuccess?: () => void;\n onError?: (error: Error) => void;\n}\n\n/** Actions and state returned by useCartActions. */\ninterface CartActions {\n addToCart: (item: CartLineInput, options?: CartActionOptions) => Promise<boolean>;\n updateQuantity: (\n invMastUid: number,\n newQuantity: number,\n options?: CartActionOptions,\n ) => Promise<boolean>;\n removeFromCart: (invMastUid: number, options?: CartActionOptions) => Promise<boolean>;\n clearCart: (options?: Omit<CartActionOptions, \"itemId\" | \"unitOfMeasure\">) => Promise<boolean>;\n isInCart: (invMastUid: number) => boolean;\n getItemQuantity: (invMastUid: number) => number;\n cartHdrUid: number | string | undefined;\n cartLines: TCartLine[];\n invalidateCartCache: () => void;\n}\n\n/** A store cart uid as a number, or undefined when unset (NaN is no uid, as `!num` treated it). */\nfunction cartUidOf(cartHdrUid: string | number | undefined): number | undefined {\n const num = typeof cartHdrUid === \"string\" ? Number(cartHdrUid) : cartHdrUid;\n return num === undefined || Number.isNaN(num) ? undefined : num;\n}\n\nfunction requireCartUid(cartHdrUid: string | number | undefined): number {\n const uid = requiredCartUid(cartUidOf(cartHdrUid));\n if (uid === null) throw new Error(\"Cart UID is not set\");\n return uid;\n}\n\n/** The store's LIVE cart (not a render closure), so concurrent ops stack; throws with no cart UID. */\nfunction liveCart(): { uid: number; lines: TCartLine[] } {\n const { cartHdrUid, cartLines } = useCartStore.getState();\n return { uid: requireCartUid(cartHdrUid), lines: cartLines };\n}\n\nfunction buildOptimisticAdd(\n cartLines: TCartLine[],\n item: CartLineInput,\n cartHdrUid: number,\n itemId: string,\n): TCartLine[] {\n const existingIndex = indexOfUidFrom(uidsOf(cartLines), item.invMastUid, 0);\n\n if (existingIndex >= 0) {\n return cartLines.map((line, index) =>\n index === existingIndex\n ? { ...line, quantity: qtyOrZero(line.quantity) + item.quantity }\n : line,\n );\n }\n\n return [\n ...cartLines,\n {\n cartHdrUid,\n invMastUid: item.invMastUid,\n invMastUidCount: 1,\n isAssembly: \"N\",\n itemId,\n lineNo: cartLines.length + 1,\n lineNote: null,\n quantity: item.quantity,\n unitOfMeasure: item.unitOfMeasure,\n key: null,\n unitPrice: null,\n },\n ];\n}\n\n// --- Targeted optimistic-rollback helpers ---------------------------------\n// Each reverses ONLY its own op's delta against the LIVE store state (passed\n// in from useCartStore.getState()), never a stale render-closure snapshot,\n// and only while the store still holds the op's cart (settleCartOp).\n\n/**\n * Reverse an optimistic add.\n * @invariant only the FIRST line with the item loses q (buildOptimisticAdd added to the first\n * only; atlas#89 finding 7), dropped iff nothing is left; other lines untouched.\n */\nfunction reverseAdd(cartLines: TCartLine[], invMastUid: number, quantity: number): TCartLine[] {\n const index = indexOfUidFrom(uidsOf(cartLines), invMastUid, 0);\n if (index < 0) return cartLines;\n const line = cartLines[index] as TCartLine;\n if (!keepsAfterReverse(line.quantity, quantity)) {\n return [...cartLines.slice(0, index), ...cartLines.slice(index + 1)];\n }\n return cartLines.map((l, i) =>\n i === index ? { ...l, quantity: qtyOrZero(l.quantity) - quantity } : l,\n );\n}\n\n/** The line an update or remove changes, as an index (or −1): item and unit of measure. */\ninterface Target {\n invMastUid: number;\n unit: string;\n}\n\n/**\n * The target line's index: the first line with the item in `unitOfMeasure`, or in the unit of the\n * item's first line when none is given.\n */\nfunction targetOf(\n cartLines: TCartLine[],\n invMastUid: number,\n unitOfMeasure: string | undefined,\n): Target | null {\n const first = indexOfUidFrom(uidsOf(cartLines), invMastUid, 0);\n if (first < 0) return null;\n const unit = unitOfMeasure ?? unitOf(cartLines[first] as TCartLine);\n if (indexOfUnitFrom(uidsOf(cartLines), unitsOf(cartLines), invMastUid, unit, 0) < 0) return null;\n return { invMastUid, unit };\n}\n\n/** Whether a line is the target's: same item and unit of measure. */\nfunction isTarget(line: TCartLine, target: Target): boolean {\n return (\n indexOfUnitFrom([line.invMastUid], [unitOf(line)], target.invMastUid, target.unit, 0) === 0\n );\n}\n\n/** The target's first line (it exists: `targetOf` found it). */\nfunction targetLine(cartLines: TCartLine[], target: Target): TCartLine {\n const index = indexOfUnitFrom(\n uidsOf(cartLines),\n unitsOf(cartLines),\n target.invMastUid,\n target.unit,\n 0,\n );\n return cartLines[index] as TCartLine;\n}\n\n/**\n * Reverse an optimistic quantity set.\n * @invariant the target's lines go back to their pre-op quantity; other lines untouched.\n */\nfunction reverseQuantity(\n cartLines: TCartLine[],\n target: Target,\n previousQuantity: TCartLine[\"quantity\"],\n): TCartLine[] {\n return cartLines.map((line) =>\n isTarget(line, target) ? { ...line, quantity: previousQuantity } : line,\n );\n}\n\n/**\n * Reverse an optimistic remove by re-inserting the removed line.\n * @invariant re-adds removedLine iff no line of its item and unit is there now (a concurrent op\n * may have re-added it; never duplicate).\n */\nfunction restoreRemoved(\n cartLines: TCartLine[],\n target: Target,\n removedLine: TCartLine,\n): TCartLine[] {\n if (\n indexOfUnitFrom(uidsOf(cartLines), unitsOf(cartLines), target.invMastUid, target.unit, 0) >= 0\n ) {\n return cartLines;\n }\n return [...cartLines, removedLine];\n}\n\n/**\n * Reverse an optimistic clear by restoring snapshot lines missing from live state.\n * @invariant result ⊇ live ∧ result ⊇ snapshot (by invMastUid); concurrent adds\n * that landed after the clear are preserved, cleared lines are restored.\n */\nfunction mergeRestore(cartLines: TCartLine[], snapshot: TCartLine[]): TCartLine[] {\n const merged = [...cartLines];\n for (const line of snapshot) {\n if (!hasNumberFrom(uidsOf(merged), line.invMastUid, 0)) merged.push(line);\n }\n return merged;\n}\n\n/** The line as `updateCartLines` sends it: the quantity, `lineNo` 0, a price only when set. */\nfunction sentLine(line: TCartLine, quantity: number): CartLineUpdate {\n const { unitPrice, ...rest } = line;\n const sent: CartLineUpdate = { ...rest, quantity, lineNo: 0 };\n if (sendsPrice(unitPrice)) sent.unitPrice = unitPrice as number;\n return sent;\n}\n\n/** Each line's item uid, in order. */\nfunction uidsOf(cartLines: TCartLine[]): number[] {\n return cartLines.map((line) => line.invMastUid);\n}\n\n/** A line's unit of measure, null as \"\". */\nfunction unitOf(line: TCartLine): string {\n return line.unitOfMeasure ?? \"\";\n}\n\n/** Each line's unit of measure, in order. */\nfunction unitsOf(cartLines: TCartLine[]): string[] {\n return cartLines.map(unitOf);\n}\n\n/** Calls `notify[kind]` as a method when toasts are on, it is set, and there is a message. */\nfunction sendToast(\n notify: CartActionCallbacks[\"toast\"],\n kind: \"info\" | \"error\",\n showToast: boolean,\n message: string | undefined,\n): void {\n if (toastShown(showToast, message !== undefined)) notify?.[kind]?.(message as string);\n}\n\n/** One cart op after its optimistic update: the server call and how it settles. */\ninterface CartOp {\n /** The cart the op ran on. */\n cartUid: number;\n call: () => Promise<boolean>;\n /** The error a falsy result becomes (what `onError` receives). */\n failure: string;\n /** The success toast, if the op has one. */\n infoMessage?: string;\n errorMessage: string;\n showToast: boolean;\n /** Undoes this op's own optimistic change against the live store. */\n rollback: () => void;\n}\n\n/**\n * Runs the server call. On success: the info toast, `onSuccess`, true. On a falsy result or a\n * throw: the rollback (only while the store still holds the op's cart), the error toast,\n * `onError`, false. Either way the op stops counting as in flight and the cart queries are\n * invalidated, so the live cart refetches and its data reaches the store (atlas#89).\n */\nasync function settleCartOp(\n op: CartOp,\n options: CartActionOptions,\n notify: CartActionCallbacks[\"toast\"],\n invalidate: () => void,\n): Promise<boolean> {\n const { endCartOp } = useCartStore.getState();\n try {\n const success = await op.call();\n if (!success) throw new Error(op.failure);\n } catch (error) {\n if (rollsBack(cartUidOf(useCartStore.getState().cartHdrUid), op.cartUid)) op.rollback();\n endCartOp();\n invalidate();\n sendToast(notify, \"error\", op.showToast, op.errorMessage);\n options.onError?.(error as Error);\n return false;\n }\n endCartOp();\n invalidate();\n sendToast(notify, \"info\", op.showToast, op.infoMessage);\n options.onSuccess?.();\n return true;\n}\n\n/**\n * Optimistic cart actions hook with automatic rollback on failure.\n *\n * Accepts site-specific server action callbacks so the hook itself\n * has no dependency on any particular server action implementation.\n *\n * @example\n * ```tsx\n * import { useCartActions } from \"@simpleapps-com/augur-hooks\";\n * import { addToCart, updateCartLines, deleteItemsFromCart } from \"@/lib/actions/commerce\";\n * import { toast } from \"react-toastify\";\n *\n * const cart = useCartActions({\n * addToCart, updateCartLines, deleteItemsFromCart,\n * toast: { info: toast.info, error: toast.error },\n * });\n *\n * await cart.addToCart({ invMastUid: 123, quantity: 1, unitOfMeasure: \"EA\" });\n * ```\n */\nexport function useCartActions(callbacks: CartActionCallbacks): CartActions {\n const queryClient = useQueryClient();\n const cartHdrUid = useCartHdrUid();\n const cartLines = useCartLines();\n const setCartLines = useSetCartLines();\n const notify = callbacks.toast;\n\n // Every cart's lines (the live cart's query refetches) and the render's also-bought.\n const invalidateCartCache = useCallback(() => {\n void queryClient.invalidateQueries({ queryKey: [\"cartLines\"] });\n void queryClient.invalidateQueries({\n queryKey: [\"cart-also-bought\", cartHdrUid],\n });\n }, [queryClient, cartHdrUid]);\n\n const addToCart = useCallback(\n async (item: CartLineInput, options: CartActionOptions = {}): Promise<boolean> => {\n const { showToast = true, itemId = \"\" } = options;\n // A cart line MUST have its unit of measure and its quantity: augur enforces neither (atlas#93).\n const quantity = Number.isFinite(item.quantity) ? item.quantity : null;\n if (!addAccepted(item.unitOfMeasure, quantity)) {\n sendToast(notify, \"error\", showToast, \"Choose a quantity and a unit of measure.\");\n options.onError?.(new Error(\"Quantity and unit of measure are required\"));\n return false;\n }\n const { uid, lines: liveLines } = liveCart();\n\n useCartStore.getState().beginCartOp();\n setCartLines(buildOptimisticAdd(liveLines, item, uid, itemId));\n\n return settleCartOp(\n {\n cartUid: uid,\n call: () =>\n callbacks.addToCart(uid, [\n {\n cartHdrUid: uid,\n invMastUid: item.invMastUid,\n quantity: item.quantity,\n unitOfMeasure: item.unitOfMeasure,\n },\n ]),\n failure: \"Failed to add item to cart\",\n infoMessage: `${item.quantity} x ${itemId || \"Item\"} added to cart`,\n errorMessage: \"Failed to add item to cart. Please try again.\",\n showToast,\n rollback: () =>\n setCartLines(\n reverseAdd(useCartStore.getState().cartLines, item.invMastUid, item.quantity),\n ),\n },\n options,\n notify,\n invalidateCartCache,\n );\n },\n [setCartLines, invalidateCartCache, callbacks, notify],\n );\n\n const updateQuantity = useCallback(\n async (\n invMastUid: number,\n newQuantity: number,\n options: CartActionOptions = {},\n ): Promise<boolean> => {\n const { showToast = false, unitOfMeasure } = options;\n // A cart line MUST have a quantity (AugurHooks.UpdateAccepted): NaN reaches augur as null,\n // which it writes as 0, deleting the line.\n if (!lineHasQuantity(Number.isFinite(newQuantity) ? newQuantity : null)) {\n sendToast(notify, \"error\", showToast, \"Choose a quantity.\");\n options.onError?.(new Error(\"Quantity is required\"));\n return false;\n }\n const { uid, lines: liveLines } = liveCart();\n const target = targetOf(liveLines, invMastUid, unitOfMeasure);\n // Not in the cart: nothing to change (the page offers this only on a line it shows).\n if (target === null) return true;\n const line = targetLine(liveLines, target);\n const previousQuantity = line.quantity;\n\n useCartStore.getState().beginCartOp();\n setCartLines(\n liveLines.map((l) => (isTarget(l, target) ? { ...l, quantity: newQuantity } : l)),\n );\n\n return settleCartOp(\n {\n cartUid: uid,\n call: () => callbacks.updateCartLines(uid, [sentLine(line, newQuantity)]),\n failure: \"Failed to update quantity\",\n errorMessage: \"Failed to update quantity. Please try again.\",\n showToast,\n rollback: () =>\n setCartLines(\n reverseQuantity(useCartStore.getState().cartLines, target, previousQuantity),\n ),\n },\n options,\n notify,\n invalidateCartCache,\n );\n },\n [setCartLines, invalidateCartCache, callbacks, notify],\n );\n\n const removeFromCart = useCallback(\n async (invMastUid: number, options: CartActionOptions = {}): Promise<boolean> => {\n const { showToast = true, itemId = \"\", unitOfMeasure } = options;\n const { uid, lines: liveLines } = liveCart();\n const target = targetOf(liveLines, invMastUid, unitOfMeasure);\n // Not in the cart: nothing to remove.\n if (target === null) return true;\n const removedLine = targetLine(liveLines, target);\n\n useCartStore.getState().beginCartOp();\n setCartLines(liveLines.filter((l) => !isTarget(l, target)));\n\n return settleCartOp(\n {\n cartUid: uid,\n call: () => callbacks.updateCartLines(uid, [sentLine(removedLine, 0)]),\n failure: \"Failed to remove item\",\n infoMessage: `${itemId || \"Item\"} removed from cart`,\n errorMessage: \"Failed to remove item. Please try again.\",\n showToast,\n rollback: () =>\n setCartLines(restoreRemoved(useCartStore.getState().cartLines, target, removedLine)),\n },\n options,\n notify,\n invalidateCartCache,\n );\n },\n [setCartLines, invalidateCartCache, callbacks, notify],\n );\n\n const clearCart = useCallback(\n async (options: Omit<CartActionOptions, \"itemId\" | \"unitOfMeasure\"> = {}): Promise<boolean> => {\n const { showToast = true } = options;\n const { uid, lines: snapshot } = liveCart();\n useCartStore.getState().beginCartOp();\n setCartLines([]);\n\n return settleCartOp(\n {\n cartUid: uid,\n call: () => callbacks.deleteItemsFromCart(uid),\n failure: \"Failed to clear cart\",\n infoMessage: \"Cart cleared\",\n errorMessage: \"Failed to clear cart. Please try again.\",\n showToast,\n rollback: () => setCartLines(mergeRestore(useCartStore.getState().cartLines, snapshot)),\n },\n options,\n notify,\n invalidateCartCache,\n );\n },\n [setCartLines, invalidateCartCache, callbacks, notify],\n );\n\n const isInCart = useCallback(\n (invMastUid: number): boolean => {\n return cartLines.some((line) => line.invMastUid === invMastUid);\n },\n [cartLines],\n );\n\n const getItemQuantity = useCallback(\n (invMastUid: number): number => {\n return cartLines.find((line) => line.invMastUid === invMastUid)?.quantity ?? 0;\n },\n [cartLines],\n );\n\n return {\n addToCart,\n updateQuantity,\n removeFromCart,\n clearCart,\n isInCart,\n getItemQuantity,\n cartHdrUid,\n cartLines,\n invalidateCartCache,\n };\n}\n","\"use client\";\nimport { useEffect, useState } from \"react\";\nimport { bodyOverflow, closesOnKey } from \"../rules\";\n\n/**\n * Shared modal lifecycle hook -- scroll lock, Escape key, client-side hydration gate.\n *\n * Locks body scroll when the modal is open and restores it on close.\n * Listens for Escape key to trigger onClose. Returns isClient for\n * hydration-safe conditional rendering.\n */\nexport function useModalLifecycle(isOpen: boolean, onClose: () => void) {\n const [isClient, setIsClient] = useState(false);\n\n useEffect(() => {\n setIsClient(true);\n }, []);\n\n // Scroll lock\n useEffect(() => {\n document.body.style.overflow = bodyOverflow(isOpen);\n return () => {\n document.body.style.overflow = \"auto\";\n };\n }, [isOpen]);\n\n // Escape key\n useEffect(() => {\n const handleEscape = (e: KeyboardEvent) => {\n if (closesOnKey(e.key, isOpen)) onClose();\n };\n document.addEventListener(\"keydown\", handleEscape);\n return () => document.removeEventListener(\"keydown\", handleEscape);\n }, [isOpen, onClose]);\n\n return { isClient };\n}\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport type { TCartLine } from \"@simpleapps-com/augur-utils\";\nimport { acceptsLookup, cartIdle, initStepOf } from \"../rules\";\nimport {\n useCartHdrUid,\n useCartStore,\n useSetCartHdrUid,\n useSetCartLines,\n useClearCart,\n} from \"../stores/cart-store\";\nimport { useAugurAuth } from \"../provider\";\n\nconst MAX_RETRY_ATTEMPTS = 7;\nconst RETRY_DELAY_MS = 1000;\n/** After a lookup's attempts all fail, it starts again this much later (atlas#89 finding 17). */\nconst LOOKUP_RESTART_MS = 30_000;\n\n/** Before another lookup attempt: wait 1 s × 1.5^attempt (at most 10 s); none after the last. */\nasync function waitBeforeRetry(attempt: number): Promise<void> {\n if (attempt >= MAX_RETRY_ATTEMPTS) return;\n const delay = Math.min(RETRY_DELAY_MS * Math.pow(1.5, attempt), 10000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n}\n\n/** Session info passed from the consumer's auth system. */\nexport interface CartSessionInfo {\n /** Auth status: \"loading\" | \"authenticated\" | \"unauthenticated\" */\n status: \"loading\" | \"authenticated\" | \"unauthenticated\";\n /** User's ID (e.g., Joomla user ID). Undefined if not authenticated. */\n userId?: string | number;\n /** Cart header UID from the auth session, if available. */\n cartHdrUid?: number | string;\n}\n\n/** Site-specific callbacks injected into useCartInitialization. */\nexport interface CartInitCallbacks {\n /** Look up or create a cart header. Returns { cartHdrUid, cartToken? }. */\n cartHdrLookup: (\n userId: string | number,\n cartToken: string,\n ) => Promise<{ cartHdrUid: number; cartToken?: string | null } | false | null | undefined>;\n /** Fetch cart line items for a given cart header UID. */\n getCartLines: (cartHdrUid: number) => Promise<TCartLine[] | undefined>;\n /** Get the current cart token. Defaults to localStorage.getItem(\"cartToken\"). */\n getCartToken?: () => string | null;\n /** Save cart token. Defaults to localStorage.setItem(\"cartToken\", token). */\n saveCartToken?: (token: string) => void;\n /** Generate a new unique cart token. Defaults to crypto.randomUUID(). */\n generateCartToken?: () => string;\n}\n\nconst defaultGetCartToken = () => localStorage.getItem(\"cartToken\");\nconst defaultSaveCartToken = (token: string) => localStorage.setItem(\"cartToken\", token);\nconst defaultGenerateCartToken = () => crypto.randomUUID();\n\n/** A cart uid as text, so a session's \"42\" and a store's 42 compare equal. */\nfunction cartKey(uid: number | string | undefined): string | undefined {\n return uid === undefined ? undefined : String(uid);\n}\n\n/**\n * Initialize cart state from session (authenticated) or cookie (guest).\n * Call once in the root layout.\n *\n * - A signed-in session's `cartHdrUid` is the cart, also when the store holds a guest cart.\n * - A signed-in session with no `cartHdrUid` looks the user's cart up (`cartHdrLookup(userId, …)`).\n * - A guest looks a cart up with its token (`cartHdrLookup(\"0\", …)`); a lookup's answer is used\n * only while the shopper is still in the state it was started for, with no cart set.\n * - A lookup whose attempts all fail starts again 30 s later.\n * - The cart's lines reach the store on every fetch while no cart op is in flight.\n *\n * @example\n * ```tsx\n * import { useCartInitialization } from \"@simpleapps-com/augur-hooks\";\n * import { useSession } from \"next-auth/react\";\n * import { cartHdrLookup, getCartLines } from \"@/lib/actions/commerce\";\n *\n * function CartInitializer() {\n * const { data: session, status } = useSession();\n *\n * // Minimal setup — token storage defaults to localStorage,\n * // token generation defaults to crypto.randomUUID().\n * useCartInitialization(\n * {\n * status,\n * userId: session?.user?.id,\n * cartHdrUid: session?.user?.cartHdrUid,\n * },\n * { cartHdrLookup, getCartLines },\n * );\n *\n * return null;\n * }\n * ```\n */\nexport function useCartInitialization(session: CartSessionInfo, callbacks: CartInitCallbacks) {\n const getCartToken = callbacks.getCartToken ?? defaultGetCartToken;\n const saveCartToken = callbacks.saveCartToken ?? defaultSaveCartToken;\n const generateCartToken = callbacks.generateCartToken ?? defaultGenerateCartToken;\n\n const auth = useAugurAuth();\n const cartHdrUid = useCartHdrUid();\n const setCartHdrUid = useSetCartHdrUid();\n const setCartLines = useSetCartLines();\n const clearCart = useClearCart();\n const queryClient = useQueryClient();\n\n // Merge session with provider auth — session fields take priority\n const effectiveStatus = session.status;\n const effectiveUserId = session.userId ?? auth?.userId;\n const effectiveCartHdrUid = session.cartHdrUid ?? auth?.cartHdrUid;\n const effectiveSession = useMemo<CartSessionInfo>(\n () => ({ status: effectiveStatus, userId: effectiveUserId, cartHdrUid: effectiveCartHdrUid }),\n [effectiveStatus, effectiveUserId, effectiveCartHdrUid],\n );\n\n const retryCountRef = useRef(0);\n const isInitializingRef = useRef(false);\n const prevStatusRef = useRef(effectiveSession.status);\n // The status now, for a lookup that answers after the session changed.\n const statusRef = useRef(effectiveSession.status);\n statusRef.current = effectiveSession.status;\n // Bumped 30 s after a lookup gave up, so the init effect runs (and looks up) again.\n const [lookupRound, setLookupRound] = useState(0);\n const restartTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n\n useEffect(() => () => clearTimeout(restartTimerRef.current), []);\n\n // Auto-clear cart on logout (authenticated → unauthenticated)\n useEffect(() => {\n const prevStatus = prevStatusRef.current;\n prevStatusRef.current = effectiveSession.status;\n\n if (prevStatus === \"authenticated\" && effectiveSession.status === \"unauthenticated\") {\n clearCart();\n queryClient.removeQueries({ queryKey: [\"cartLines\"] });\n queryClient.removeQueries({ queryKey: [\"cart-also-bought\"] });\n }\n }, [effectiveSession.status, clearCart, queryClient]);\n\n // Initialize cart header\n useEffect(() => {\n const step = initStepOf(\n effectiveSession.status === \"loading\",\n effectiveSession.status === \"authenticated\",\n !!effectiveSession.cartHdrUid,\n cartKey(cartHdrUid) === cartKey(effectiveSession.cartHdrUid),\n !!cartHdrUid,\n effectiveSession.userId !== undefined,\n isInitializingRef.current,\n );\n\n if (step.kind === \"stay\") return;\n\n if (step.kind === \"session\") {\n setCartHdrUid(effectiveSession.cartHdrUid);\n return;\n }\n\n // A lookup: the user's cart (signed in, no cart on the session) or a guest cart.\n const forUser = step.kind === \"user\";\n const lookupUserId = forUser ? (effectiveSession.userId as string | number) : \"0\";\n isInitializingRef.current = true;\n retryCountRef.current = 0;\n\n const lookUpCart = async () => {\n const existingToken = getCartToken();\n const cartToken =\n existingToken && typeof existingToken === \"string\" ? existingToken : generateCartToken();\n let lastError: unknown;\n\n while (retryCountRef.current < MAX_RETRY_ATTEMPTS) {\n try {\n const cartHdr = await callbacks.cartHdrLookup(lookupUserId, cartToken);\n\n if (cartHdr && cartHdr.cartHdrUid !== 0) {\n // The answer applies only if the shopper is still where it started, with no cart.\n const stillApplies = acceptsLookup(\n forUser,\n statusRef.current === \"authenticated\",\n !!useCartStore.getState().cartHdrUid,\n );\n if (stillApplies) {\n saveCartToken(cartToken);\n setCartHdrUid(cartHdr.cartHdrUid);\n }\n isInitializingRef.current = false;\n return;\n }\n\n retryCountRef.current++;\n await waitBeforeRetry(retryCountRef.current);\n } catch (error) {\n // Retries are expected; only the final failure is logged (below).\n lastError = error;\n retryCountRef.current++;\n await waitBeforeRetry(retryCountRef.current);\n }\n }\n\n console.error(`Cart initialization failed after ${MAX_RETRY_ATTEMPTS} attempts`, lastError);\n isInitializingRef.current = false;\n // Without a cart every action throws: look again later rather than never.\n restartTimerRef.current = setTimeout(() => setLookupRound((n) => n + 1), LOOKUP_RESTART_MS);\n };\n\n void lookUpCart();\n }, [\n effectiveSession,\n cartHdrUid,\n setCartHdrUid,\n callbacks,\n getCartToken,\n saveCartToken,\n generateCartToken,\n lookupRound,\n ]);\n\n // Fetch cart lines when cartHdrUid is available. No structural sharing: a refetch that equals\n // the last data still reaches the sync below, so a store a rollback left wrong is corrected.\n const { data: cartLinesData } = useQuery({\n queryKey: [\"cartLines\", cartHdrUid],\n queryFn: async () => (await callbacks.getCartLines(Number(cartHdrUid))) ?? [],\n enabled: !!cartHdrUid,\n structuralSharing: false,\n });\n\n // Sync cart lines to the Zustand store, while no cart op is in flight (one landing mid-op\n // would wipe its optimistic change; that op's settle refetches).\n useEffect(() => {\n if (cartLinesData && cartIdle(useCartStore.getState().pendingCartOps)) {\n setCartLines(cartLinesData);\n }\n }, [cartLinesData, setCartLines]);\n\n return {\n cartHdrUid,\n isInitializing: isInitializingRef.current,\n retryCount: retryCountRef.current,\n };\n}\n","import { useMemo } from \"react\";\nimport { queryOptions, skipToken, useQueries } from \"@tanstack/react-query\";\nimport type { AddressId, DerivedPrice, TPriceData } from \"@simpleapps-com/augur-utils\";\nimport {\n cleanMoney,\n derivePrice,\n linePriceAt,\n priceQueryRuns,\n priceQueryUnit,\n pricingLoadingFrom,\n pricingSettledFrom,\n resolveAddressId,\n} from \"@simpleapps-com/augur-utils\";\nimport { lineUnitPrice } from \"../rules\";\nimport { useCartLines } from \"../stores/cart-store\";\nimport { useAugurOptions, useAugurAuth, useAugurSite } from \"../provider\";\n\nexport interface CartPriceData {\n unitPrice: number;\n priceData: Record<string, unknown> | null;\n}\n\nexport interface CartPricingResult {\n /**\n * Map of itemId -> price data. An item on more than one line (two units of measure) holds its\n * last line's price: read a line's own price with `getLineUnitPrice` / `linePrices`.\n */\n prices: Record<string, CartPriceData>;\n /** Each cart line's own price data, in cart order (null until it loads). */\n linePrices: (CartPriceData | null)[];\n /**\n * Unit price for an item (0 if not found). Per item: for an item on more than one line, use\n * `getLineUnitPrice`.\n */\n getUnitPrice: (itemId: string) => number;\n /** `getUnitPrice(itemId)` × quantity. Per item, as `getUnitPrice`. */\n getItemTotal: (itemId: string, quantity: number) => number;\n /**\n * Unit price of the cart line at `index`, fetched at that line's quantity (0 past the cart or not\n * priced). Each line keeps its own price, so one item on two lines can show two.\n */\n getLineUnitPrice: (index: number) => number;\n /** The line's total: `getLineUnitPrice(index)` × its quantity (0 without a quantity). */\n getLineTotal: (index: number) => number;\n /** Cart subtotal: the sum of every line's own total. */\n subtotal: number;\n /** True if any price that is fetched is still loading */\n isLoading: boolean;\n /**\n * True once every price that is fetched has loaded. A line whose price is never fetched (no\n * quantity, no itemId, no customer) doesn't hold it back.\n */\n isSuccess: boolean;\n /** True if any price failed to load */\n isError: boolean;\n}\n\ninterface UseCartPricingOptions {\n customerId?: string | number;\n /**\n * Override per-line price fetching (e.g. with a custom server action, such as augur-server's\n * `getItemPrice`). `unitOfMeasure` is the line's unit (undefined when it has none): pass it to the\n * price engine, which otherwise prices the item's default selling unit (a CASE/6 line as one EACH).\n */\n queryFn?: (\n itemId: string,\n customerId: string | number,\n quantity: number,\n unitOfMeasure?: string,\n ) => Promise<TPriceData>;\n}\n\n/**\n * derivePrice for a known quantity, or null when it refuses the input (negative or non-finite\n * quantity or unitPrice: its RangeError), so one bad line degrades instead of throwing during render\n * and crashing the cart (GH #496). Any other error is a bug and is rethrown.\n */\nfunction derivedOrRefused(priceData: TPriceData, quantity: number): DerivedPrice | null {\n try {\n return derivePrice({ priceData, quantity });\n } catch (error) {\n if (error instanceof RangeError) return null;\n throw error;\n }\n}\n\n/**\n * Unit price for one cart line (the proved `lineUnitPrice`): only a line with a quantity that\n * derivePrice prices has one; no quantity (null, or non-finite at runtime), loading,\n * callForPrice and a refused input all give 0.\n */\nfunction deriveLineUnitPrice(priceData: TPriceData, quantity: number | null): number {\n const hasQuantity = typeof quantity === \"number\" && Number.isFinite(quantity);\n const derived = hasQuantity ? derivedOrRefused(priceData, quantity as number) : null;\n const priced = derived?.state === \"priced\";\n return lineUnitPrice(hasQuantity, priced, priced ? derived.unitPrice : 0);\n}\n\n/**\n * Extended price for one line. A non-finite quantity (NaN, ±Infinity, or null\n * at runtime) contributes 0, so one bad line cannot turn the whole subtotal\n * into NaN (GH #496). The product is passed through cleanMoney to drop float noise.\n */\nfunction lineTotal(unitPrice: number, quantity: number | null): number {\n return Number.isFinite(quantity) ? cleanMoney(unitPrice * (quantity as number)) : 0;\n}\n\n/**\n * A line's price query keyed by the line, not the proxy: through a custom `queryFn`, or, with no\n * customer, TanStack's `skipToken`, a query that cannot run (priceQueryRuns needs a customer too).\n */\nfunction keyedPriceQuery(\n itemId: string,\n customerId: AddressId | null,\n quantity: number,\n unitOfMeasure: string | undefined,\n enabled: boolean,\n priceFn: UseCartPricingOptions[\"queryFn\"],\n) {\n return queryOptions({\n queryKey: [\"price\", itemId?.toUpperCase() || \"\", customerId, quantity, unitOfMeasure ?? \"\"],\n queryFn:\n priceFn && customerId !== null\n ? () => priceFn(itemId, customerId, quantity, unitOfMeasure)\n : skipToken,\n refetchOnReconnect: true,\n refetchOnWindowFocus: false,\n meta: { persist: true },\n enabled,\n });\n}\n\n/**\n * Centralized hook for cart/checkout pricing.\n *\n * Fetches prices for ALL cart items with their actual quantities\n * to support quantity-based price breaks. React Query dedupes\n * identical calls across components.\n *\n * Uses the proxy from AugurHooksProvider context. Works with:\n * - Direct SDK (api prop on provider)\n * - Server actions (auto-detected via queryAction registration)\n * - Custom queryFn override\n */\nexport function useCartPricing(options: UseCartPricingOptions = {}): CartPricingResult {\n const proxy = useAugurOptions();\n const auth = useAugurAuth();\n const site = useAugurSite();\n const cartLines = useCartLines();\n // The first usable customer: the option's, the session's, then the site's default. \"\" and \"0\" are\n // no customer, so they never hide the default or price customer 0 (atlas#95).\n const customerId = resolveAddressId(\n options.customerId,\n auth?.customerId,\n site?.defaults?.customerId,\n );\n\n const priceFn = options.queryFn;\n\n // Whether each line's price is fetched: a customer, an itemId and a quantity (proved rule). augur\n // never stores a null quantity (models/AugurCommerceCartLine.dfy RoutesWriteQuantity); the type\n // allows one, and such a line is simply not priced.\n const runs = cartLines.map((line) =>\n priceQueryRuns(customerId !== null, !!line.itemId, line.quantity),\n );\n\n const priceQueries = useQueries({\n queries: cartLines.map((line, index) => {\n // Only the query key reads this for a line without a quantity: its query never runs.\n const quantity = line.quantity ?? 0;\n const enabled = runs[index] === true;\n // Priced in the line's own unit (proved rule): the engine prices no unit as the default one.\n const unitOfMeasure = priceQueryUnit(line.unitOfMeasure) ?? undefined;\n // A custom queryFn, or no customer: in a price a customer is never 0 (atlas#95), so with\n // none no price call is built: the line's query is `skipToken` and never runs.\n if (priceFn || customerId === null) {\n return keyedPriceQuery(line.itemId, customerId, quantity, unitOfMeasure, enabled, priceFn);\n }\n\n // Use the proxy — works with SDK, server actions, or keys-only\n const proxyOpts = proxy.pricing.priceEngine.list({\n itemId: line.itemId?.toUpperCase() || \"\",\n customerId,\n quantity,\n unitOfMeasure,\n });\n\n return {\n ...proxyOpts,\n enabled,\n refetchOnReconnect: true,\n refetchOnWindowFocus: false,\n meta: { persist: true },\n };\n }),\n });\n\n // Each line's own price (atlas#93), in cart order: fetched at its own quantity, so one item on two\n // lines (two units of measure) keeps two prices. null until its data loads.\n const linePrices = useMemo(\n () =>\n cartLines.map((line, index): CartPriceData | null => {\n // Every proxy resolves to the unwrapped SDK data (augur-core unwrapBaseResponse).\n const priceData = priceQueries[index]?.data as TPriceData | undefined;\n if (!priceData) return null;\n return {\n unitPrice: deriveLineUnitPrice(priceData, line.quantity),\n priceData: priceData as Record<string, unknown>,\n };\n }),\n [cartLines, priceQueries],\n );\n\n const lineUnitPrices = useMemo(() => linePrices.map((p) => p?.unitPrice ?? 0), [linePrices]);\n\n // By itemId, kept for compatibility: an item on more than one line holds its last line's price.\n const prices = useMemo(() => {\n const map: Record<string, CartPriceData> = {};\n cartLines.forEach((line, index) => {\n const linePrice = linePrices[index];\n if (linePrice) map[line.itemId.toUpperCase()] = linePrice;\n });\n return map;\n }, [cartLines, linePrices]);\n\n const getUnitPrice = useMemo(() => {\n return (itemId: string): number => {\n return prices[itemId?.toUpperCase()]?.unitPrice ?? 0;\n };\n }, [prices]);\n\n const getItemTotal = useMemo(() => {\n return (itemId: string, quantity: number): number => {\n return lineTotal(getUnitPrice(itemId), quantity);\n };\n }, [getUnitPrice]);\n\n // The proved linePriceAt: line `index`'s own price, 0 past the cart.\n const getLineUnitPrice = useMemo(() => {\n return (index: number): number => linePriceAt(lineUnitPrices, index);\n }, [lineUnitPrices]);\n\n const getLineTotal = useMemo(() => {\n return (index: number): number =>\n lineTotal(linePriceAt(lineUnitPrices, index), cartLines[index]?.quantity ?? null);\n }, [cartLines, lineUnitPrices]);\n\n const subtotal = useMemo(() => {\n return cartLines.reduce(\n (sum, line, index) =>\n cleanMoney(sum + lineTotal(linePriceAt(lineUnitPrices, index), line.quantity)),\n 0,\n );\n }, [cartLines, lineUnitPrices]);\n\n // Over the queries that run only (proved rules): a query that never runs stays pending and idle,\n // so counting it left isSuccess false for good with no spinner.\n const isLoading = pricingLoadingFrom(\n priceQueries.map((q) => q.isLoading),\n runs,\n 0,\n );\n const isSuccess = pricingSettledFrom(\n priceQueries.map((q) => q.isSuccess),\n runs,\n 0,\n );\n const isError = priceQueries.some((q) => q.isError);\n\n return {\n prices,\n linePrices,\n getUnitPrice,\n getItemTotal,\n getLineUnitPrice,\n getLineTotal,\n subtotal,\n isLoading,\n isSuccess,\n isError,\n };\n}\n","import { minutes, toMillis } from \"@simpleapps-com/augur-utils\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { useCallback } from \"react\";\nimport type { QueryKey } from \"@tanstack/react-query\";\nimport type { Millis } from \"../duration\";\n\ninterface UsePaginationPrefetchOptions {\n /** Query key for the paginated data */\n queryKey: QueryKey;\n /** Function to fetch a page of data */\n queryFn: (offset: number) => Promise<unknown>;\n /** Number of items per page */\n pageSize: number;\n /** Custom query key builder. Receives the base key and offset, returns the full key. Default: [...queryKey, offset]. */\n queryKeyFn?: (baseKey: QueryKey, offset: number) => QueryKey;\n /** Stale time (defaults to 10 minutes) */\n staleTime?: Millis;\n /** GC time (defaults to 30 minutes) */\n gcTime?: Millis;\n enabled?: boolean;\n}\n\n/**\n * Prefetch adjacent pages on hover for instant pagination.\n * Accepts a generic queryFn so it works with any paginated resource.\n */\nexport const usePaginationPrefetch = ({\n queryKey,\n queryFn,\n pageSize,\n queryKeyFn,\n staleTime = toMillis(minutes(10)),\n gcTime = toMillis(minutes(30)),\n enabled = true,\n}: UsePaginationPrefetchOptions) => {\n const queryClient = useQueryClient();\n\n const prefetchPage = useCallback(\n async (page: number) => {\n if (!enabled) return;\n\n const offset = (page - 1) * pageSize;\n\n // prefetchQuery never rejects: query-core swallows fetch errors, and the\n // real query surfaces them when the page is actually opened.\n await queryClient.prefetchQuery({\n queryKey: queryKeyFn ? queryKeyFn(queryKey, offset) : [...queryKey, offset],\n queryFn: () => queryFn(offset),\n staleTime,\n gcTime,\n });\n },\n [queryKey, queryFn, pageSize, queryKeyFn, staleTime, gcTime, queryClient, enabled],\n );\n\n const handlePaginationHover = useCallback(\n (page: number) => {\n const timeoutId = setTimeout(() => prefetchPage(page), 150);\n return () => clearTimeout(timeoutId);\n },\n [prefetchPage],\n );\n\n return {\n prefetchPage,\n handlePaginationHover,\n };\n};\n","import { hours, toMillis } from \"@simpleapps-com/augur-utils\";\nimport { useState, useEffect, useMemo } from \"react\";\nimport { shouldPersistOf } from \"../rules\";\nimport type { PersistenceConfig } from \"../types\";\nimport { createPersister } from \"./create-persister\";\nimport { useStorageMonitor } from \"./use-storage-monitor\";\n\n/**\n * Version of the persisted query-data format, prefixed to every buster.\n * Bump it when the shape the proxies resolve to changes, so caches written by\n * older package versions are discarded without each site bumping its own buster.\n * \"augur-2\": the direct-SDK options proxy unwraps BaseResponse (2.5.0).\n */\nexport const PERSISTED_DATA_FORMAT = \"augur-2\";\n\n/**\n * Returns a fully configured `persistOptions` object for use with\n * `PersistQueryClientProvider` from `@tanstack/react-query-persist-client`.\n *\n * Handles:\n * - SSR-safe persister creation (no-op on server)\n * - Map → Record serialization for localStorage compatibility\n * - Selective persistence (only successful queries matching persistableKeys)\n * - Per-key-prefix LRU eviction (via `limits`)\n * - Throttled writes to localStorage\n * - Hydration safety (maxAge: 0 until client mount)\n * - Storage monitoring with automatic eviction when over threshold\n * - Dev mode auto-buster (invalidates cache on each restart)\n *\n * @example\n * ```tsx\n * import { useAugurPersistence } from \"@simpleapps-com/augur-hooks\";\n *\n * function Providers({ children }) {\n * const [queryClient] = useState(() => new QueryClient({ ... }));\n * const persistOptions = useAugurPersistence({\n * key: \"my-site-cache\",\n * buster: \"1.0.0\",\n * persistableKeys: [\"price\", \"categories\", \"invMast\"],\n * limits: { invMast: 100 },\n * });\n *\n * return (\n * <PersistQueryClientProvider client={queryClient} persistOptions={persistOptions}>\n * <augur.Provider api={api} auth={auth}>\n * {children}\n * </augur.Provider>\n * </PersistQueryClientProvider>\n * );\n * }\n * ```\n */\nexport function useAugurPersistence(config: PersistenceConfig) {\n const [persister] = useState(() => createPersister(config));\n const [isMounted, setIsMounted] = useState(false);\n\n useEffect(() => {\n setIsMounted(true);\n }, []);\n\n useStorageMonitor(config);\n\n const isDev = typeof process !== \"undefined\" && process.env?.[\"NODE_ENV\"] === \"development\";\n\n const { persistableKeys } = config;\n\n const dehydrateOptions = useMemo(\n () => ({\n shouldDehydrateQuery: (query: {\n queryKey: readonly unknown[];\n state: { status: string };\n }) => {\n const key = query.queryKey;\n const hasHead = Array.isArray(key) && key.length > 0;\n return shouldPersistOf(\n hasHead,\n query.state.status === \"success\",\n hasHead && persistableKeys.includes(key[0] as string),\n );\n },\n }),\n [persistableKeys],\n );\n\n return {\n persister,\n maxAge: isMounted ? (config.maxAge ?? toMillis(hours(24))) : 0,\n buster: isDev ? String(Date.now()) : `${PERSISTED_DATA_FORMAT}:${config.buster ?? \"\"}`,\n dehydrateOptions,\n };\n}\n","import { seconds, toMillis } from \"@simpleapps-com/augur-utils\";\nimport type { Persister, PersistedClient } from \"@tanstack/react-query-persist-client\";\nimport type { PersistenceConfig } from \"../types\";\nimport { serialize, deserialize } from \"./serializer\";\nimport { applyLimits } from \"./apply-limits\";\n\n/** No-op persister for SSR environments where localStorage is unavailable. */\nconst noopPersister: Persister = {\n persistClient: async () => {},\n restoreClient: async () => undefined,\n removeClient: async () => {},\n};\n\n/**\n * Creates an SSR-safe localStorage persister with throttled writes and LRU limiting.\n *\n * On the server (typeof window === \"undefined\"), returns a no-op persister.\n * On the client, writes are throttled to avoid performance degradation.\n */\nexport function createPersister(config: PersistenceConfig): Persister {\n if (typeof window === \"undefined\") return noopPersister;\n\n const throttleMs = config.throttleMs ?? toMillis(seconds(1));\n const limits = config.limits ?? {};\n let timer: ReturnType<typeof setTimeout> | undefined;\n // The latest client handed to persistClient. Only the timer reads it, and persistClient\n // sets it before it starts the timer, so it is always assigned when read.\n let pending!: PersistedClient;\n\n function write(client: PersistedClient) {\n try {\n const limited = applyLimits(client, limits);\n window.localStorage.setItem(config.key, serialize(limited));\n } catch {\n /* quota exceeded — silently skip */\n }\n }\n\n return {\n persistClient(client: PersistedClient) {\n pending = client;\n if (!timer) {\n timer = setTimeout(() => {\n timer = undefined;\n write(pending);\n }, throttleMs);\n }\n },\n\n restoreClient() {\n try {\n const raw = window.localStorage.getItem(config.key);\n if (!raw) return undefined;\n return deserialize(raw);\n } catch {\n return undefined;\n }\n },\n\n removeClient() {\n window.localStorage.removeItem(config.key);\n },\n };\n}\n","import type { PersistedClient } from \"@tanstack/react-query-persist-client\";\n\n/**\n * Serializes a PersistedClient to a JSON string.\n * Converts Map instances to plain objects for localStorage compatibility.\n */\nexport function serialize(data: PersistedClient): string {\n return JSON.stringify(data, (_key, value) => {\n if (value instanceof Map) return Object.fromEntries(value);\n return value;\n });\n}\n\n/**\n * Deserializes a JSON string back to a PersistedClient.\n */\nexport function deserialize(data: string): PersistedClient {\n return JSON.parse(data) as PersistedClient;\n}\n","import type { PersistedClient } from \"@tanstack/react-query-persist-client\";\n\ninterface QueryEntry {\n queryKey: readonly unknown[];\n queryHash: string;\n state: { dataUpdatedAt?: number };\n}\n\n/**\n * Applies per-key-prefix LRU limits to the queries in a PersistedClient.\n * For each prefix in `limits`, keeps only the N most-recently-updated queries.\n * Returns a shallow copy with trimmed queries; does not mutate the input.\n */\nexport function applyLimits(\n data: PersistedClient,\n limits: Record<string, number>,\n): PersistedClient {\n const queries = data.clientState?.queries;\n if (!queries || Object.keys(limits).length === 0) return data;\n\n const entries = queries as unknown as QueryEntry[];\n const unlimited: QueryEntry[] = [];\n const groups = new Map<string, QueryEntry[]>();\n\n for (const q of entries) {\n const prefix = Array.isArray(q.queryKey) ? q.queryKey[0] : undefined;\n if (typeof prefix === \"string\" && prefix in limits) {\n const group = groups.get(prefix) ?? [];\n group.push(q);\n groups.set(prefix, group);\n } else {\n unlimited.push(q);\n }\n }\n\n const kept: QueryEntry[] = [];\n for (const [prefix, group] of groups) {\n const limit = limits[prefix]!;\n const sorted = [...group].sort(\n (a, b) => (b.state.dataUpdatedAt ?? 0) - (a.state.dataUpdatedAt ?? 0),\n );\n kept.push(...sorted.slice(0, limit));\n }\n\n return {\n ...data,\n clientState: {\n ...data.clientState,\n queries: [...unlimited, ...kept] as unknown as typeof queries,\n },\n };\n}\n","import { minutes, toMillis } from \"@simpleapps-com/augur-utils\";\nimport { useEffect } from \"react\";\nimport { useLatest } from \"../hooks/use-latest\";\nimport type { PersistenceConfig } from \"../types\";\n\nconst CHECK_INTERVAL = toMillis(minutes(5));\n\n/**\n * Monitors total localStorage size and evicts limited query families\n * when the threshold is exceeded.\n *\n * Eviction strategy: remove queries whose key prefix appears in `limits`,\n * starting with the largest family. If parsing fails, clears the entire\n * persistence key as a fallback.\n */\nexport function useStorageMonitor(config: PersistenceConfig): void {\n const { key, limits = {}, maxStorageMB = 3 } = config;\n // A new array each render: the effect restarts when the number of limited families\n // changes, and takes the keys as of that render.\n const limitKeysRef = useLatest(Object.keys(limits));\n const limitCount = limitKeysRef.current.length;\n\n useEffect(() => {\n const limitKeys = limitKeysRef.current;\n if (typeof window === \"undefined\" || limitKeys.length === 0) return;\n\n function evict() {\n const storage = window.localStorage;\n let totalSize = 0;\n\n for (const k of Object.keys(storage)) {\n const v = storage.getItem(k);\n if (v) totalSize += k.length + v.length;\n }\n\n // UTF-16: each char = 2 bytes\n const usedMB = (totalSize * 2) / 1024 / 1024;\n if (usedMB <= maxStorageMB) return;\n\n try {\n const raw = storage.getItem(key);\n if (!raw) return;\n const parsed = JSON.parse(raw);\n if (!parsed.clientState?.queries) return;\n\n // Remove all queries whose prefix is in limits\n parsed.clientState.queries = parsed.clientState.queries.filter(\n (q: { queryKey?: unknown[] }) => {\n if (!Array.isArray(q.queryKey)) return true;\n const prefix = q.queryKey[0];\n return typeof prefix !== \"string\" || !limitKeys.includes(prefix);\n },\n );\n\n storage.setItem(key, JSON.stringify(parsed));\n } catch {\n // Corrupted data — clear entirely\n storage.removeItem(key);\n }\n }\n\n evict();\n const id = setInterval(evict, CHECK_INTERVAL);\n return () => clearInterval(id);\n }, [key, maxStorageMB, limitCount, limitKeysRef]);\n}\n","import { clearedBy } from \"@simpleapps-com/augur-core\";\nimport type { Mutation, MutationCacheConfig, QueryClient } from \"@tanstack/react-query\";\nimport { keyPathFrom, leadingTextsFrom } from \"./rules\";\n\n/**\n * A React Query key's method path: its leading text segments, joined by \".\" (augur-core keys a\n * query `[...path, ...args]` and a mutation `path`). How many lead is the proved leadingTextsFrom;\n * the join is the proved keyPathFrom (model KeyPathFrom), which reads only those first `n`, all text.\n */\nexport function keyPathOf(key: readonly unknown[] | undefined): string {\n const segments = key ?? [];\n const n = leadingTextsFrom(\n segments.map((s) => typeof s === \"string\"),\n 0,\n );\n return keyPathFrom(segments as string[], n);\n}\n\n/**\n * After the user's own write succeeds, clears the browser's cached reads that share a user\n * namespace with it (augur-core `clearedBy`, atlas#102): a wishlist write refetches the\n * wishlists and their lines; a favorites write leaves the wishlists alone; a catalogue write\n * clears nothing. User data is never cached on the server, so this is the only copy to clear.\n */\nexport function clearUserReadsOnWrite(\n queryClient: QueryClient,\n mutationKey: readonly unknown[] | undefined,\n): Promise<void> {\n const writePath = keyPathOf(mutationKey);\n return queryClient.invalidateQueries({\n predicate: (query) => clearedBy(writePath, keyPathOf(query.queryKey)),\n });\n}\n\n/**\n * The `MutationCache` config a site gives its browser QueryClient so the user's own writes clear\n * their cached reads. Works for mutations keyed by their SDK method path (augur-core's options\n * proxy keys them so) and reads keyed by it.\n *\n * @example\n * ```ts\n * const queryClient: QueryClient = new QueryClient({\n * mutationCache: new MutationCache(userWriteClearing(() => queryClient)),\n * });\n * ```\n */\nexport function userWriteClearing(getQueryClient: () => QueryClient): MutationCacheConfig {\n return {\n onSuccess: (_data, _variables, _context, mutation: Mutation<unknown, unknown, unknown>) =>\n clearUserReadsOnWrite(getQueryClient(), mutation.options.mutationKey),\n };\n}\n"]}
package/dist/index.js CHANGED
@@ -43,7 +43,7 @@ import {
43
43
  useSetCartHdrUid,
44
44
  useSetCartLines,
45
45
  zeroLabelShown
46
- } from "./chunk-V3VBNWLM.js";
46
+ } from "./chunk-2VK2LDMV.js";
47
47
 
48
48
  // src/provider.tsx
49
49
  import { createContext, useContext, useMemo } from "react";
@@ -659,7 +659,7 @@ function useCartInitialization(session, callbacks) {
659
659
 
660
660
  // src/hooks/use-cart-pricing.ts
661
661
  import { useMemo as useMemo4 } from "react";
662
- import { useQueries } from "@tanstack/react-query";
662
+ import { queryOptions, skipToken, useQueries } from "@tanstack/react-query";
663
663
  import {
664
664
  cleanMoney as cleanMoney2,
665
665
  derivePrice,
@@ -667,7 +667,8 @@ import {
667
667
  priceQueryRuns,
668
668
  priceQueryUnit,
669
669
  pricingLoadingFrom,
670
- pricingSettledFrom
670
+ pricingSettledFrom,
671
+ resolveAddressId
671
672
  } from "@simpleapps-com/augur-utils";
672
673
  function derivedOrRefused(priceData, quantity) {
673
674
  try {
@@ -686,38 +687,41 @@ function deriveLineUnitPrice(priceData, quantity) {
686
687
  function lineTotal(unitPrice, quantity) {
687
688
  return Number.isFinite(quantity) ? cleanMoney2(unitPrice * quantity) : 0;
688
689
  }
690
+ function keyedPriceQuery(itemId, customerId, quantity, unitOfMeasure, enabled, priceFn) {
691
+ return queryOptions({
692
+ queryKey: ["price", itemId?.toUpperCase() || "", customerId, quantity, unitOfMeasure ?? ""],
693
+ queryFn: priceFn && customerId !== null ? () => priceFn(itemId, customerId, quantity, unitOfMeasure) : skipToken,
694
+ refetchOnReconnect: true,
695
+ refetchOnWindowFocus: false,
696
+ meta: { persist: true },
697
+ enabled
698
+ });
699
+ }
689
700
  function useCartPricing(options = {}) {
690
701
  const proxy = useAugurOptions();
691
702
  const auth = useAugurAuth();
692
703
  const site = useAugurSite();
693
704
  const cartLines = useCartLines();
694
- const customerId = options.customerId ?? auth?.customerId ?? site?.defaults?.customerId;
705
+ const customerId = resolveAddressId(
706
+ options.customerId,
707
+ auth?.customerId,
708
+ site?.defaults?.customerId
709
+ );
695
710
  const priceFn = options.queryFn;
696
- const runs = cartLines.map((line) => priceQueryRuns(!!customerId, !!line.itemId, line.quantity));
711
+ const runs = cartLines.map(
712
+ (line) => priceQueryRuns(customerId !== null, !!line.itemId, line.quantity)
713
+ );
697
714
  const priceQueries = useQueries({
698
715
  queries: cartLines.map((line, index) => {
699
716
  const quantity = line.quantity ?? 0;
700
717
  const enabled = runs[index] === true;
701
718
  const unitOfMeasure = priceQueryUnit(line.unitOfMeasure) ?? void 0;
702
- if (priceFn) {
703
- return {
704
- queryKey: [
705
- "price",
706
- line.itemId?.toUpperCase() || "",
707
- customerId,
708
- quantity,
709
- unitOfMeasure ?? ""
710
- ],
711
- queryFn: () => priceFn(line.itemId, customerId, quantity, unitOfMeasure),
712
- refetchOnReconnect: true,
713
- refetchOnWindowFocus: false,
714
- meta: { persist: true },
715
- enabled
716
- };
719
+ if (priceFn || customerId === null) {
720
+ return keyedPriceQuery(line.itemId, customerId, quantity, unitOfMeasure, enabled, priceFn);
717
721
  }
718
722
  const proxyOpts = proxy.pricing.priceEngine.list({
719
723
  itemId: line.itemId?.toUpperCase() || "",
720
- customerId: Number(customerId),
724
+ customerId,
721
725
  quantity,
722
726
  unitOfMeasure
723
727
  });