Documentation menu

Documentation / Commerce engine / storefront

Storefront

Package
@wabbit/tome-storefront
Version
v0.6.1
npm install @wabbit/tome-storefront
First install from our registry?
  1. Get a registry token from your credentials page. You need a purchase that includes this package, or a Craft Library membership.

  2. Add the registry and your token to the .npmrc at the root of your project, with your token in place of YOUR_TOKEN:

    @wabbit:registry=https://npm.wabbit.com/
    //npm.wabbit.com/:_authToken=YOUR_TOKEN
Commerce enginePreview

Tome storefront layer — a cookie-token shopping cart (guest and member, merged at sign-in, swept on a TTL), a single store-facts global, a public non-leaky stock-availability projection, a product listing that joins catalog, prices and availability, and cookie-aware Next.js server actions. Money stays in economy, stock in fulfillment, product nouns in catalog.

Overview

The neutral layer that turns Tome's commerce primitives into a working shop for physical goods. It owns the shopper's cart, one store-facts source, a public derived-availability read, the browse listing, the checkout orchestration, and the order confirmation and lookup surfaces. It does not own money, stock or product data: money stays in @wabbit/tome-economy, stock in @wabbit/tome-fulfillment, product nouns in @wabbit/tome-catalog.

It ships the storefront-carts collection with an opaque-cookie token, the storefront-settings global, the guest-to-member cart merge, the public availability projection and endpoint, the product listing, multi-line checkout through economy's cart action (guest and member), stock reservation with a replay-safe trail, after-payment processing (address, pending shipment, confirmation and staff email, staff tasks), signed order links, an email-only order lookup, four jobs and the cookie-aware Next.js wrappers. Back-in-stock alerts (the storefront-restock-requests collection, requestRestockAlert and the storefront-restock-notify job) are described under Restock alerts below. The blocks live in @wabbit/tome-blocks-storefront-pack.

Peer dependencies

PeerRangeOptional?
@wabbit/tome-core>=1.24.0 <2.0.0no — access helpers, the layer registry, capabilities, the GDPR registry, the jobs adapters, the notifier, member resolution, the signed token and the shared unstable_cache loader.
@wabbit/tome-catalog>=1.5.0 <2.0.0no — products and variants the cart and listing read (turn variants on with createCatalogLayer({ variants: true })).
@wabbit/tome-economy>=0.18.0 <1.0.0no — prices, the cart checkout action, the order buses and the pending-order sweeper.
@wabbit/tome-fulfillment>=0.2.0 <1.0.0no — stock reserve and release, the availability read, addresses and shipments, the flat-rate shipping and tax seams.
@wabbit/tome-local>=0.2.0 <1.0.0yes — when installed, the dispatch line falls back to the business profile's timezone if the store settings set none.
payload>=3.67.0no — the collection, global, endpoint and job task are Payload config.
next>=15.0.0yes — @wabbit/tome-storefront/next reads next/headers, and the settings save hook revalidates through next/cache.

server-only is a runtime dependency, imported by @wabbit/tome-storefront/server alone.

Module surface

EntrySafe in a client bundleWhat it carries
@wabbit/tome-storefrontno (Payload config)createStorefrontLayer, the carts collection and settings global factories, the job handlers (cartSweepHandler, reconcilePaidHandler, pendingSweepHandler, restockNotifyHandler), the restock requests collection factory and its GDPR registration, the bus handlers, setStorefrontPayload, config helpers, constants and every public type
@wabbit/tome-storefront/serverno (server-only)the cart operations (getCart, addToCart, updateCartLine, removeCartLine, setShipCountry, clearCart, getPricedCart), checkoutCart, processPaidStorefrontOrder, getOrderViewBySession, getOrderViewByToken, getStorefrontOrderView, requestOrderLookup, ensureStorefrontGuestMember, the reservation helpers, requestRestockAlert, unsubscribeRestock, confirmRestock, notifyRestocked, getStorefrontAvailability, listStorefrontProducts, addToCartBySlug, storefrontListingSource, storefrontAvailabilitySource, storefrontFactsSource, getStoreFacts, getStorefrontSettings, the cart-cookie helpers
@wabbit/tome-storefront/nextno (reads next/headers)createStorefrontActions and createStorefrontRouteHandlers (cart, availability, checkout, lookup, order, restock, restockConfirm, restockUnsubscribe), the cookie-aware wrappers over the server API

