@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.
@@ -0,0 +1,64 @@
1
+ import type { Shopper, ShopperNeedsProfile } from '../types/api';
2
+ import { type SessionTransport } from './session';
3
+ /** What a sign-in step answers: signed in, or the store needs a profile first. */
4
+ export type SignInResult = {
5
+ signedIn: true;
6
+ shopper: Shopper;
7
+ cartMerged: boolean;
8
+ } | {
9
+ signedIn: false;
10
+ needsProfile: true;
11
+ registrationToken: string;
12
+ requirements: ShopperNeedsProfile['requirements'];
13
+ };
14
+ export interface ShopperVerify {
15
+ phone: string;
16
+ code: string;
17
+ /** Profile fields the store asks for at sign-up, when known already. */
18
+ /** True: a shopper new to the store gets `needsProfile` instead of a refusal. */
19
+ progressive?: boolean;
20
+ firstName?: string;
21
+ lastName?: string;
22
+ email?: string;
23
+ [field: string]: unknown;
24
+ }
25
+ /**
26
+ * Shopper sign-in with a code sent by text message (part 1B). A guest's cart is merged into the
27
+ * shopper's on sign-in (`cartMerged`). The tokens stay inside the library's `Session`: never
28
+ * handed to the caller.
29
+ */
30
+ export interface ShopperResource {
31
+ /** Texts a sign-in code to `phone` (E.164, such as `+15551234567`). */
32
+ start(phone: string): Promise<{
33
+ sent: true;
34
+ }>;
35
+ /**
36
+ * Checks the code. Signed in, or (with `progressive: true`, for a shopper new to the store)
37
+ * `needsProfile`: ask for the `requirements`, then call `register`.
38
+ */
39
+ verify(input: ShopperVerify): Promise<SignInResult>;
40
+ /** Finishes a sign-up the store needed more for: the `registrationToken` and the asked fields. */
41
+ register(input: {
42
+ registrationToken: string;
43
+ [field: string]: unknown;
44
+ }): Promise<SignInResult>;
45
+ /** Stores that check email: send and check an email code (`{ email }`, then `{ email, code }`). */
46
+ email: {
47
+ start(input: {
48
+ email: string;
49
+ [field: string]: unknown;
50
+ }): Promise<unknown>;
51
+ verify(input: {
52
+ email: string;
53
+ code: string;
54
+ [field: string]: unknown;
55
+ }): Promise<unknown>;
56
+ };
57
+ /** The signed-in shopper, or null when no one is signed in here. */
58
+ get(): Promise<Shopper | null>;
59
+ /** True while this storefront holds a shopper's session. */
60
+ signedIn(): boolean;
61
+ /** Ends the session at Hand-Off and here. */
62
+ signOut(): Promise<void>;
63
+ }
64
+ export declare function shopperResource(transport: SessionTransport): ShopperResource;
@@ -0,0 +1,86 @@
1
+ import { type CartResource } from '../core/cart';
2
+ import { type CollectionsResource } from '../core/collections';
3
+ import { type ContentResource } from '../core/content';
4
+ import { type MenusResource } from '../core/menus';
5
+ import { type ProductsResource } from '../core/products';
6
+ import { type StoreHours } from '../core/store';
7
+ import { type Transport } from '../core/transport';
8
+ import { type KeyTransportOptions } from '../transport/key';
9
+ import type { Category, SessionCart, PageSummary, PathContent, Policy, Store, VariantLookup } from '../types/api';
10
+ import { type CheckoutResource } from './checkout';
11
+ import { type ShopperResource } from './shopper';
12
+ /**
13
+ * `createStorefront`: the npm package's front door (ship 3, part 3A). The same resources the
14
+ * sealed page's `window.HandOff` is built from (`core/`), over the outside-site transport, plus
15
+ * the reads an outside site needs that a sealed page gets from its context (the store itself,
16
+ * pages, a variant by id).
17
+ *
18
+ * The cart and shopper sign-in stand on token sessions (1B, `sdk/session.ts`), checkout on the
19
+ * checkout links for outside sites (2A-2, `sdk/checkout.ts`). Methods are added, never renamed.
20
+ */
21
+ export interface StorefrontOptions extends KeyTransportOptions {
22
+ /** Told the visitor's cart after every cart call that answered one. */
23
+ onCartChange?: (cart: SessionCart) => void;
24
+ }
25
+ /** The cart a visitor has before their first add: nothing is made at Hand-Off until then. */
26
+ export declare const EMPTY_CART: Readonly<SessionCart>;
27
+ export interface StoreInfoResource {
28
+ /** The store: name, address, currency, language, branding, contact, hours, fulfillment. */
29
+ get(): Promise<Store>;
30
+ /** Opening hours, whether orders are taken now, and each fulfillment method's hours. */
31
+ hours(): Promise<StoreHours>;
32
+ /** The store's policy pages (refunds, privacy, terms…). */
33
+ policies(): Promise<Policy[]>;
34
+ }
35
+ export interface VariantsResource {
36
+ /** A variant by its id (a cart line's or an order line's), with its product. */
37
+ get(variantId: string): Promise<VariantLookup>;
38
+ }
39
+ export interface CategoriesResource {
40
+ /**
41
+ * The store's product categories: top-level ones first, then their subcategories (`parentId`),
42
+ * each with its page on the shop (`url`) and `productCount`. List a category's products with
43
+ * `products.list({ categoryId })`.
44
+ */
45
+ list(): Promise<Category[]>;
46
+ }
47
+ export interface PagesResource {
48
+ /** The pages anyone may list: the built-in pages (home, about, contact, FAQ) and the store's own. */
49
+ list(): Promise<PageSummary[]>;
50
+ /**
51
+ * Whatever lives at a path of the shop (`/about`, `/blog`, `/blog/first-post`): a page, a
52
+ * content list, one entry, or `{ kind: 'redirect', toPath }` where the address moved.
53
+ */
54
+ byPath(path: string): Promise<PathContent>;
55
+ }
56
+ export interface Storefront {
57
+ store: StoreInfoResource;
58
+ products: ProductsResource;
59
+ variants: VariantsResource;
60
+ collections: CollectionsResource;
61
+ categories: CategoriesResource;
62
+ pages: PagesResource;
63
+ content: ContentResource;
64
+ menus: MenusResource;
65
+ /**
66
+ * The visitor's cart (token sessions, part 1B). The first write makes a cart token and keeps it
67
+ * in `session`; `get()` before that answers an empty cart without calling. Discount codes need a
68
+ * signed-in shopper.
69
+ */
70
+ cart: CartResource<SessionCart>;
71
+ /** Shopper sign-in with a text-message code, and sign-out (part 1B). */
72
+ shopper: ShopperResource;
73
+ /** Hand-Off's checkout: a one-time link from lines or the cart, and the confirmed return (part 2A-2). */
74
+ checkout: CheckoutResource;
75
+ /** The transport underneath: its `base`, the visitor's `session`, and `request` for a route the library has no method for yet. */
76
+ transport: Transport & {
77
+ readonly base: string;
78
+ };
79
+ }
80
+ export declare function createStorefront(options: StorefrontOptions): Storefront;
81
+ /**
82
+ * An amount in minor units as a price: `formatMoney(1250, 'USD')` → `$12.50`. Every price the
83
+ * API gives is in minor units and names its `currency`; `language` is the store's
84
+ * (`store.get()`'s `language`) or the visitor's.
85
+ */
86
+ export declare function formatMoney(amount: number, currency: string, language?: string): string;
@@ -0,0 +1,77 @@
1
+ import type { Session, Transport, TransportResult } from '../core/transport';
2
+ /**
3
+ * THE OUTSIDE-SITE TRANSPORT (ship 3, part 3A): how a shop built on another stack (a Next.js
4
+ * site, a static page, a server) calls the storefront API. It calls
5
+ * `https://{shop address}/storefront/api/v1/…`, the same public routes the shop's own pages read.
6
+ *
7
+ * - The store is the one the shop address names: its host (a `*.handoff.market` address or the
8
+ * store's own domain) and, in an organization with several stores, the store slug after it.
9
+ * - The store's publishable storefront key (`hopk_…`, part 1A), when one is given, goes in
10
+ * `PUBLISHABLE_KEY_HEADER` (`X-Storefront-Key`). It is public by design: it names the store, a
11
+ * browser's `Origin` must be on the key's allowed sites, and it grants nothing a shopper could
12
+ * not do on the shop itself. With a key the API serves the key's store whatever the address.
13
+ * A keyed call never carries cookies, and the API answers CORS for the key's sites only.
14
+ * - The visitor's session (part 1B: a cart or shopper token) goes in `Authorization: Bearer` and
15
+ * nowhere else. Where it is kept is the caller's choice (`Session`); memory by default.
16
+ * - No cookie is ever sent or kept (`credentials: 'omit'`): an outside site is another site, and
17
+ * the shop's own cookies are not its to use.
18
+ * - It calls one place only: addresses under the base. A redirect is refused, so the token and
19
+ * the key never follow one to another host.
20
+ * - Every failure rejects with a `HandOffError` whose `code` is the API's (`NOT_FOUND`, …) or one
21
+ * of the library's (`NETWORK_ERROR`, `INVALID_RESPONSE`, `INVALID_ARGUMENT`).
22
+ *
23
+ * Unlike the sealed transport it runs on a page the developer owns (or a server), next to no
24
+ * code it must distrust, so it uses the platform's built-ins in the ordinary way.
25
+ */
26
+ /** The header the publishable storefront key travels in (the contract's `STOREFRONT_KEY_HEADER`). */
27
+ export declare const PUBLISHABLE_KEY_HEADER = "X-Storefront-Key";
28
+ /** The path under a shop address where the API's public routes live. */
29
+ export declare const STOREFRONT_API_PATH = "storefront/api/v1/";
30
+ /** As much of `fetch` as this transport uses: the browser's, Node's (18 and later), or a polyfill. */
31
+ export interface KeyFetchInit {
32
+ method: string;
33
+ headers: Record<string, string>;
34
+ body?: string;
35
+ credentials: 'omit';
36
+ redirect: 'error';
37
+ signal?: AbortSignal;
38
+ }
39
+ export interface KeyFetchAnswer {
40
+ status: number;
41
+ text(): Promise<string>;
42
+ }
43
+ export type KeyFetch = (url: string, init: KeyFetchInit) => Promise<KeyFetchAnswer>;
44
+ export interface KeyTransportOptions {
45
+ /**
46
+ * The shop's address: `https://acme.handoff.market`, the store's own domain, or either with the
47
+ * store slug after it (`https://acme.handoff.market/bakery`) when the organization has several
48
+ * stores. `https` only (`http` on `localhost` for development).
49
+ */
50
+ shop: string;
51
+ /**
52
+ * The store's publishable storefront key (`hopk_…`), created by the store's owner with your
53
+ * site's address on its allowed sites. Needed for browser calls; optional from a server.
54
+ */
55
+ publishableKey?: string;
56
+ /** Where the visitor's cart or shopper token is kept. Memory when left out. */
57
+ session?: Session;
58
+ /** `fetch` to use. The global one when left out (browsers, Node 18 and later). */
59
+ fetch?: KeyFetch;
60
+ /** Headers added to every request (`Accept-Language`, a tracing header). Never `Authorization` or the key's header. */
61
+ headers?: Record<string, string>;
62
+ /** Gives up after this long. 15 seconds by default; 0 waits as long as `fetch` does. */
63
+ timeoutMs?: number;
64
+ }
65
+ /**
66
+ * The API base for a shop address: `{origin}{store slug path}/storefront/api/v1/`. Refuses an
67
+ * address that is not https (http on localhost), carries a user name, a query or a fragment, or
68
+ * has more than two path parts (a store slug and a language).
69
+ */
70
+ export declare function storefrontApiBase(shop: string): string;
71
+ /** The API's answer as `{ data, page? }`, or the `HandOffError` it stands for. */
72
+ export declare function understoodAnswer<T>(status: number, text: string): TransportResult<T>;
73
+ export interface KeyTransport extends Transport {
74
+ /** `https://{shop}/storefront/api/v1/`: every address this transport calls starts with it. */
75
+ readonly base: string;
76
+ }
77
+ export declare function createKeyTransport(options: KeyTransportOptions): KeyTransport;
@@ -0,0 +1,21 @@
1
+ import type { Session, SessionValue } from '../core/transport';
2
+ /** A session kept in memory and nowhere else: gone with the page (or the server process). */
3
+ export declare function memorySession(initial?: SessionValue | null): Session;
4
+ /** The part of the Web Storage API a storage session uses (`localStorage`, `sessionStorage`, or anything shaped like them). */
5
+ export interface StorageLike {
6
+ getItem(key: string): string | null;
7
+ setItem(key: string, value: string): void;
8
+ removeItem(key: string): void;
9
+ }
10
+ /**
11
+ * A session kept in Web Storage under `key`, so the visitor's cart survives a reload. A value
12
+ * that is not one this library wrote, or whose time has passed, reads as no session. Storage
13
+ * that throws (a private window, storage switched off) behaves as memory for this page.
14
+ *
15
+ * For a CART token only. Anything stored there is readable by every script on the site; a cart
16
+ * token reaches the visitor's cart and nothing else (part 1B). A shopper's sign-in tokens reach
17
+ * their account (orders, addresses): keep those in `memorySession()`, or in an HttpOnly cookie
18
+ * your own server sets behind a `Session` of your own, never in Web Storage. So a shopper's
19
+ * session given to it is kept in memory for this page only, and what storage held is removed.
20
+ */
21
+ export declare function storageSession(storage: StorageLike, key?: string, now?: () => number): Session;