@hand-off/storefront 0.0.0-stage → 0.1.1

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.
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@hand-off/storefront",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Build a shop on any stack against a Hand-Off store: catalogue, cart, shopper sign-in and checkout, typed.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/hand-off/hand-off-api.git",
9
+ "directory": "libs/storefront"
10
+ },
11
+ "homepage": "https://handoff.store/developers",
12
+ "keywords": [
13
+ "hand-off",
14
+ "storefront",
15
+ "headless",
16
+ "ecommerce",
17
+ "sdk"
18
+ ],
19
+ "main": "./index.cjs",
20
+ "module": "./index.mjs",
21
+ "types": "./types/entry/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./types/entry/index.d.ts",
25
+ "import": "./index.mjs",
26
+ "require": "./index.cjs"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "index.mjs",
32
+ "index.cjs",
33
+ "types",
34
+ "skill",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "sideEffects": false,
39
+ "engines": {
40
+ "node": ">=18"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "provenance": false
45
+ }
46
+ }
package/skill/SKILL.md ADDED
@@ -0,0 +1,207 @@
1
+ ---
2
+ name: build-hand-off-shop
3
+ description: Build or extend a shop's own website (Next.js, Astro, Remix, SvelteKit, plain Node, or another stack) on a Hand-Off store with the @hand-off/storefront library. Use when someone wants their Hand-Off products, collections, pages or blog on a site they host themselves, or asks for a custom or headless storefront for a Hand-Off store.
4
+ ---
5
+
6
+ # Build a shop on Hand-Off with `@hand-off/storefront`
7
+
8
+ Hand-Off keeps the store: products, stock, prices, orders, payments, shoppers. Your site shows
9
+ it. `@hand-off/storefront` is the typed client for that: it reads the store's public catalogue and
10
+ pages, and (as each part ships) keeps the visitor's cart, signs shoppers in and hands them to
11
+ Hand-Off's checkout. You never handle card details.
12
+
13
+ Reference: the package's own README
14
+ (`node_modules/@hand-off/storefront/README.md`) lists every method; its types are the source of
15
+ truth for every field.
16
+
17
+ ## What you need from the person
18
+
19
+ 1. **The shop's address**: the address shoppers visit, such as `https://acme.handoff.market` or the
20
+ store's own domain. In an organization with several stores it ends with the store's slug:
21
+ `https://acme.handoff.market/bakery`. Ask for it; never guess it from a store name.
22
+ 2. Their **stack**, if a project does not exist yet. Default to what is already in the folder.
23
+
24
+ Nothing else. The library needs no secret: never ask for a password, an email code, an API
25
+ token or card details. For browser code you also need the store's *publishable* storefront key
26
+ (`hopk_…`): public by design, safe in the site's JavaScript. The store's owner creates it and
27
+ lists the site's exact origin on it (and `http://localhost:3000` while developing).
28
+
29
+ ## Steps
30
+
31
+ 1. **Install**: `npm install @hand-off/storefront` (Node 18 or later, any bundler, TypeScript 4.7+ or plain JS).
32
+ 2. **Make one client module** and import it everywhere:
33
+
34
+ ```ts
35
+ // lib/shop.ts
36
+ import { createStorefront } from '@hand-off/storefront';
37
+ export const shop = createStorefront({ shop: process.env.HAND_OFF_SHOP_URL! });
38
+ ```
39
+
40
+ Put the address in configuration (`HAND_OFF_SHOP_URL`), not in components.
41
+ 3. **Check it answers** before building pages: `await shop.store.get()` gives the store's
42
+ `name`, `currency` and `language`. A `NOT_FOUND` means the address names no published store.
43
+ 4. **Build the pages from the catalogue**, on the server (see "Where it runs"):
44
+ - Home / list: `shop.products.list({ limit, cursor, collectionId, categoryId, search, sort, inStock, onSale })`
45
+ gives `{ items, nextCursor }`. Page with `nextCursor` (null on the last page).
46
+ - Product page: `shop.products.get({ slug })`: media, options, `variants` (each with `price`,
47
+ `stock`, and the `key` the cart takes), `descriptionHtml` (already sanitised by Hand-Off),
48
+ `seo`, `categories`.
49
+ - Collection page: `shop.collections.get(slug)` for its name and image, then
50
+ `shop.products.list({ collectionId: collection.id })`.
51
+ - Category navigation: `shop.categories.list()` (top-level first; `parentId` nests
52
+ subcategories), then `shop.products.list({ categoryId })`.
53
+ - Menus, pages, blog: `shop.menus.get()`, `shop.pages.list()`, `shop.pages.byPath('/about')`,
54
+ `shop.content.list('blog')`.
55
+ - Store facts for the header and footer: `shop.store.get()` (logo, branding colours and fonts,
56
+ contact, hours), `shop.store.policies()`.
57
+ 5. **Show money right**: every amount is an integer in minor units with its `currency`. Use
58
+ `formatMoney(amount, currency, store.language)`; never divide by 100 yourself (JPY has no
59
+ minor unit). `price` is what the shopper pays now; show `compareAtPrice` struck through when it
60
+ is set. `maxPrice` set means "from `price`".
61
+ 6. **Buying**:
62
+ - Where the store has token sessions on (a call answers rather than `NOT_FOUND`), keep the bag
63
+ on your site: `shop.cart.add({ productId, combinationKey: variant.key, quantity })`,
64
+ `cart.get()`, `cart.update(lineId, quantity)`, `cart.remove(lineId)`, with `onCartChange` to
65
+ redraw the bag. Shopper sign-in: `shop.shopper.start(phone)`, then
66
+ `shop.shopper.verify({ phone, code })` (`needsProfile` → `shopper.register`).
67
+ - **Pay on Hand-Off's checkout** (needs the store key; checkout links on for the store):
68
+ `const link = await shop.checkout.fromCart({ successUrl, cancelUrl })` (or
69
+ `checkout.create({ lines, successUrl })`), then send the shopper to `link.url`. Both
70
+ addresses must be absolute and on one of the key's allowed sites (`RETURN_URL_REFUSED`).
71
+ - **On the success page**, call `await shop.checkout.handleReturn(location.href)` (or the
72
+ request URL on a server). Show the order as paid only when it answers `paid: true`: the
73
+ `handoff_order` in the address is the shopper's word, the API's answer is the truth. It also
74
+ empties the visitor's cart.
75
+ - Where checkout links or token sessions are off (`UNAVAILABLE`, or `NOT_FOUND`), link each
76
+ product to its page on the shop (`product.url`) to buy there.
77
+ 7. **Handle errors** by `code` (below), give missing records a real 404, and run the site.
78
+
79
+ ## Where it runs
80
+
81
+ - **Server code works today**: Next.js server components and route handlers, Remix/React Router
82
+ loaders, SvelteKit `load`, Astro frontmatter, Nuxt server routes, plain Node, edge runtimes.
83
+ - **The browser** needs `publishableKey: 'hopk_…'` and the site's origin on that key's allowed
84
+ sites. Without a key a browser call fails with `NETWORK_ERROR` (no CORS); `ORIGIN_REFUSED` means
85
+ the site's origin is not on the key; `KEY_INVALID` (`reason`: `UNKNOWN`, `REVOKED`, `EXPIRED`,
86
+ `DISABLED`) means ask the owner for a working key. Server calls work with or without a key.
87
+ - Catalogue reads hold no visitor state, so one client can serve every request. Anything that
88
+ holds a visitor's cart or sign-in needs one client per visitor (pass that visitor's `session`);
89
+ never share one between visitors on a server.
90
+
91
+ ## Gotchas
92
+
93
+ - **Branch on `error.code`, never on `message`.** `NOT_FOUND` (missing, draft, unpublished or
94
+ hidden: the API never says which), `AUTH_REQUIRED` / `REGISTRATION_REQUIRED` /
95
+ `PENDING_APPROVAL` (a private store: its catalogue is for signed-in, approved shoppers only),
96
+ `RATE_LIMITED` (back off; `retryAfterMs`), `NETWORK_ERROR`, `INVALID_ARGUMENT` (refused before
97
+ sending), `INVALID_RESPONSE`.
98
+ - **A product is named by its slug in addresses**, by its id everywhere else. `products.get()`
99
+ takes either; a 24-hex-character string is read as an id.
100
+ - **Slugs change.** Use `product.slug` from the latest read for links; a `pages.byPath()` answer
101
+ of `{ kind: 'redirect', toPath }` means the address moved: redirect there.
102
+ - **Images**: use `image.url` with `image.srcset` (empty when there are no other sizes) and the
103
+ `width`/`height` to reserve space; `alt` is the store's text.
104
+ - **Cache reads, briefly.** The API's public answers are cacheable for about a minute. Revalidate
105
+ every 60–300 seconds (Next.js `export const revalidate = 60`); never cache a visitor's cart.
106
+ - **Stock**: `stock.state` is `in_stock`, `out_of_stock` or `not_tracked` (always buyable);
107
+ `stock.quantity` is null when the store hides counts.
108
+ - **Never scrape the shop's HTML** or call routes under `/storefront/api/v1/page/` (those are for
109
+ the store's own sealed pages). If a route the library lacks is needed, `shop.transport.request()`
110
+ calls any `/storefront/api/v1/` route, but prefer a library method.
111
+ - **Never handle tokens yourself.** The library keeps the cart and sign-in tokens in its
112
+ `session` and renews them; no method returns one. One storefront per visitor on a server.
113
+ - **Private stores** answer catalogue reads with `AUTH_REQUIRED` (or `REGISTRATION_REQUIRED`,
114
+ `PENDING_APPROVAL`, `VERIFICATION_REQUIRED`). The API does not yet read a shopper's token on
115
+ catalogue routes, so signing in does not unlock a private catalogue from an outside site: tell
116
+ the person to keep the store public for a custom site, or show a sign-in notice.
117
+ - **Sign-in codes belong to the key's store.** Always start with `shop.shopper.start(phone)`; a code
118
+ from the shop's own sign-in page, or from another store, is refused by `shopper.verify`.
119
+ - **Discount codes**: one call is one attempt (never retried) and needs a signed-in shopper.
120
+ - **Don't re-implement checkout, payments, tax or shipping.** Hand-Off does them on its checkout.
121
+ - **Escape store text** in templates (framework defaults do). Only `descriptionHtml` and a
122
+ content entry's `contentHtml` are HTML, already sanitised.
123
+ - **Where tokens live.** `storageSession(localStorage, key)` is for a guest's cart token only. A
124
+ signed-in shopper's tokens reach their orders and addresses: keep them in `memorySession()` or
125
+ an HttpOnly cookie set by the site's own server, never in `localStorage`.
126
+ - **Mixing ESM and CommonJS builds** of the library in one program gives two `HandOffError`
127
+ classes; test `error.name === 'HandOffError'` if you must.
128
+
129
+ ## Example: Next.js (App Router)
130
+
131
+ ```tsx
132
+ // app/page.tsx — the product grid
133
+ import Link from 'next/link';
134
+ import { formatMoney } from '@hand-off/storefront';
135
+ import { shop } from '@/lib/shop';
136
+
137
+ export const revalidate = 60;
138
+
139
+ export default async function Home() {
140
+ const [store, { items }] = await Promise.all([shop.store.get(), shop.products.list({ limit: 24 })]);
141
+ return (
142
+ <main>
143
+ <h1>{store.name}</h1>
144
+ <ul>
145
+ {items.map((p) => (
146
+ <li key={p.id}>
147
+ <Link href={`/products/${p.slug}`}>
148
+ {p.image && <img src={p.image.url} srcSet={p.image.srcset || undefined} alt={p.image.alt} width={p.image.width ?? undefined} height={p.image.height ?? undefined} />}
149
+ {p.name} · {formatMoney(p.price, p.currency, store.language)}
150
+ </Link>
151
+ </li>
152
+ ))}
153
+ </ul>
154
+ </main>
155
+ );
156
+ }
157
+ ```
158
+
159
+ ```tsx
160
+ // app/products/[slug]/page.tsx — one product
161
+ import { notFound } from 'next/navigation';
162
+ import { formatMoney, HandOffError } from '@hand-off/storefront';
163
+ import { shop } from '@/lib/shop';
164
+
165
+ export const revalidate = 60;
166
+
167
+ export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
168
+ const { slug } = await params;
169
+ const product = await shop.products.get({ slug }).catch((error) => {
170
+ if (error instanceof HandOffError && error.code === 'NOT_FOUND') notFound();
171
+ throw error;
172
+ });
173
+ return (
174
+ <main>
175
+ <h1>{product.name}</h1>
176
+ <div dangerouslySetInnerHTML={{ __html: product.descriptionHtml ?? '' }} />
177
+ <ul>
178
+ {product.variants.map((v) => (
179
+ <li key={v.id}>{v.title}: {formatMoney(v.price, v.currency)} {v.stock.state === 'out_of_stock' && '(sold out)'}</li>
180
+ ))}
181
+ </ul>
182
+ <a href={product.url}>Buy</a>
183
+ </main>
184
+ );
185
+ }
186
+ ```
187
+
188
+ ## Example: all products, every page
189
+
190
+ ```ts
191
+ const all = [];
192
+ let cursor: string | undefined;
193
+ do {
194
+ const page = await shop.products.list({ limit: 50, cursor });
195
+ all.push(...page.items);
196
+ cursor = page.nextCursor ?? undefined;
197
+ } while (cursor);
198
+ ```
199
+
200
+ ## Done means
201
+
202
+ - Every page reads from the library (no hard-coded products, prices or copied images).
203
+ - Prices go through `formatMoney`; sold-out variants show as sold out.
204
+ - A missing product or page answers 404; a moved one redirects.
205
+ - The shop address is configuration; no secret is in the code.
206
+ - Buying sends the shopper to Hand-Off's checkout (a checkout link), and the success page trusts
207
+ only `checkout.handleReturn`'s `paid`.
@@ -0,0 +1,47 @@
1
+ import type { Cart } from '../types/api';
2
+ import type { DiscountResource } from './discount';
3
+ import { type Transport } from './transport';
4
+ export interface CartAddition {
5
+ productId: string;
6
+ /** The variant's `key`. Left out for a product without options. */
7
+ combinationKey?: string;
8
+ /** 1 when left out. */
9
+ quantity?: number;
10
+ selectedAddOns?: Array<{
11
+ addOnId: string;
12
+ selectedOptionId: string;
13
+ quantity: number;
14
+ }>;
15
+ personalizationText?: string;
16
+ }
17
+ export interface CartLineChange {
18
+ /** 0 removes the line. */
19
+ quantity: number;
20
+ /** Another variant of the same product. */
21
+ combinationKey?: string;
22
+ personalizationText?: string;
23
+ }
24
+ /**
25
+ * The visitor's own cart: lines and list prices. Discounts, shipping and totals show on the
26
+ * store's cart page, never here. Every method answers the cart as it now is.
27
+ */
28
+ /** `C`: the cart shape the transport's routes answer (the sealed page's `Cart` by default). */
29
+ export interface CartResource<C = Cart> {
30
+ get(): Promise<C>;
31
+ add(item: CartAddition): Promise<C>;
32
+ update(lineId: string, change: CartLineChange | number): Promise<C>;
33
+ remove(lineId: string): Promise<C>;
34
+ clear(): Promise<C>;
35
+ applyDiscount(code: string): Promise<C>;
36
+ removeDiscount(code: string): Promise<C>;
37
+ }
38
+ /**
39
+ * Order. The cart a listener is told about must be the newest one, so:
40
+ * - writes go to the API one after the other, in the order they were called (two sent at once
41
+ * could be answered in either order, and the older answer would be told last);
42
+ * - a read that overlapped a write gives its answer to its caller and tells no one: the write's
43
+ * own answer is the newer cart;
44
+ * - of two reads in flight together, the one asked last has the last word: when it has told its
45
+ * answer, the earlier read's answer, arriving late, tells no one.
46
+ */
47
+ export declare function cartResource<C = Cart>(transport: Transport, discount: DiscountResource<C>, changed: (cart: C) => void): CartResource<C>;
@@ -0,0 +1,7 @@
1
+ import type { Collection } from '../types/api';
2
+ import { type Transport } from './transport';
3
+ export interface CollectionsResource {
4
+ list(): Promise<Collection[]>;
5
+ get(idOrSlug: string): Promise<Collection>;
6
+ }
7
+ export declare function collectionsResource(transport: Transport): CollectionsResource;
@@ -0,0 +1,8 @@
1
+ import type { ContentItem, ContentList } from '../types/api';
2
+ import { type Transport } from './transport';
3
+ /** The store's own content collections (CMS): a blog, a team list, a menu of the day. */
4
+ export interface ContentResource {
5
+ list(collection: string): Promise<ContentList>;
6
+ get(collection: string, item: string): Promise<ContentItem>;
7
+ }
8
+ export declare function contentResource(transport: Transport): ContentResource;
@@ -0,0 +1,15 @@
1
+ import type { Cart } from '../types/api';
2
+ import { type Transport } from './transport';
3
+ export declare const DISCOUNT_CODE_MAX_LENGTH = 64;
4
+ /**
5
+ * Discount codes on the visitor's cart (signed-in, registered shoppers only; the API refuses
6
+ * anyone else with a code). One call is one attempt: a refusal is never sent again by this
7
+ * library, so a page cannot use it to try codes faster than the API's own limit.
8
+ */
9
+ export interface DiscountResource<C = Cart> {
10
+ /** The code as it will be sent; throws `INVALID_ARGUMENT` for one that cannot be. */
11
+ checked(code: unknown): string;
12
+ apply(code: string): Promise<C>;
13
+ remove(code: string): Promise<C>;
14
+ }
15
+ export declare function discountResource<C = Cart>(transport: Transport): DiscountResource<C>;
@@ -0,0 +1,34 @@
1
+ import type { ApiErrorCode } from '../types/api';
2
+ /**
3
+ * Codes this library adds to the API's own: nothing reached the API (`NETWORK_ERROR`), the answer
4
+ * was not the API's shape (`INVALID_RESPONSE`), or the call was refused before it was sent
5
+ * (`INVALID_ARGUMENT`, `NAVIGATION_REFUSED`).
6
+ */
7
+ export type ClientErrorCode = 'NETWORK_ERROR' | 'INVALID_RESPONSE' | 'INVALID_ARGUMENT' | 'NAVIGATION_REFUSED';
8
+ /** A string, so a code a newer API adds still arrives as itself. */
9
+ export type HandOffErrorCode = ApiErrorCode | ClientErrorCode | (string & {});
10
+ export interface HandOffErrorDetails {
11
+ /** The HTTP status, or 0 when no answer came. */
12
+ status?: number;
13
+ /** A more exact reason where the API has one (a form's own code). */
14
+ reason?: string;
15
+ /** Per-field error codes of a form submission. */
16
+ fields?: Record<string, string>;
17
+ retryAfterMs?: number;
18
+ /** A fresh form render token, to send the same answers again. */
19
+ formToken?: string;
20
+ }
21
+ /**
22
+ * Every failure of this library. Branch on `code`, never on `message`. An error never holds the
23
+ * request, its headers or the session: nothing of the visitor's token can be read from one.
24
+ */
25
+ export declare class HandOffError extends Error {
26
+ readonly code: HandOffErrorCode;
27
+ readonly status: number;
28
+ readonly reason?: string;
29
+ readonly fields?: Record<string, string>;
30
+ readonly retryAfterMs?: number;
31
+ readonly formToken?: string;
32
+ constructor(code: HandOffErrorCode, message: string, details?: HandOffErrorDetails);
33
+ }
34
+ export declare const invalidArgument: (message: string) => HandOffError;
@@ -0,0 +1,7 @@
1
+ import type { Menus } from '../types/api';
2
+ import type { Transport } from './transport';
3
+ export interface MenusResource {
4
+ /** The store's header and footer menus; each is null when the store has none of its own. */
5
+ get(): Promise<Menus>;
6
+ }
7
+ export declare function menusResource(transport: Transport): MenusResource;
@@ -0,0 +1,34 @@
1
+ import type { Product, ProductSummary, Variant } from '../types/api';
2
+ import { type Transport } from './transport';
3
+ export interface ProductListQuery {
4
+ limit?: number;
5
+ cursor?: string;
6
+ search?: string;
7
+ collectionId?: string;
8
+ categoryId?: string;
9
+ brandId?: string;
10
+ sort?: string;
11
+ inStock?: boolean;
12
+ onSale?: boolean;
13
+ }
14
+ export interface ProductList {
15
+ items: ProductSummary[];
16
+ /** Pass as `cursor` for the next page; null on the last. */
17
+ nextCursor: string | null;
18
+ }
19
+ /** A product by its id or its slug (the address part). A bare string is read as an id when it looks like one. */
20
+ export type ProductRef = string | {
21
+ id: string;
22
+ } | {
23
+ slug: string;
24
+ };
25
+ export interface ProductsResource {
26
+ list(query?: ProductListQuery): Promise<ProductList>;
27
+ get(ref: ProductRef): Promise<Product>;
28
+ /** The product's variants, each with its price, stock and the `key` the cart takes. */
29
+ variants(ref: ProductRef): Promise<Variant[]>;
30
+ related(productId: string, options?: {
31
+ limit?: number;
32
+ }): Promise<ProductSummary[]>;
33
+ }
34
+ export declare function productsResource(transport: Transport): ProductsResource;
@@ -0,0 +1,15 @@
1
+ import type { Hours, OrderingState, Policy, Store } from '../types/api';
2
+ import type { Transport } from './transport';
3
+ export interface StoreHours {
4
+ /** IANA name; every time below is in it. */
5
+ timezone: string;
6
+ hours: Hours[];
7
+ /** Whether the store takes orders right now, and when that changes. */
8
+ ordering: OrderingState;
9
+ fulfillment: Store['fulfillment'];
10
+ }
11
+ export interface StoreResource {
12
+ hours(): Promise<StoreHours>;
13
+ policies(): Promise<Policy[]>;
14
+ }
15
+ export declare function storeResource(transport: Transport): StoreResource;
@@ -0,0 +1,47 @@
1
+ import type { ApiPageInfo } from '../types/api';
2
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
3
+ export type QueryValue = string | number | boolean | null | undefined;
4
+ export interface RequestOptions {
5
+ query?: Record<string, QueryValue>;
6
+ /**
7
+ * False: send once, whatever the answer. The transport then does not send the call a second
8
+ * time after renewing an expired session (discount codes: one attempt is one attempt).
9
+ */
10
+ retry?: boolean;
11
+ /** False: send no session token with this call (outside-site transport: a refresh, a new cart token). */
12
+ auth?: boolean;
13
+ }
14
+ /** A successful answer: `data`, and `page.nextCursor` on a list. */
15
+ export interface TransportResult<T> {
16
+ data: T;
17
+ page?: ApiPageInfo;
18
+ }
19
+ /** What a transport holds for the visitor between calls. Where it is kept is the caller's choice. */
20
+ export interface SessionValue {
21
+ token: string;
22
+ /** ISO 8601. */
23
+ expiresAt: string;
24
+ /**
25
+ * What the token is, on the outside-site transport: a guest's `cart` token, or a signed-in
26
+ * `shopper`'s access token. Absent on a sealed page (its page token).
27
+ */
28
+ kind?: 'cart' | 'shopper';
29
+ /** A signed-in shopper's refresh token and when it expires (ISO 8601). */
30
+ refreshToken?: string;
31
+ refreshExpiresAt?: string;
32
+ }
33
+ export interface Session {
34
+ get(): SessionValue | null;
35
+ set(value: SessionValue | null): void;
36
+ }
37
+ /**
38
+ * How `core/` reaches the API. `path` is relative to the transport's base and names a resource
39
+ * (`products`, `cart/items/…`); the transport adds the host, the credentials and the session, and
40
+ * rejects with a `HandOffError` for every failure.
41
+ */
42
+ export interface Transport {
43
+ request<T>(method: HttpMethod, path: string, body?: unknown, options?: RequestOptions): Promise<TransportResult<T>>;
44
+ readonly session: Session;
45
+ }
46
+ /** One path part, safe to join: encoded, and never empty, `.` or `..` (which would climb out of the base). */
47
+ export declare function segment(value: unknown, what: string): string;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * `HandOff.format.money(1250)` → "$12.50": an amount in minor units (as every price in the API
3
+ * is), in the store's currency and language unless another currency is named.
4
+ */
5
+ export declare function moneyFormatter(language: string, storeCurrency: string): (amount: number, currency?: string) => string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The npm entry of `@hand-off/storefront`: build a shop on another stack against a Hand-Off store.
3
+ *
4
+ * const shop = createStorefront({ shop: 'https://acme.handoff.market' });
5
+ * const { items } = await shop.products.list({ limit: 12 });
6
+ *
7
+ * (`npm/README.md` is the package's page; `skill/SKILL.md` the coding agents' guide.)
8
+ *
9
+ * Built by `tools/build-package.js` (ESM, CommonJS and type declarations). It never includes the
10
+ * sealed page's runtime (`entry/block.ts`) or its custom elements.
11
+ */
12
+ export { createStorefront, formatMoney, EMPTY_CART } from '../sdk/storefront';
13
+ export type { ShopperResource, ShopperVerify, SignInResult } from '../sdk/shopper';
14
+ export { linesOfCart } from '../sdk/checkout';
15
+ export type { CheckoutResource, CheckoutReturn, CheckoutStart } from '../sdk/checkout';
16
+ export type { CartAddition, CartLineChange, CartResource } from '../core/cart';
17
+ export type { CategoriesResource, PagesResource, StoreInfoResource, Storefront, StorefrontOptions, VariantsResource } from '../sdk/storefront';
18
+ export { createKeyTransport, storefrontApiBase, PUBLISHABLE_KEY_HEADER } from '../transport/key';
19
+ export type { KeyFetch, KeyFetchAnswer, KeyFetchInit, KeyTransport, KeyTransportOptions } from '../transport/key';
20
+ export { memorySession, storageSession } from '../transport/session';
21
+ export type { StorageLike } from '../transport/session';
22
+ export { HandOffError } from '../core/errors';
23
+ export type { ClientErrorCode, HandOffErrorCode, HandOffErrorDetails } from '../core/errors';
24
+ export type { HttpMethod, QueryValue, RequestOptions, Session, SessionValue, Transport, TransportResult } from '../core/transport';
25
+ export type { CollectionsResource } from '../core/collections';
26
+ export type { ContentResource } from '../core/content';
27
+ export type { MenusResource } from '../core/menus';
28
+ export type { ProductList, ProductListQuery, ProductRef, ProductsResource } from '../core/products';
29
+ export type { StoreHours } from '../core/store';
30
+ export * from '../types/api';
@@ -0,0 +1,51 @@
1
+ import { type Transport } from '../core/transport';
2
+ import type { CheckoutLink, CheckoutLinkLine, CheckoutLinkState, SessionCart } from '../types/api';
3
+ /**
4
+ * CHECKOUT for outside sites (part 2A-2): Hand-Off takes the payment on its own checkout page.
5
+ * The site makes a one-time checkout link from lines (or from the visitor's cart), sends the
6
+ * shopper to its `url`, and gets them back on `successUrl` with
7
+ * `?handoff_checkout_link=cs_…&handoff_order=…`. That return is only a hint: `handleReturn`
8
+ * confirms it with the API before anything trusts it.
9
+ *
10
+ * Needs the store's storefront key; `successUrl` and `cancelUrl` must be on one of the key's
11
+ * allowed sites (`INVALID_REQUEST`, reason `RETURN_URL_REFUSED`, otherwise).
12
+ */
13
+ export interface CheckoutStart {
14
+ /** Where the shopper lands after paying. Absolute https (http on localhost), on one of the key's allowed sites. */
15
+ successUrl: string;
16
+ /** Where the checkout page's back link goes. */
17
+ cancelUrl?: string | null;
18
+ /** 5 to 1440; 60 by default. */
19
+ expiresInMinutes?: number;
20
+ }
21
+ export interface CheckoutReturn {
22
+ checkoutLinkId: string;
23
+ status: CheckoutLinkState['status'];
24
+ orderNumber: string | null;
25
+ /** True only when the API says the link's order is complete. */
26
+ paid: boolean;
27
+ }
28
+ export interface CheckoutResource {
29
+ /** Makes a checkout link from lines. */
30
+ create(input: CheckoutStart & {
31
+ lines: CheckoutLinkLine[];
32
+ }): Promise<CheckoutLink>;
33
+ /** Makes a checkout link from the visitor's cart (the lines it holds now). Refuses an empty cart. */
34
+ fromCart(input: CheckoutStart): Promise<CheckoutLink>;
35
+ /** A link's state: `OPEN`, `COMPLETED` (with `orderNumber`) or `EXPIRED`. */
36
+ get(checkoutLinkId: string): Promise<CheckoutLinkState>;
37
+ /**
38
+ * Reads the return address (the page's URL, as a string or URL) and confirms it with the API.
39
+ * Null when the address is not a return from checkout. When the order is complete and
40
+ * `clearCart` is not false, the visitor's cart here is emptied (its lines were bought).
41
+ */
42
+ handleReturn(address: string | URL, options?: {
43
+ clearCart?: boolean;
44
+ }): Promise<CheckoutReturn | null>;
45
+ }
46
+ /** The checkout lines a cart's items stand for: gifts a discount added are left to the discount. */
47
+ export declare function linesOfCart(cart: SessionCart): CheckoutLinkLine[];
48
+ export declare function checkoutResource(transport: Transport, cart: {
49
+ get(): Promise<SessionCart>;
50
+ clear(): Promise<SessionCart>;
51
+ }): CheckoutResource;
@@ -0,0 +1,29 @@
1
+ import type { HttpMethod, SessionValue, Transport } from '../core/transport';
2
+ import type { ShopperTokens } from '../types/api';
3
+ /**
4
+ * TOKEN SESSIONS on the outside-site transport (part 1B): every route under
5
+ * `storefront/api/v1/session/`, with the visitor's token as `Authorization: Bearer`.
6
+ *
7
+ * - A guest has a cart token (`kind: 'cart'`, 30 days), made on the first cart write
8
+ * (`POST session/cart-token`), never on a read: a visitor who only browses costs nothing.
9
+ * - A signed-in shopper has an access token (`kind: 'shopper'`, 15 minutes) and a refresh token.
10
+ * The access token is renewed shortly before it expires and once when the API answers
11
+ * `TOKEN_EXPIRED`; one renewal runs at a time. A renewal that is refused signs the shopper out
12
+ * here (the session is cleared) and the call fails with the API's code.
13
+ * - A cart token the API no longer takes (`TOKEN_INVALID`, `TOKEN_EXPIRED`) is dropped; a cart
14
+ * write then starts a new cart once.
15
+ */
16
+ export declare const SESSION_PREFIX = "session/";
17
+ export declare const isCartWrite: (method: HttpMethod, path: string) => boolean;
18
+ export declare function shopperSession(tokens: ShopperTokens): SessionValue;
19
+ export interface SessionTransport extends Transport {
20
+ /** Makes sure a cart write has a token to go with: the shopper's, the guest's, or a new cart token. */
21
+ ensureCartToken(): Promise<void>;
22
+ /** Renews a shopper's access token now (single flight). Rejects, and signs out here, when refused. */
23
+ refresh(): Promise<void>;
24
+ }
25
+ /**
26
+ * The key transport with paths under `session/`, a cart token made on demand and a shopper's
27
+ * access token kept fresh. `inner` sends the session's token (it reads `session` at each call).
28
+ */
29
+ export declare function sessionTransport(inner: Transport, now?: () => number): SessionTransport;