@hand-off/storefront 0.1.0 → 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/README.md CHANGED
@@ -1,9 +1,8 @@
1
1
  # @hand-off/storefront
2
2
 
3
- Build a shop on any stack against a [Hand-Off](https://hand-off.net) store: Next.js, Astro, Remix,
3
+ Build a shop on any stack against a [Hand-Off](https://handoff.store) store: Next.js, Astro, Remix,
4
4
  SvelteKit, a static page, or your own server. The library reads the store's catalogue and pages,
5
- and (as each server part ships) keeps the visitor's cart, signs shoppers in and sends them to
6
- Hand-Off's checkout.
5
+ keeps the visitor's cart, signs shoppers in and sends them to Hand-Off's checkout.
7
6
 
8
7
  - No dependencies. ES module and CommonJS builds, with TypeScript types for every answer.
9
8
  - The same client the store builder's own pages run on (`window.HandOff` on a sealed page).
@@ -100,6 +99,8 @@ await shop.shopper.signOut();
100
99
  - The library keeps every token in its `session` and renews a shopper's 15-minute access token on
101
100
  its own. No method hands a token back.
102
101
  - A discount code is sent once per call, never retried.
102
+ - Sign-in codes belong to the key's store: start with `shopper.start`. A code from the shop's own
103
+ sign-in page is refused by `shopper.verify`.
103
104
 
104
105
  | Call | Does |
105
106
  | --- | --- |
@@ -140,6 +141,262 @@ if (result?.paid) showThanks(result.orderNumber); // confirmed with the API, car
140
141
  - `INVALID_REQUEST` with `reason: 'RETURN_URL_REFUSED'`: an address is not on the key's allowed
141
142
  sites. `UNAVAILABLE` with `reason: 'CHECKOUT_LINKS_OFF'`: the store has no checkout links.
142
143
 
144
+ ## Set up the store (the owner)
145
+
146
+ The store's owner does this once, in the Hand-Off dashboard (or by asking the Hand-Off Assistant
147
+ or a connected AI, which have the same tools: `set_storefront_keys_enabled`, `create_storefront_key`):
148
+
149
+ 1. **Publish the store's Hand-Off storefront.** The API serves only a published store.
150
+ 2. **Switch storefront keys on** for the store (off by default) and **create a key** (`hopk_…`).
151
+ It is publishable: it may sit in your site's JavaScript.
152
+ 3. **List the sites allowed to use it**: exact origins such as `https://shop.example.com`, plus
153
+ `http://localhost:3000` while developing. A browser call from any other origin is refused
154
+ (`ORIGIN_REFUSED`); server calls send no origin and are accepted.
155
+ 4. **Token sessions and checkout links** (the cart, shopper sign-in and checkout from your site)
156
+ are rolling out store by store: ask Hand-Off support to switch them on for the store. Until
157
+ then those calls answer `NOT_FOUND` or `UNAVAILABLE`, and catalogue reads still work.
158
+
159
+ Rotate a key that leaked (the old one keeps working until the time you set) or revoke it; both
160
+ are in the same settings.
161
+
162
+ ## Next.js (App Router) walk-through
163
+
164
+ Server components read the catalogue on the server, with no key needed. The browser gets the
165
+ publishable key for the cart and checkout, and nothing else.
166
+
167
+ ```bash
168
+ # .env.local
169
+ HAND_OFF_SHOP_URL=https://acme.handoff.market
170
+ NEXT_PUBLIC_HAND_OFF_SHOP_URL=https://acme.handoff.market
171
+ NEXT_PUBLIC_HAND_OFF_STOREFRONT_KEY=hopk_… # publishable; browser only
172
+ ```
173
+
174
+ ```ts
175
+ // lib/shop.server.ts: catalogue reads on the server (no visitor state, so one client for every request)
176
+ import { createStorefront } from '@hand-off/storefront';
177
+ export const shop = createStorefront({ shop: process.env.HAND_OFF_SHOP_URL! });
178
+ ```
179
+
180
+ ```tsx
181
+ // app/page.tsx: the product list, paged with ?cursor=
182
+ import Link from 'next/link';
183
+ import { formatMoney } from '@hand-off/storefront';
184
+ import { shop } from '@/lib/shop.server';
185
+
186
+ export const revalidate = 60;
187
+
188
+ export default async function Home({ searchParams }: { searchParams: Promise<{ cursor?: string }> }) {
189
+ const { cursor } = await searchParams;
190
+ const [store, page] = await Promise.all([shop.store.get(), shop.products.list({ limit: 24, cursor })]);
191
+ return (
192
+ <main>
193
+ <h1>{store.name}</h1>
194
+ <ul>
195
+ {page.items.map((p) => (
196
+ <li key={p.id}>
197
+ <Link href={`/products/${p.slug}`}>
198
+ {p.image && <img src={p.image.url} srcSet={p.image.srcset || undefined} alt={p.image.alt} />}
199
+ {p.name} · {formatMoney(p.price, p.currency, store.language)}
200
+ </Link>
201
+ </li>
202
+ ))}
203
+ </ul>
204
+ {page.nextCursor && <Link href={`/?cursor=${encodeURIComponent(page.nextCursor)}`}>More</Link>}
205
+ </main>
206
+ );
207
+ }
208
+ ```
209
+
210
+ ```tsx
211
+ // app/products/[slug]/page.tsx: one product by its slug
212
+ import { notFound } from 'next/navigation';
213
+ import { formatMoney, HandOffError } from '@hand-off/storefront';
214
+ import { shop } from '@/lib/shop.server';
215
+ import { AddToBag } from './add-to-bag';
216
+
217
+ export const revalidate = 60;
218
+
219
+ export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
220
+ const { slug } = await params;
221
+ const product = await shop.products.get({ slug }).catch((error) => {
222
+ if (error instanceof HandOffError && error.code === 'NOT_FOUND') notFound();
223
+ throw error;
224
+ });
225
+ return (
226
+ <main>
227
+ <h1>{product.name}</h1>
228
+ {/* descriptionHtml is sanitised by Hand-Off */}
229
+ <div dangerouslySetInnerHTML={{ __html: product.descriptionHtml ?? '' }} />
230
+ <AddToBag
231
+ productId={product.id}
232
+ variants={product.variants.map((v) => ({ key: v.key, title: v.title, price: formatMoney(v.price, v.currency), soldOut: v.stock.state === 'out_of_stock' }))}
233
+ />
234
+ </main>
235
+ );
236
+ }
237
+ ```
238
+
239
+ ```tsx
240
+ // lib/shop.client.ts: the browser's client, with the publishable key and the guest cart kept across visits
241
+ 'use client';
242
+ import { createStorefront, storageSession } from '@hand-off/storefront';
243
+
244
+ let client: ReturnType<typeof createStorefront> | undefined;
245
+ export function browserShop() {
246
+ client ??= createStorefront({
247
+ shop: process.env.NEXT_PUBLIC_HAND_OFF_SHOP_URL!,
248
+ publishableKey: process.env.NEXT_PUBLIC_HAND_OFF_STOREFRONT_KEY!,
249
+ session: storageSession(window.localStorage, 'hand-off.cart'),
250
+ });
251
+ return client;
252
+ }
253
+ ```
254
+
255
+ ```tsx
256
+ // app/products/[slug]/add-to-bag.tsx: the cart, in the browser
257
+ 'use client';
258
+ import { useState } from 'react';
259
+ import { HandOffError } from '@hand-off/storefront';
260
+ import { browserShop } from '@/lib/shop.client';
261
+
262
+ export function AddToBag({ productId, variants }: { productId: string; variants: { key: string; title: string; price: string; soldOut: boolean }[] }) {
263
+ const [key, setKey] = useState(variants.find((v) => !v.soldOut)?.key ?? variants[0]?.key);
264
+ const [message, setMessage] = useState('');
265
+ async function add() {
266
+ try {
267
+ const cart = await browserShop().cart.add({ productId, combinationKey: key, quantity: 1 });
268
+ setMessage(`${cart.itemCount} in your bag`);
269
+ } catch (error) {
270
+ setMessage(error instanceof HandOffError && error.code === 'OUT_OF_STOCK' ? 'Sold out' : 'Could not add it');
271
+ }
272
+ }
273
+ return (
274
+ <div>
275
+ <select value={key} onChange={(e) => setKey(e.target.value)}>
276
+ {variants.map((v) => (
277
+ <option key={v.key} value={v.key} disabled={v.soldOut}>{v.title} · {v.price}</option>
278
+ ))}
279
+ </select>
280
+ <button onClick={add}>Add to bag</button>
281
+ <p role="status">{message}</p>
282
+ </div>
283
+ );
284
+ }
285
+ ```
286
+
287
+ ```tsx
288
+ // app/bag/pay-button.tsx: checkout on Hand-Off
289
+ 'use client';
290
+ import { browserShop } from '@/lib/shop.client';
291
+
292
+ export function PayButton() {
293
+ async function pay() {
294
+ const link = await browserShop().checkout.fromCart({
295
+ successUrl: `${location.origin}/thanks`,
296
+ cancelUrl: `${location.origin}/bag`,
297
+ });
298
+ location.assign(link.url);
299
+ }
300
+ return <button onClick={pay}>Pay</button>;
301
+ }
302
+ ```
303
+
304
+ ```tsx
305
+ // app/thanks/page.tsx: confirm the order (never trust handoff_order in the address alone)
306
+ 'use client';
307
+ import { useEffect, useState } from 'react';
308
+ import { browserShop } from '@/lib/shop.client';
309
+
310
+ export default function Thanks() {
311
+ const [text, setText] = useState('Checking your order…');
312
+ useEffect(() => {
313
+ browserShop().checkout.handleReturn(location.href).then((result) => {
314
+ setText(result?.paid ? `Thank you! Order ${result.orderNumber}.` : 'Your order is not paid yet.');
315
+ });
316
+ }, []);
317
+ return <main><p>{text}</p></main>;
318
+ }
319
+ ```
320
+
321
+ Your site's origins (production, and `http://localhost:3000` while developing) must be on the
322
+ key's allowed sites, and `successUrl` / `cancelUrl` must be on one of them.
323
+
324
+ ## Public vs sign-in-only catalogue
325
+
326
+ A store is public by default: anyone can read its catalogue. Its owner can make it private (the
327
+ store's visibility setting in the Hand-Off dashboard, or `update_storefront_availability` with
328
+ `visibility: 'PRIVATE'`), optionally with registration rules (approval, verification, a referral
329
+ code, a minimum age). A private store's catalogue is for its signed-in, approved shoppers only.
330
+
331
+ On a private store the reads answer:
332
+
333
+ | Code | Means | Show |
334
+ | --- | --- | --- |
335
+ | `AUTH_REQUIRED` | No signed-in shopper | A sign-in form |
336
+ | `REGISTRATION_REQUIRED` | Signed in, but not registered at this store | The sign-up (`shopper.register`) |
337
+ | `PENDING_APPROVAL` | Registered, waiting for the store's approval | A "we'll let you know" note |
338
+ | `VERIFICATION_REQUIRED` | The store needs email or ID verification first | The verification step |
339
+
340
+ ```tsx
341
+ // A server component that falls back to sign-in on a private store
342
+ import { HandOffError } from '@hand-off/storefront';
343
+ import { shop } from '@/lib/shop.server';
344
+ import { SignIn } from './sign-in';
345
+
346
+ export default async function Catalogue() {
347
+ try {
348
+ const { items } = await shop.products.list({ limit: 24 });
349
+ return <ProductGrid items={items} />;
350
+ } catch (error) {
351
+ if (error instanceof HandOffError && ['AUTH_REQUIRED', 'REGISTRATION_REQUIRED', 'PENDING_APPROVAL', 'VERIFICATION_REQUIRED'].includes(error.code)) {
352
+ return <SignIn reason={error.code} />;
353
+ }
354
+ throw error;
355
+ }
356
+ }
357
+ ```
358
+
359
+ ```tsx
360
+ // sign-in.tsx: shopper.start, then verify (with register when the store needs a profile)
361
+ 'use client';
362
+ import { useState } from 'react';
363
+ import { browserShop } from '@/lib/shop.client';
364
+
365
+ export function SignIn({ reason }: { reason: string }) {
366
+ const [phone, setPhone] = useState('');
367
+ const [code, setCode] = useState('');
368
+ const [sent, setSent] = useState(false);
369
+ if (reason === 'PENDING_APPROVAL') return <p>Your account is waiting for the store's approval.</p>;
370
+ async function submit() {
371
+ const shop = browserShop();
372
+ if (!sent) {
373
+ await shop.shopper.start(phone); // always start here: codes belong to the key's store
374
+ setSent(true);
375
+ return;
376
+ }
377
+ const result = await shop.shopper.verify({ phone, code, progressive: true });
378
+ if (!result.signedIn) {
379
+ // ask for result.requirements (name, email, referral…), then:
380
+ await shop.shopper.register({ registrationToken: result.registrationToken /* , firstName, … */ });
381
+ }
382
+ location.reload();
383
+ }
384
+ return (
385
+ <form onSubmit={(e) => { e.preventDefault(); void submit(); }}>
386
+ <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+15551234567" />
387
+ {sent && <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="Code" />}
388
+ <button>{sent ? 'Sign in' : 'Text me a code'}</button>
389
+ </form>
390
+ );
391
+ }
392
+ ```
393
+
394
+ > **Not yet: a private store's catalogue through the SDK.** Sign-in works, but the API reads a
395
+ > shopper's token on the cart and sign-in routes only, so the catalogue of a private store still
396
+ > answers `AUTH_REQUIRED` to an outside site after sign-in. Until that ships, keep a store whose
397
+ > catalogue you show on your own site public. The cart, sign-in and checkout already work on a
398
+ > private store's session routes.
399
+
143
400
  ## Errors
144
401
 
145
402
  Every failure rejects with a `HandOffError`. Branch on `code`, never on `message`:
@@ -198,9 +455,10 @@ createStorefront({
198
455
 
199
456
  ## Building a shop with a coding agent
200
457
 
201
- The Hand-Off developer pages publish a skill (instructions a coding agent such as Claude Code
202
- follows) for building a shop with this library: https://hand-off.net/developers/storefront-sdk/SKILL.md.
203
- It is in the package too: `node_modules/@hand-off/storefront/skill/SKILL.md`.
458
+ The package ships a skill (instructions a coding agent such as Claude Code follows) for building a
459
+ shop with this library: `node_modules/@hand-off/storefront/skill/SKILL.md`. Copy it into your
460
+ project (for Claude Code: `.claude/skills/build-hand-off-shop/SKILL.md`). A page for it on
461
+ handoff.store/developers is coming soon.
204
462
 
205
463
  ## License
206
464
 
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@hand-off/storefront",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Build a shop on any stack against a Hand-Off store: catalogue, cart, shopper sign-in and checkout, typed.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
8
- "url": "https://github.com/hand-off/hand-off-api",
8
+ "url": "git+https://github.com/hand-off/hand-off-api.git",
9
9
  "directory": "libs/storefront"
10
10
  },
11
- "homepage": "https://hand-off.net/developers/storefront-sdk",
11
+ "homepage": "https://handoff.store/developers",
12
12
  "keywords": [
13
13
  "hand-off",
14
14
  "storefront",
package/skill/SKILL.md CHANGED
@@ -10,7 +10,7 @@ it. `@hand-off/storefront` is the typed client for that: it reads the store's pu
10
10
  pages, and (as each part ships) keeps the visitor's cart, signs shoppers in and hands them to
11
11
  Hand-Off's checkout. You never handle card details.
12
12
 
13
- Reference: https://hand-off.net/developers/storefront-sdk. The package's own README
13
+ Reference: the package's own README
14
14
  (`node_modules/@hand-off/storefront/README.md`) lists every method; its types are the source of
15
15
  truth for every field.
16
16
 
@@ -110,6 +110,12 @@ lists the site's exact origin on it (and `http://localhost:3000` while developin
110
110
  calls any `/storefront/api/v1/` route, but prefer a library method.
111
111
  - **Never handle tokens yourself.** The library keeps the cart and sign-in tokens in its
112
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`.
113
119
  - **Discount codes**: one call is one attempt (never retried) and needs a signed-in shopper.
114
120
  - **Don't re-implement checkout, payments, tax or shipping.** Hand-Off does them on its checkout.
115
121
  - **Escape store text** in templates (framework defaults do). Only `descriptionHtml` and a