npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

cart-handler

v1.0.0

Published

Framework-agnostic shopping cart state with subscriptions, totals, and optional persistence.

Readme

cart-handler

Framework-agnostic shopping cart state for TypeScript. One CartHandler instance holds line items, optional tax/shipping/discounts, and notifies subscribers when anything changes. Use it from React, Vue, Svelte, or plain DOM code.

Install

npm install cart-handler

ESM and CommonJS builds are published (exports in package.json). TypeScript types are included.

Quick start

import { CartHandler } from 'cart-handler';

const cart = new CartHandler();

const unsubscribe = cart.subscribe((lines) => {
  console.log('Cart updated:', lines);
});

cart.addItem({
  id: 'sku-1',
  title: 'Example product',
  unitPriceMinor: 1299, // $12.99 in cents
  quantity: 1,
});

console.log(cart.getTotals().grandTotalMinor);

unsubscribe();

Money (minor units)

All prices and totals use integer minor units (e.g. cents) via unitPriceMinor and the *Minor fields on CartTotals. That avoids floating-point rounding issues in checkout math.

Line identity

  • Each row has a stable key: id, or id::variantId when variantId is set.
  • By default, addItem merges quantity when id + variantId match an existing line. Override with duplicateLineStrategy in the constructor (merge + pricePolicy, or alwaysAppend).

Custom data (per line and per cart)

Per line: use metadata on addItem / CartLineInput — any JSON-serializable structure you need (engraving text, bundle ids, gift wrap). It is returned on each row from getState() / getSnapshot() and included when you serialize() / hydrate().

cart.addItem({
  id: 'sku-1',
  unitPriceMinor: 500,
  quantity: 1,
  metadata: { engraving: 'Hello', source: 'campaign-x' },
});

Per cart: use getExtras, setExtras, and patchExtras for cart-wide fields (affiliate code, experiment flags, checkout notes). These are included in serialize() / hydrate() and therefore in localStorage when persistence is attached. Optional constructor initialExtras seeds the bag.

cart.patchExtras({ affiliateId: 'partner-42' });
console.log(cart.getExtras());

cart.setExtras({}); // clear extras

clear() removes lines and coupon/discount defaults; it does not clear extras (so session-level flags can survive an empty cart). Call setExtras({}) if you want those gone too.

Checkout fields

Set these from your own tax/shipping engines or APIs:

  • setTaxMinor, setShippingMinor
  • setDiscount{ kind: 'none' }, { kind: 'fixed', amountMinor }, or { kind: 'percent', percent } (percent applies to the subtotal after line discounts)
  • setCouponCode / getCouponCode — stores a string; amount logic stays in your backend or setDiscount

Use getTotals() for merchandiseMinor, subtotalMinor, taxableBaseMinor, grandTotalMinor, and related breakdowns.

Persistence

Implement CartPersistenceAdapter (load / save / clear) or use createLocalStorageAdapter(key, storage?) with localStorage or sessionStorage.

Important: attachPersistence only binds the adapter; it does not write immediately, so existing storage is not overwritten before you call loadFromPersistence. Typical order:

import { CartHandler, createLocalStorageAdapter } from 'cart-handler';

const cart = new CartHandler();
const adapter = createLocalStorageAdapter('my-shop-cart');

cart.attachPersistence(adapter);
cart.loadFromPersistence(adapter); // restores lines + tax/shipping/discount/coupon if present

// Optional: push current in-memory state to storage without changing lines
cart.flushPersistence();

You can also use serialize(), hydrate(state), and loadFromPersistence for custom sync (e.g. IndexedDB or your API).

React (18+)

getSnapshot / getServerSnapshot pair with useSyncExternalStore so the cart and SSR stay consistent:

import { useSyncExternalStore } from 'react';
import { cart } from './cart';

export function useCartLines() {
  return useSyncExternalStore(
    (onStoreChange) => cart.subscribe(onStoreChange),
    () => cart.getSnapshot(),
    () => cart.getServerSnapshot(),
  );
}

Construct the server-side cart with the same initialLines you used when rendering HTML.

Vue (3)

Yes — Vue is fully supported. The library does not import Vue; you keep a shared CartHandler (module singleton or provide/inject) and wire subscribe into Vue reactivity.

Recommended pattern: shallowRef for the line array (the handler replaces the array when notifying) and computed for totals so you do not duplicate pricing logic.

// cart.ts — create once (e.g. singleton or create per shop session)
import { CartHandler } from 'cart-handler';

export const cart = new CartHandler();
<script setup lang="ts">
import { computed, onUnmounted, shallowRef } from 'vue';
import type { CartLine } from 'cart-handler';
import { cart } from './cart';

const lines = shallowRef<readonly CartLine[]>(cart.getState());

const unsubscribe = cart.subscribe((next) => {
  lines.value = next;
});

onUnmounted(() => {
  unsubscribe();
});

const totals = computed(() => cart.getTotals());

function addExample() {
  cart.addItem({
    id: 'sku-1',
    title: 'Example',
    unitPriceMinor: 999,
    quantity: 1,
  });
}
</script>

<template>
  <div>
    <p>Lines: {{ lines.length }}</p>
    <p>Grand total (minor units): {{ totals.grandTotalMinor }}</p>
    <button type="button" @click="addExample">Add item</button>
  </div>
</template>

For Nuxt or SSR, create the CartHandler per request (or per app on the client only) so server renders do not share one global cart between users.

API overview

| Area | Methods | |------|---------| | Subscriptions | subscribe, getState, getSnapshot, getServerSnapshot | | Lines | addItem, setLines, replaceItems, updateLine, removeLine, removeItem, clear | | Quantities | setQuantity, incrementQuantity, decrementQuantity | | Queries | hasLine, hasItem, getLine, getItem, lineCount, totalQuantity, isEmpty | | Totals | getLineTotalMinor, getSubtotalMinor, getCartDiscountMinor, getTotals | | Merge / batch | mergeIncoming, batch | | Persistence | attachPersistence, detachPersistence, flushPersistence, serialize, hydrate, loadFromPersistence | | Custom fields | Line: metadata on each item. Cart: getExtras, setExtras, patchExtras, initialExtras (constructor) |

Development

npm install
npm run check   # TypeScript
npm run build   # dist/ via tsup (runs automatically on publish via prepublishOnly)

License

ISC