Server/client posture: nothing here renders UI, so no entry is imported by a client component. Code that runs inside Payload (hooks, jobs, the CLI) imports the file it needs, because the server-only guard throws outside a React Server Components build.

Setting up

import { createStorefrontLayer } from '@wabbit/tome-storefront'
import { createStripeAdapter } from '@wabbit/tome-economy'

const storefront = createStorefrontLayer({
  adapter: () => createStripeAdapter({ secretKey: process.env.STRIPE_SECRET_KEY! }),
  publicBaseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,
  tokenSecret: process.env.STOREFRONT_TOKEN_SECRET!, // must differ from PAYLOAD_SECRET
})

export default buildConfig({
  // ...
  plugins: [storefront.plugin], // or spread storefront.collections / globals / endpoints, not both
})

adapter, publicBaseUrl and tokenSecret are required. The adapter must declare supportsCartShipping (economy's Stripe adapter does). Cart defaults are 50 lines, quantity 99 and a 30-day (guest) or 90-day (member) TTL; the cart cookie is tome_cart. jobs: false registers no task, and the consumer runs the jobs itself; layer.jobEndpoints carries all four as CRON_SECRET-guarded endpoints for an external scheduler (the plugin does not mount them).

On the economy webhook route, pass cancelOnExpiry: ['storefront-cart'] so an expired hosted session cancels its order and releases its stock. The plugin captures the Payload instance in onInit for the order handlers; if you spread the arrays instead, pass getPayload or call setStorefrontPayload(payload) in your own onInit. The layer reserves the storefront- collection prefix.

Behavior to know

  • The cart holds identities, never prices: a line is (product, variantSku, quantity), and every display re-reads the active one-time price.
  • The browser holds only a random token in an httpOnly, SameSite=Lax cookie (Secure in production); the row stores its SHA-256 hash. Carts are admin-only over REST and GraphQL and are registered with the GDPR registry.
  • Availability is a public, non-leaky projection (in-stock, low with the remaining count at or under the threshold, out, untracked). It never exposes onHand or reserved.
  • storefront-settings is the single source for currency, shipping rates, the free-shipping threshold, the minimum order, dispatch and returns copy. The storefront:edit-settings capability is granted to admin and editor.

Checkout and orders

  • checkoutCart(ctx, { email?, shipCountry }) re-prices the cart, applies the store rules (minimum order, served destinations, the free-shipping threshold on the pre-discount subtotal, the tax seam), resolves the buyer and calls economy's createCartCheckoutAction with line identities only. It returns redirect, blocked (with reasons) or out-of-stock (with SKUs). The cart stays active until payment.
  • Guests check out against one placeholder member (guest.customerId, else storefront-settings.system.guestCustomerId, else ensureStorefrontGuestMember); their identity on the order is the email. A members collection that requires a user needs guest.customerId pointing at a member linked to a system user.
  • Stock is reserved when the hosted session is created (reserve:<orderId>:<sku>) and released on cancel or a full refund before shipping (release:<orderId>:<sku>), checked against the trail so a replay never over-releases. Commit happens at ship, in fulfillment.
  • After payment, processPaidStorefrontOrder writes the address and one pending shipment, checks the cart out, emails the buyer a signed one-year view link and staff a notice, and raises one "pack" task per staff recipient. It is idempotent, and storefront-reconcile-paid retries what the bus missed. An order paid after its reservation was released re-reserves; if stock is short, the shipment stays pending with a note and a high-priority staff task, and nothing is committed.
  • The signed view link opens <publicBaseUrl>/orders/view?token=… by default; set orders: { viewPath: '/themes/shelf/orders/view' } to send it to a themed page (a path on this site; anything else throws at config time). People see a short order reference (view.reference, from storefrontOrderReference: a numeric id as it is, otherwise the id's last eight characters as XXXX-XXXX) in the confirmation and lookup emails and on the confirmation block; the token, links and lookups always carry the real id, and the staff notice shows both.
  • /checkout/success reads getOrderViewBySession and never mutates the order. The view shows a masked email and the ship-to city and country, never the street or payment detail.
  • requestOrderLookup always answers the same line, emails links only for paid storefront orders of the last year, and is rate-limited per IP and per email (five an hour) with a honeypot field.
  • Email goes through payload.sendEmail when an adapter is configured and is logged otherwise; a send never throws.

Restock alerts

A sold-out item can offer "email me once when it is back". It is a one-time message the person asked for about one item, never a list: it names the product and variant, links to it, and carries a signed unsubscribe link.

  • The collection. storefront-restock-requests holds one row per (email, variantSku): email (lower-cased), user (set when signed in), product, variantSku (the product sku for a product without variants), status (waiting, notified, canceled, and the older cancelled, which is still accepted and still written for now), requiresConfirmation and confirmedAt (double opt-in), requestedAt, notifiedAt, consentText (the disclosure shown, stamped by the server) and tokenVersion (raise it to revoke that person's links). REST and GraphQL are staff-only for every operation; the public path is requestRestockAlert, which writes with overrideAccess. The GDPR registration matches user OR email, because a guest request has no user.
  • Asking. requestRestockAlert(payload, { email, productSlug | productId, variantSku?, honeypot?, clientKey?, user?, disclosure? }) always resolves to the same line, whether the address is new or already waiting, the item is real or invented, the honeypot (website) was filled or a limit was hit. It stores a request only for an item that cannot be bought right now, dedupes on (email, variantSku) (a second ask stores nothing), and is limited to ten asks per IP and five per address an hour. The route is POST /restock; the server action is actions.requestRestockAlert.
  • Double opt-in is off by default (storefront-settings.restock.doubleOptIn). Turned on, a new request is stored unconfirmed and a signed confirmation link (GET /restock/confirm?token=, good for seven days) is emailed; the notifier skips it until it is confirmed, and asking again re-sends the link. restock.enabled switches the whole feature; restock.waitingTtlDays (default 180) is how long a waiting request is kept.
  • Notifying. storefront-restock-notify runs every 15 minutes (jobs.restockCron). For each SKU with live waiting requests that is back in stock (tracked, at least one unit available) it emails the oldest requesters, at most min(available x 3, 200) per SKU, so a restock of two units emails six people, not the list. The cap counts what was already sent for that SKU in the last 24 hours, so the next run does not walk further down the list on the same two units. A request is marked notified before its email is sent. A request for a product that is gone or off sale is closed without a message.
  • Unsubscribing. GET /restock/unsubscribe?token= (good for a year) cancels the request and answers a small page with no personal data. A tampered, expired or revoked token changes nothing; a used link keeps answering "unsubscribed". Mount the three handlers (restock, restockConfirm, restockUnsubscribe) under /api/storefront/restock, /restock/confirm and /restock/unsubscribe, or set restock.linksBasePath to where you mounted them.
  • Config. restock: { productPath?: (slug) => string, linksBasePath? }; the product link in the email defaults to /products/<slug>, matching the listing source. The emails come from notify.templates.restockAvailable and restockConfirm.
  • Retention. The cart sweep deletes notified and cancelled requests 30 days after they changed state and waiting requests after restock.waitingTtlDays; its summary gains restockPruned when it removed any.

Listing, facets and injected sources

listStorefrontProducts(payload, query) browses active, cartable products joined with price and availability. Besides category, tag, attributes, q, sort, page and limit, the query takes:

  • ids: explicit products in the order given; every other filter is ignored.
  • edition: a value of the attribute named in storefront-settings.edition.attribute.
  • priceBand: a listing.priceBands label or its key (Under $40 or under-40). A band covers min up to, not including, max. An unknown key filters nothing.
  • availability: 'in-stock' hides sold-out products; the default is 'all'.
  • facets: true: adds facets to the result. There is one facet per filterable select, multi-select or text attribute, then price (when bands are set), then availability. Each option's count is taken over the filtered set with that facet's own selection removed, so a choice never zeroes its siblings; empty options stay listed with a count of 0.

Price bands, the availability filter, price sorts and facets run in memory over at most 500 products (STOREFRONT_LISTING_SORT_CAP). Above that, a price sort falls back to newest with sortDegraded: true, and a band, availability filter or facets request is skipped with filtersDegraded: true.

addToCartBySlug (server), actions.addToCart({ productSlug, ... }) and POST /cart with { productSlug } add by catalog slug; the add then runs exactly as an add by id.

Store settings (all optional, unchanged when empty): edition (attribute, label, current, next { name, date, line }), afterOrder.steps[] { label, line, icon }, facts.extra[] { label, text }, listing.priceBands[] { label, min, max }. The public ones come back from getStoreFacts as edition, afterOrder and extra, and only when set.

Product story fields. storefrontProductFields({ mediaCollection }) returns one story group (notes, questions, inUse, folds) for the site's catalog bridge to append to createProductCollection()'s fields. No plugin is involved.

Sources for catalog-pack. catalog-pack has no dependency on this package, so the site registers these once at boot, from @wabbit/tome-storefront/server:

const options = { getPayload, productHref: (slug) => `/shop/${slug}` }
registerCatalogListingSource(storefrontListingSource(options))
registerCatalogAvailabilitySource(storefrontAvailabilitySource(options))
const facts = storefrontFactsSource(options) // { get(): Promise<StorefrontStoreFacts> }

The listing source maps each product to a tile: lowest active price (fromPrice when variant prices differ), compareAtCents, the primary and second image, availability, edition, the first category with its zero-padded ordered-step number (per parent, by sortOrder then name) and a "Back in {next edition}" line for a sold-out product when the next edition has a date. A frame's keyed flag is read from a keyed checkbox on the upload or on the catalog-media row, when the site has one. Its categories() returns each category's number and live product count.

How search params reach a hydrated block. RenderBlocks({ context }) and RenderBlock({ context }) forward an opaque context to every renderer as BlockRenderProps.context; that is the one request-scoped channel. A page route that wants server-side filtered tiles reads its searchParams prop and adds it to the context it already passes (the starter's catch-all page passes publicContext today and does not read searchParams). Reading searchParams makes that route dynamic, so a statically rendered page should instead render the unfiltered first page and let the 'use client' filter island (never hydrated by the server) read the URL and re-request. The starter's proxy.ts sets only x-pathname, so a headers() route would need the proxy to stamp the query string as well. This package has no GET /products route; the island's re-request goes to a route the site mounts over the listing source.

Exports

Import path
@wabbit/tome-storefront
@wabbit/tome-storefront/server
@wabbit/tome-storefront/next

Changelog

0.6.xMinor

  • Update your code first: the commerce writers now store the American values.

    New rows hold canceled and canceling, so a site that compares to 'cancelled' or 'cancelling' must accept both spellings before it takes this release. This is the second of three steps toward American spelling in stored values.

    Canceled orders (cart and checkout failures, Stripe session expiry and the stale order sweep) store canceled. Entitlements canceling at period end store canceling, and the order overview's access status reports it.

    Restock requests store canceled, and a canceled shipment prefers canceled when the shipments collection offers it.

    Reads still accept both spellings, and rows that hold the old values are unchanged until a site runs its backfill. The old options stay until the third step.

    On a SQL adapter the enum already gained the new value in the accept-both release, so make sure that migration has run.

1 fix (0.6.1)
  • 0.6.1
    The availability rate limit now keys on the client address your proxy vouched for, so a caller can no longer dodge it by sending a made-up X-Forwarded-For header.

    The limiter used the leftmost x-forwarded-for entry, which the client controls. It now uses the rightmost non-empty entry (the one a reverse proxy appends), then x-real-ip, then a shared unknown key.

    This assumes one trusted proxy in front of the app; the same key also feeds the order lookup and restock alert limits.

0.5.xMinor

  • BREAKING: handleStorefrontOrderCancelled is now handleStorefrontOrderCanceled.

    The bus registration key ends in order-canceled, and the stale-order job summary fields are canceled and canceledOrderIds. Stored order statuses are unchanged.

  • BREAKING: these packages now require @wabbit/tome-economy 0.18.0 or later, because they use its renamed SubscriptionCanceledEvent, OrderCanceledEvent and subscription.canceled names.

    Update @wabbit/tome-economy in the same change as these packages.

  • Admin labels, field descriptions, demo content and messages now use American spellings.

1 fix (0.5.1)
  • 0.5.1
    Canceled statuses now accept both spellings.

    This is the first of three steps toward American spelling in stored values, and nothing that gets written changes yet.

    Entitlement access canceling, order, payout and shipment canceled, and restock request canceled join the existing cancelling and cancelled options. Every read, query and display treats the two spellings as one meaning: access checks, refund access, the order cancel event, the order overview, restock links and cleanup, the shipment close on refund, and the order confirmation view.

    Documents that hold the old value keep validating and behave as before.

    The admin shows both options, because Payload cannot hide one select option. The old one is labeled "Canceled (legacy spelling)".

    Writers still store the old values; a later release switches them and a backfill moves the stored data.

    If you read these statuses in your own code or queries, accept both spellings now. Postgres sites need a migration for the added enum values.

0.4.xMinor

  • Honors staff from LayerFactoryConfig: operations this layer left without an access rule go to the site's staff check.

    This layer passes a hand-built config to applyLayerFactoryConfig, so it now forwards staff explicitly. Without that, it would accept the option and silently drop it.

    Omitting staff changes nothing.

0.3.xMinor

  • Fixes from the Shelf storefront checkpoint: variant-free products add from a tile, a buyer who backs out of payment keeps their own pieces, and order links and numbers are configurable.
    • Fixes from Shelf Checkpoint B. A product without variants adds to the cart from a tile again: the cart accepts a product's own SKU while the product has no active variant (the rule the restock request already follows) and stores the line with no variant SKU, the same line an add by product makes, so pricing, the reservation and the order read it as before. The listing source's tile addSku is now null for a product without variants (the tile adds by product alone) and stays the single variant's SKU when there is exactly one; a product with several variants still links to choose.
    • Backing out of the payment page no longer locks the buyer's own pieces. The bag and the checkout step credit the stock a cart already holds through its own pending checkout back to that cart's lines (new getStorefrontAvailability(payload, skus, config, { credit }) option; public reads never pass it), so a buyer who returns from an abandoned hosted session sees their pieces for sale instead of "sold out" for 30 minutes. The next checkout releases that hold (trail-keyed, idempotent) before it reserves, so the same units are reserved once. The abandoned order stays pending for the sweep; its later cancel releases nothing, and if it is paid after all the existing expired-then-paid path re-reserves or raises a staff task. The reservation guard itself never credits anything. Economy is unchanged.
    • Order links and numbers people can use. New orders: { viewPath } config (default /orders/view; a site path, refused otherwise) sets the page the emailed order-view links open, so a themed shop can point them at its own page (Shelf: /themes/shelf/orders/view). StorefrontOrderView gains reference, a short stable form of the order id (storefrontOrderReference from ./server: a numeric id as it is, else the last eight characters as XXXX-XXXX), used in the confirmation email and subject, the staff notice (with the id beside it) and the lookup email (its links gain an optional reference). The token still carries the real id.
  • Adds the listing data the Shelf storefront needs: filters, facet counts, injected sources, add-by-slug, four optional settings groups and the product story fields.

    A second minor changeset on one package merges into one bump.

    • Listing filters. listStorefrontProducts takes ids (explicit products in order; every other filter ignored), edition (the value of the attribute named in storefront-settings.edition.attribute), priceBand (a listing.priceBands label or key; an unknown key filters nothing) and availability: 'in-stock' | 'all'. Items gain compareAtCents (read from the price row), priceVaries, remaining (only when low) and variantSkus.
    • Facets. facets: true adds facets to the result: one facet per filterable select, multi-select or text attribute, then price and availability (in-stock and all). Counts are taken over the filtered set with each facet's own selection removed, and empty options stay listed with a count of 0. Price bands, the availability filter, price sorts and facets run over at most 500 products; above that a price sort falls back to newest with sortDegraded, and a band, availability filter or facets request is skipped with filtersDegraded: true.
    • Settings groups, all optional and empty by default. edition (attribute, label, current, next { name, date, line }), afterOrder.steps[], facts.extra[] and listing.priceBands[]. getStoreFacts returns edition, afterOrder and extra only when they are set, so an existing store reads exactly as before.
    • `storefrontProductFields()`. One namespaced story group (notes, questions, inUse, folds) for the site's catalog bridge to append to createProductCollection()'s fields. No plugin.
    • Injected sources from /server: storefrontListingSource, storefrontAvailabilitySource and storefrontFactsSource. They satisfy catalog-pack's listing and availability source types structurally, so neither package imports the other. The listing source maps products to tiles (price, compare-at, primary and second image, availability, edition, category with an ordered-step number, and a "Back in" line) and counts products per category.
    • Add by slug. addToCartBySlug (server), actions.addToCart({ productSlug }) and POST /cart with { productSlug }. An unknown slug is product-not-found; every other rule is the add by id.
    • Edition on bag lines. StorefrontPricedLine gains an optional editionLabel ("Batch 14"), present when storefront-settings.edition.attribute is set and the product has a value; a failed read leaves the line without it and never blocks pricing.

    Polish: "Featured" is the catalog's manual order. listStorefrontProducts({ sort: 'featured' }) now orders by the product's sortOrder (lowest first) and then by title, on both the database path and the in-memory path, instead of duplicating newest (-publishedAt). newest is unchanged, and so is a query with no sort.

    Needs the catalog's new Products.sortOrder field (see the catalog changeset); products with no value sort among the unplaced, so a store sets the order on the products it wants first.

  • Adds back-in-stock alerts: a storefront-restock-requests collection, requestRestockAlert, signed confirm and unsubscribe links, and the storefront-restock-notify job.

    Double opt-in is off by default.

    • Collection. storefront-restock-requests holds one row per (email, variantSku) with a waiting, notified or cancelled status, the lower-cased email, an optional user, a server-stamped requestedAt and consentText, and a tokenVersion that revokes one person's links. Every REST and GraphQL operation is staff-only; the public path is the action. A second waiting row for the same email and SKU is refused by the collection's beforeChange hook. The GDPR registration matches user OR email, because a guest request has no user.
    • Asking. requestRestockAlert (server and actions), and POST /restock on the route handlers. It always answers the same neutral line, whether the address is new or already waiting, the item exists or not, the honeypot (website) was filled or a limit was hit (ten asks per IP and five per address an hour). It stores a request only for an item that cannot be bought right now, and dedupes silently.
    • Double opt-in. storefront-settings.restock.doubleOptIn (default off). On, a request is stored unconfirmed, a signed confirmation link is emailed (GET /restock/confirm, seven days), and the notifier skips it until confirmed.
    • Notifying. storefront-restock-notify runs every 15 minutes (jobs.restockCron). For each SKU that is back in stock it emails the oldest waiting requesters, at most min(available x 3, 200) per SKU, counting what was already sent for that SKU in the last 24 hours, each with a signed unsubscribe link (GET /restock/unsubscribe, one year). A request is marked notified before its email is sent, so a failed write cannot cause a duplicate. The job is also in jobEndpoints and STOREFRONT_JOB_PATHS.restockNotify.
    • Unsubscribing. unsubscribeRestock and confirmRestock (server and actions), and the restockUnsubscribe and restockConfirm route handlers, which answer a small page with no personal data. Tampered, expired, wrong-purpose and revoked tokens change nothing.
    • Config. restock: { productPath?, linksBasePath? } sets the product link in the email (default /products/<slug>) and where the link handlers are mounted (default /api/storefront). notify.templates gains restockConfirm; restockAvailable was already there.
    • Retention. storefront-cart-sweep now also deletes notified and cancelled requests 30 days after they changed state and waiting requests after restock.waitingTtlDays, and reports restockPruned when it removed any.

    createStorefrontLayer now returns storefront-restock-requests in collections and a fourth task and cron endpoint; a site that lists the layer's collections or tasks by hand adds them.

1 fix (0.3.1)
  • 0.3.1

    README: subpath and file mentions are written package-qualified (for example @wabbit/tome-x/render) or as code text, so crawlers no longer resolve them as site URLs.

0.2.xMinor

  • BREAKING: Adds checkout, order processing and order lookup; now needs economy 0.15.0, core 1.24.0 and a commerce-family license.

    The peer ranges tighten to @wabbit/tome-economy >=0.15.0 and @wabbit/tome-core >=1.24.0, and wabbit.family moves from foundation to commerce (tier pro).

    Migration: upgrade economy to 0.15.0 and core to 1.24.0, add cancelOnExpiry: ['storefront-cart'] to your economy webhook handler, and make sure your license covers the commerce family.

    • Checkout. checkoutCart re-prices the cart, applies the store rules and the tax seam, resolves a member or guest buyer and calls economy's createCartCheckoutAction with line identities only. Results are redirect, blocked with reasons, or out-of-stock with the short SKUs.
    • Stock. Reservations are made when the hosted session is created and released on cancel, expiry or a full refund before shipping, checked against the stock trail so a replay never over-releases. An order paid after its reservation was released re-reserves; if stock is short the shipment stays pending with a staff task and nothing is committed.
    • After payment. processPaidStorefrontOrder writes the shipping address and one pending shipment, checks the cart out, sends the buyer confirmation (with a signed view link) and the staff notice, and raises staff pack tasks. Idempotent.
    • Order views and lookup. getOrderViewBySession (read-only, for the success page), getOrderViewByToken, getStorefrontOrderView, and requestOrderLookup, which always answers the same message, is rate-limited per IP and per email, and has a honeypot field.
    • Bus handlers and jobs. The layer registers order complete, cancel and refund handlers, adds the storefront-reconcile-paid and storefront-pending-sweep tasks, and returns all three jobs as cron endpoints in jobEndpoints. The plugin captures the Payload instance in onInit; getPayload and setStorefrontPayload cover setups without the plugin.
    • Next.js. The route handlers gain checkout, lookup and order; the server-action wrappers gain the same operations.
    • Fixes found by the money smoke. A wildcard rate row now stores shipsTo as ["*"] (a bare "*" was parsed as JSON by Payload and could never be saved); readers still accept a legacy bare "*". The rate table no longer sets minRows at field level, so the guest member can be recorded on a fresh database (the save hook still rejects an explicitly empty table). The checkout route answers 503 for a Stripe failure or a site's StripeKeyRefusedError, 429 for a Stripe rate limit, and 400 with shopper copy for VariantPriceRequiredError; Stripe error messages are never logged.
    • Fixes from the second money smoke. The rate-table check rejects an empty table only when the save changes it, so the guest-member seed passes on a fresh database (Payload fills rates: [] from an empty stored document). Stripe errors are recognized by type as well as name (stripe-node 22 keeps name as Error), so a rejected key now answers 503 and a rate limit 429. New StorefrontPaymentsUnavailableError (root and ./server): a site's adapter factory throws it when the paid rail is not connected, and the checkout route answers 503 payments-unavailable. The cached settings read now expires after five minutes as well as on tag revalidation, and a stored guest member id is checked against the members collection before an order uses it, so a seed or dropped database can no longer leave a stale id on an order.
    • Guest member self-heal on sites whose members require a user. New guest.resolveUserId(payload) config: when a stored guest member id is dangling and the layer has to find-or-create the placeholder at runtime, it asks the site for the system user, so the create no longer fails with ValidationError: User (checkout answered guest-disabled). The member lookup now matches the canonical slug, the alternate storefront-guest slug a members collection derives for a system-user row, and the system user itself, so the first-boot member is found instead of duplicated. Sites without the option behave as before.

0.1.xMinor

  • New package: @wabbit/tome-storefront, the cart, store-facts and availability layer for physical goods (increment S1, no money path).
    • `createStorefrontLayer`: returns the storefront-carts collection, the storefront-settings global, the public availability endpoint and the storefront-cart-sweep task, plus a plugin that appends all four. adapter, publicBaseUrl and tokenSecret are required; cart limits default to 50 lines, quantity 99 and a 30-day guest or 90-day member TTL. jobs: false registers no task.
    • `./server`: cart operations resolved from an opaque cookie token (stored as a SHA-256 hash), the guest-to-member merge at sign-in, a re-priced cart, the public availability projection (in-stock, low, out, untracked, never raw counts), the browse listing and the cached store facts.
    • `./next`: cookie-aware server actions and route handlers over the server API.

    Not in this release: checkout, order confirmation and lookup, restock alerts, and the storefront blocks.

Full changelog across all packages