@moonbase.sh/react 0.0.0 → 1.1.0

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,670 @@
1
+ import { User, Address, SignUpOptions, SignUpResult, CommunicationPreferences, UserAccountConfirmed, ConnectableAccountProvider, CheckoutRedirectMode, StorefrontProduct, StorefrontBundle, PricingVariation, StorefrontOffer, LineItem, MoonbaseConfiguration, Storefront, MoonbaseClient, Order, UrchinTrackingModule, OpenOrder, Money, CheckoutPaymentFailure, CompletedOrder, AdConsentReport, AdSignals, OfferConditionContext, StorefrontPromotion, OfferProgress, ActivationRequest, CartTotal, SubscribeInput, CommunicationPreferencesInput, Activation, ActivationMethod, Download, SubscriptionCancellationFeedback, Subscription, Page, ProductReviewSort, SubmitReviewRequest, ReviewVoteDirection, Vendor, Voucher } from '@moonbase.sh/storefront-api';
2
+ export * from '@moonbase.sh/storefront-api';
3
+ import { ReactNode } from 'react';
4
+
5
+ interface StorefrontAuth {
6
+ signIn: (email: string, password: string) => Promise<User>;
7
+ /**
8
+ * Creates the customer's account. Sends the UTM tags, campaign IDs, ad click IDs (only with consent)
9
+ * and referrer the visitor arrived with, and the ad signals, as the cart and checkout do, unless
10
+ * `options` names its own `utm` or `signals`. Signs them in straight away unless the store asks new
11
+ * customers to confirm their email first.
12
+ */
13
+ signUp: (name: string, email: string, password: string, address: Address | null | undefined, acceptedPrivacyPolicy: boolean, acceptedTermsAndConditions: boolean, communicationOptIn?: boolean, options?: SignUpOptions) => Promise<SignUpResult>;
14
+ /**
15
+ * Signs the customer out. The cart stays, under a new ID, so it is no longer tied to them and can't
16
+ * be claimed by the next person who signs in on this browser.
17
+ */
18
+ signOut: () => Promise<void>;
19
+ /**
20
+ * The signed-in customer's access token, renewed first if it is about to run out, or null when
21
+ * nobody is signed in. For calling your own API on their behalf.
22
+ */
23
+ getAccessToken: () => Promise<string | null>;
24
+ /** Changes the customer's name, email or communication preferences. A null name leaves it as it is. */
25
+ update: (name: string | null, email: string, emailConfirmationToken?: string, communicationPreferences?: CommunicationPreferences) => Promise<{
26
+ user: User;
27
+ needsEmailConfirmationToken: boolean;
28
+ }>;
29
+ /** Saves the signed-in customer's address, which their next checkout starts from. */
30
+ updateAddress: (address: Address) => Promise<User>;
31
+ setPassword: (currentPassword: string, newPassword: string) => Promise<void>;
32
+ forgotPassword: (email: string) => Promise<void>;
33
+ resetPassword: (email: string, newPassword: string, code: string) => Promise<void>;
34
+ /** Confirms a new account from the code in its welcome email, which signs the customer in. */
35
+ confirmAccount: (email: string, code: string) => Promise<UserAccountConfirmed>;
36
+ confirmEmail: (email: string, code: string) => Promise<void>;
37
+ confirmEmailChange: (email: string, code: string) => Promise<User | null>;
38
+ getConnectionUrl: (provider: ConnectableAccountProvider, redirectUri: string, loginId?: string) => Promise<string>;
39
+ disconnectAccount: (provider: ConnectableAccountProvider) => Promise<User | null>;
40
+ /** Asks Moonbase who is signed in again. */
41
+ refreshUser: () => Promise<User | null>;
42
+ }
43
+
44
+ interface CheckoutItem {
45
+ item: StorefrontProduct | StorefrontBundle;
46
+ /** The pricing option to buy it at. The default one when left out. */
47
+ variation?: PricingVariation;
48
+ quantity?: number;
49
+ /**
50
+ * The customer's license this purchase upgrades or renews, for a product whose licenses cover only
51
+ * some releases. Buying it extends that license instead of issuing another, at the price the
52
+ * storefront quotes for that license. Always a quantity of 1. Products only. Left out, the purchase
53
+ * issues new licenses.
54
+ */
55
+ targetLicenseId?: string;
56
+ }
57
+ interface CheckoutResult {
58
+ /** Where the checkout suggested going next, if anywhere. */
59
+ next: string | undefined;
60
+ completed: boolean;
61
+ /**
62
+ * The buyer was sent to the hosted checkout by a full-page navigation, so this call can't report an
63
+ * outcome: the result arrives on the return page, as a `checkoutCompleted` event. Don't treat
64
+ * `completed: false` as a failure when this is set.
65
+ */
66
+ redirected: boolean;
67
+ }
68
+ interface CheckoutRedirectOptions {
69
+ /**
70
+ * Where the checkout happens. `'auto'`, the default, opens it over the page on a computer and sends
71
+ * a phone to Moonbase's own checkout page, where Apple Pay and Google Pay work: those wallets need the
72
+ * checkout to be the top-level page. `'always'` (or `true`) always sends the buyer there, `'never'`
73
+ * (or `false`) always opens it over the page.
74
+ */
75
+ redirect?: boolean | CheckoutRedirectMode;
76
+ /** Where a buyer sent to the hosted checkout comes back to. This page, by default, query and all. */
77
+ returnUrl?: string;
78
+ }
79
+ interface CheckoutOptions extends CheckoutRedirectOptions {
80
+ /** A coupon to apply. One the API refuses is reported to `onCouponRejected`, and the checkout opens without it. */
81
+ couponCode?: string;
82
+ /** Customer lists the buyer joins once the order is paid for. They have to be open to sign-ups. */
83
+ groupIds?: string[];
84
+ onCouponRejected?: (code: string, error: unknown) => void;
85
+ }
86
+
87
+ type CartItem = LineItem;
88
+ interface AddToCartOptions {
89
+ /**
90
+ * What a bundle does to the lines for products it includes: `'append'` leaves them, `'replace'`
91
+ * takes out those sold on the same terms as the bundle, and puts them back if the bundle is removed.
92
+ */
93
+ bundleBehaviour?: 'append' | 'replace';
94
+ /**
95
+ * The customer's license this purchase upgrades or renews, for a product whose licenses cover only
96
+ * some releases ("12 months of updates", "versions up to 2.x"). Buying it extends that license
97
+ * instead of issuing another, at the price the storefront quotes for that license
98
+ * (`licenseUpgrades`). Each license is a line of its own with a quantity of 1, so adding it again
99
+ * changes nothing, and adding it with another variation replaces the line. Products only. Left out,
100
+ * the purchase issues a new license.
101
+ */
102
+ targetLicenseId?: string;
103
+ }
104
+ interface CartCheckoutOptions extends CheckoutRedirectOptions {
105
+ /** Customer lists the buyer joins once the order is paid for. They have to be open to sign-ups. */
106
+ groupIds?: string[];
107
+ }
108
+ interface StorefrontCart {
109
+ /**
110
+ * Puts a product or bundle in the cart, or one more of it if it is there already, at `variation` or
111
+ * the default one, with `offer` attached if one is given. Returns the cart's line for it.
112
+ */
113
+ addToCart: (item: StorefrontProduct | StorefrontBundle, variation?: PricingVariation, offer?: StorefrontOffer, options?: AddToCartOptions) => CartItem;
114
+ /** Sets how many of a line the cart holds, and returns the line. Zero or less removes it. */
115
+ setQuantity: (cartItem: CartItem, quantity: number) => CartItem;
116
+ removeFromCart: (cartItem: CartItem) => void;
117
+ /**
118
+ * Opens the checkout for the cart. Over the page on a computer and on Moonbase's own checkout page
119
+ * on a phone, by default (see `redirect`). Settles once the overlay closes, or the page is on its way
120
+ * to the hosted checkout. The cart empties once the order is paid for.
121
+ */
122
+ checkout: (options?: CartCheckoutOptions) => Promise<CheckoutResult>;
123
+ /**
124
+ * Takes the cart offer off the order without sending the cart again. Cart offers apply themselves,
125
+ * but a page driving the cart itself may want to.
126
+ */
127
+ removeCartOffer: () => Promise<void>;
128
+ }
129
+
130
+ /** Everything a storefront knows that a page draws from. Replaced, never changed in place, on every update. */
131
+ interface StorefrontState {
132
+ /**
133
+ * The store's catalog for this visitor: products, bundles, offers and promotions, priced in their
134
+ * currency, with `owned` worked out for whoever is signed in. Starts from the copy this browser
135
+ * cached on an earlier visit, or empty, until Moonbase answers.
136
+ */
137
+ catalog: Storefront;
138
+ /** Whether `catalog` holds a real catalog yet, from Moonbase or from this browser's cache. */
139
+ catalogLoaded: boolean;
140
+ /**
141
+ * Whether the store has closed its Moonbase account. Its API then answers nothing but a
142
+ * `StoreClosedError`, so the storefront drops the cached catalog, the cart and the signed-in buyer,
143
+ * and this turns `true` for the page to say the store has closed.
144
+ */
145
+ closed: boolean;
146
+ /** The cart, as the order it becomes at checkout. Its lines are as stored: `useCart` has them priced. */
147
+ order: Order;
148
+ user: User | null;
149
+ /** Whether the storefront has asked Moonbase who is signed in, so `user: null` means nobody is. */
150
+ userLoaded: boolean;
151
+ /**
152
+ * The attribution the visitor arrived with, as the storefront keeps and sends it: the UTM tags, the
153
+ * referring site and the ad platforms a click came from, plus the ad click IDs themselves once the
154
+ * visitor has agreed to marketing cookies (`setAttributionConsent`), or where the store's own setting
155
+ * lets them go unasked.
156
+ */
157
+ utm: UrchinTrackingModule | undefined;
158
+ }
159
+ /** What a storefront reports, to `storefront.on` and `useStorefrontEvent`. */
160
+ interface StorefrontEvents {
161
+ checkoutInitiated: (order: OpenOrder, total: Money) => void;
162
+ /** The buyer saved their billing details in the embedded checkout. Called again each time they change them. */
163
+ checkoutBillingDetailsAdded: (order: OpenOrder) => void;
164
+ /**
165
+ * The buyer submitted payment in the embedded checkout. Each attempt is followed by either
166
+ * `checkoutPaymentFailed` or `checkoutCompleted`.
167
+ */
168
+ checkoutPaymentStarted: (order: OpenOrder) => void;
169
+ /**
170
+ * An attempt to pay in the embedded checkout failed: a declined card, or a 3-D Secure check the buyer
171
+ * did not pass. The checkout stays open for them to try again. `error.reason` says what kind of
172
+ * failure it was, never the card issuer's own decline code.
173
+ */
174
+ checkoutPaymentFailed: (order: OpenOrder, error: CheckoutPaymentFailure) => void;
175
+ /** The buyer applied a coupon code in the embedded checkout. */
176
+ checkoutCouponApplied: (order: OpenOrder, code: string) => void;
177
+ /** The buyer took a coupon off the order in the embedded checkout. */
178
+ checkoutCouponRemoved: (order: OpenOrder, code: string) => void;
179
+ /** The embedded checkout refused a coupon code the buyer typed, with the reason they were shown. */
180
+ checkoutCouponRejected: (code: string, message: string | undefined) => void;
181
+ /** An order was paid for, including one the buyer paid for on the hosted checkout and came back from. */
182
+ checkoutCompleted: (order: CompletedOrder) => void;
183
+ /**
184
+ * The checkout closed. `completed` says whether it completed the order (when `checkoutCompleted` is
185
+ * called), and `order` is the order it was open for, when the checkout sent it.
186
+ */
187
+ checkoutClosed: (intent: string | undefined, completed: boolean, order: Order | undefined) => void;
188
+ /** A fresh catalog arrived from Moonbase. */
189
+ catalogUpdated: (catalog: Storefront) => void;
190
+ /**
191
+ * Moonbase refused to renew the buyer's session: they signed out of it elsewhere, changed their
192
+ * password, or stayed away too long. The storefront has gone anonymous, as it does on signing out.
193
+ */
194
+ sessionEnded: (user: User) => void;
195
+ }
196
+ interface StorefrontOptions extends Omit<MoonbaseConfiguration, 'endpoint'> {
197
+ /**
198
+ * A catalog to start from, such as one a server fetched for the page it rendered. Used on the
199
+ * server, and in the browser until a fresher one loads unless this browser cached a newer one.
200
+ */
201
+ initialCatalog?: Storefront;
202
+ /**
203
+ * Whether the cart attaches eligible item-scope offers to the lines they target by itself, rather
204
+ * than only when something hands one to `addToCart`. Off by default. It never adds anything to the
205
+ * cart, and never replaces an offer a line already holds: it only fills an empty slot on a line
206
+ * that is in the cart already. Change it later with `storefront.autoApplyItemOffers`.
207
+ */
208
+ autoApplyItemOffers?: boolean;
209
+ }
210
+ /**
211
+ * A connection to a Moonbase store from a browser: the catalog, the signed-in customer and the cart,
212
+ * kept in step with Moonbase, with other tabs and with the checkout. Made once per page with
213
+ * `createStorefront` and handed to `<StorefrontProvider>`. Nothing in it depends on React, so the same
214
+ * object serves a router loader, a store of your own, or plain scripts.
215
+ */
216
+ declare class MoonbaseStorefront {
217
+ readonly configuration: MoonbaseConfiguration;
218
+ readonly client: MoonbaseClient;
219
+ static readonly sessionKey = "moonbase_session";
220
+ static readonly storefrontKey = "moonbase_storefront";
221
+ static readonly utmKey = "moonbase_utm";
222
+ static readonly arrivalKey = "moonbase_arrival";
223
+ /**
224
+ * Whether the cart attaches eligible item-scope offers by itself. See
225
+ * `StorefrontOptions.autoApplyItemOffers`. Read on every cart change.
226
+ */
227
+ autoApplyItemOffers: boolean;
228
+ /** Settles once `catalogLoaded` turns true. The same promise every time, so React's `use()` can suspend on it. */
229
+ readonly catalogLoadedPromise: Promise<void>;
230
+ /**
231
+ * Settles once the storefront knows who is signed in, if anyone. The same promise every time. On a
232
+ * server, at once: nobody is signed in there.
233
+ */
234
+ readonly userLoadedPromise: Promise<void>;
235
+ /** Signing in and out, and the customer's own account. */
236
+ readonly auth: StorefrontAuth;
237
+ /** The cart's lines and its checkout. */
238
+ readonly cart: StorefrontCart;
239
+ private state;
240
+ private readonly serverState;
241
+ private readonly listeners;
242
+ private resolveCatalogLoaded;
243
+ private resolveUserLoaded;
244
+ /**
245
+ * The attribution this tab knows of, ad click IDs and all: this page's arrival, or the one stored
246
+ * earlier in the tab. Kept in memory, where it never leaves the device, so that consent given after
247
+ * the page loaded can still add the click IDs to `utm`.
248
+ */
249
+ private arrival;
250
+ /** When and on which page `arrival` landed, for an arrival with tags. */
251
+ private landing;
252
+ /** What the site said of the visitor's consent, from its cookie banner; undefined until it says. */
253
+ private attributionConsentSetting;
254
+ /** Whether the store's own setting lets this visitor's attribution go ahead unasked, once the catalog has said. */
255
+ private storeAllowsAttribution;
256
+ private refreshOrderAbortController;
257
+ private pushTimeout;
258
+ private catalogRefreshesStarted;
259
+ private catalogRefreshLanded;
260
+ constructor(configuration: MoonbaseConfiguration, client: MoonbaseClient, options?: Pick<StorefrontOptions, 'initialCatalog' | 'autoApplyItemOffers'>);
261
+ /** The current state. A new object whenever anything in it changes, and the same one otherwise. */
262
+ readonly getState: () => StorefrontState;
263
+ /**
264
+ * The state a server renders with, and so what React hydrates against: the initial catalog, if any,
265
+ * an empty cart and nobody signed in. On the server itself, where there is nothing to hydrate, the
266
+ * current state, so a page that awaits `refreshCatalog()` before rendering renders with it.
267
+ */
268
+ readonly getServerState: () => StorefrontState;
269
+ /** Calls `listener` after every change to the state, and returns the function that stops it. */
270
+ readonly subscribe: (listener: () => void) => (() => void);
271
+ /**
272
+ * Calls `callback` each time the storefront reports `event`, and returns the function that stops it.
273
+ * In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
274
+ */
275
+ on<K extends keyof StorefrontEvents>(event: K, callback: StorefrontEvents[K]): () => void;
276
+ get hasUtm(): boolean;
277
+ get hasUtmOrReferrer(): boolean;
278
+ /** Whether the storefront may keep and send ad click IDs and record an arrival before any action. */
279
+ private get attributionConsent();
280
+ /**
281
+ * Buys these items straight away, without touching the cart: the "Buy now" path. Opens the checkout
282
+ * over the page, or on a phone sends the buyer to Moonbase's own checkout page (see `redirect`), and
283
+ * settles once the overlay closes or the page is on its way.
284
+ */
285
+ checkout(items: CheckoutItem[], options?: CheckoutOptions): Promise<CheckoutResult>;
286
+ /** Closes the checkout overlay, if one is open. */
287
+ closeCheckout(): void;
288
+ /**
289
+ * Say whether the visitor has agreed to marketing cookies, typically from a cookie banner's callback.
290
+ * `StorefrontOptions.attributionConsent` sets where it starts. Until either says, the storefront
291
+ * follows the store's own setting in Moonbase, which the catalog reports for this visitor once it
292
+ * loads. A banner that asks for Google's two parts separately can pass `{ adUserData, adPersonalization }`,
293
+ * which counts as granted here when `adUserData` is.
294
+ *
295
+ * Granting it adds the ad click IDs the visitor arrived with in this tab (`gclid`, `fbclid` and the
296
+ * rest) to `utm`, and records the arrival on a new cart if there is none yet, so a visitor who leaves
297
+ * and comes back to buy is still put down to it. Withdrawing it drops the click IDs from `utm` and the
298
+ * browser's storage again. What has already been sent stays with the order.
299
+ */
300
+ setAttributionConsent(granted: boolean | AdConsentReport): void;
301
+ /**
302
+ * What the storefront's requests say of the visit for ad measurement, beside `utm`: what the site last
303
+ * reported of the visitor's consent, left out until it says, and when and on which page the visit's
304
+ * tagged arrival landed, left out for a visit without tags.
305
+ */
306
+ adSignals(): AdSignals;
307
+ /** Asks Moonbase who is signed in. `state.user` is null when nobody is, or the session has run out. */
308
+ refreshUser(): Promise<User | null>;
309
+ /** Asks Moonbase for the catalog again, for this visitor and whoever is signed in. */
310
+ refreshCatalog(): Promise<Storefront>;
311
+ /**
312
+ * Saves the cart in this browser and sends it to Moonbase, half a second after the last change, so a
313
+ * buyer pressing "+" five times sends one request.
314
+ */
315
+ pushOrderContent(): void;
316
+ /**
317
+ * Starts a new, empty cart, or with `keepItems` a new cart holding the same lines, under a new ID.
318
+ * Coupons are not carried over: they are checked again for each order and customer.
319
+ */
320
+ resetOrder(opts?: {
321
+ keepItems?: boolean;
322
+ }): void;
323
+ /** Takes the billing details off the cart's order in Moonbase, as a buyer leaving it would want. */
324
+ surrenderOrder(): Promise<void>;
325
+ /** The lines with their products, bundles and prices from the current catalog. */
326
+ enrichLineItems(lineItems: LineItem[], order?: Order): LineItem[];
327
+ /** The context an offer's condition is judged against: the cart, unless another order is given. */
328
+ offerConditionContext(order?: Order): OfferConditionContext;
329
+ /** Puts the best cart offer the cart qualifies for on it, returning whether that changed anything. */
330
+ reconcileCartOffer(): boolean;
331
+ /**
332
+ * Takes the cart offer off the order without sending the cart again. Cart offers apply themselves,
333
+ * but a page driving the cart itself may want to.
334
+ */
335
+ removeCartOffer(): Promise<void>;
336
+ private setState;
337
+ /**
338
+ * The server refused to renew the buyer's session: they signed out of it elsewhere, changed their
339
+ * password, or stayed away too long. Goes anonymous the way signing out does, and says so, since
340
+ * nobody on this page signed out and the page would otherwise never hear of it.
341
+ */
342
+ private endSession;
343
+ private refreshInBackground;
344
+ /**
345
+ * The store has closed for good, so nothing kept for it is any use: not the catalog a returning
346
+ * visitor would otherwise be shown, not the cart, and not the buyer's session.
347
+ */
348
+ private closeStore;
349
+ /** Brings `utm`, its storage and the cart in line with the visitor's consent, when that changed. */
350
+ private attributionConsentChanged;
351
+ /** Keeps `landing` beside the arrival in `kind` storage, or clears what is there for an arrival without one. */
352
+ private storeLanding;
353
+ /** `utm` as the storefront may keep and send it: with its ad click IDs only once the visitor agreed. */
354
+ private consentedUtm;
355
+ private handleStorageUpdate;
356
+ private refreshOrder;
357
+ private static parseCachedUtm;
358
+ private static parseCachedOrder;
359
+ /**
360
+ * Reads a catalog out of local storage, normalising it through the schema, which fills in the
361
+ * defaults a catalog cached by an older version lacks. One the schema rejects is still used as it
362
+ * is: a catalog only partly understood beats an empty one while the refresh is in flight. Only
363
+ * unreadable JSON gives up.
364
+ */
365
+ private static parseCachedCatalog;
366
+ private static normalizeCatalog;
367
+ }
368
+
369
+ /** The store's catalog for this visitor, with `useStorefrontState(state => state.catalogLoaded)` saying whether it has loaded. */
370
+ declare function useCatalog(): Storefront;
371
+ declare function useProducts(): StorefrontProduct[];
372
+ /** The product with this ID in the catalog, or null, as before the catalog has loaded. */
373
+ declare function useProduct(productId: string): StorefrontProduct | null;
374
+ declare function useBundles(): StorefrontBundle[];
375
+ /** The bundle with this ID in the catalog, or null. */
376
+ declare function useBundle(bundleId: string): StorefrontBundle | null;
377
+ declare function useOffers(): StorefrontOffer[];
378
+ /** The offer with this ID in the catalog, or null. */
379
+ declare function useOffer(offerId: string): StorefrontOffer | null;
380
+ /**
381
+ * The sales currently running across the store's catalog.
382
+ *
383
+ * Moonbase already applies their dates and who they are for before it sends them, so everything here
384
+ * is live and applies to this visitor: show them as they are, never filter them again. The list
385
+ * changes when the visitor signs in or out, since that changes who qualifies.
386
+ */
387
+ declare function usePromotions(): StorefrontPromotion[];
388
+
389
+ interface LockedOffer {
390
+ offer: StorefrontOffer;
391
+ progress: OfferProgress;
392
+ }
393
+ /**
394
+ * What the cart's offer meter shows: the cart offer the buyer has earned, the one they are working
395
+ * toward, or both.
396
+ *
397
+ * A cart offer discounts the order as a whole, so there is nothing for the buyer to add and nothing to
398
+ * upsell: only a threshold to reach. Both fields can be set at once, which is the tiered case: only one
399
+ * cart offer ever applies to an order, so "10% over €50, 20% over €100" is two offers where reaching
400
+ * the second *replaces* the first. Without `next` a buyer on the lower rung would never learn the
401
+ * higher one exists.
402
+ */
403
+ interface CartOfferState {
404
+ /** The cart offer currently discounting the cart, and what it takes off. */
405
+ applied: {
406
+ offer: StorefrontOffer;
407
+ saving: number;
408
+ } | null;
409
+ /**
410
+ * The next rung worth reaching. When something is already applied this is always a strictly more
411
+ * valuable cart offer, since reaching a lesser one would leave the buyer worse off.
412
+ */
413
+ next: LockedOffer | null;
414
+ /** The cart before any cart offer. */
415
+ subtotal: number;
416
+ currency: string;
417
+ }
418
+
419
+ /** Offers the cart qualifies for and hasn't used, on something it doesn't hold yet: the upsells to show. */
420
+ declare function useEligibleOffers(): StorefrontOffer[];
421
+ /**
422
+ * Item offers the cart is short of, with how far off each is, nearest first: "spend €20 more and get
423
+ * Glass FX for half price". Only offers gated on what the cart is worth, which a buyer could otherwise
424
+ * never learn about.
425
+ */
426
+ declare function useLockedOffers(): LockedOffer[];
427
+ /** What the cart's offer meter shows: the cart offer the buyer has earned, the next one to reach, or both. */
428
+ declare function useCartOffer(): CartOfferState | null;
429
+
430
+ interface ActivationRequestState {
431
+ /** The request the app on the customer's computer made, or null until it has loaded. */
432
+ activationRequest: ActivationRequest | null;
433
+ loading: boolean;
434
+ /** Granting it a license or a trial, until Moonbase has. */
435
+ fulfilling: boolean;
436
+ /** Waiting for the app to pick up what was granted. */
437
+ completing: boolean;
438
+ error: string | null;
439
+ /** Whether the app has picked up its license or trial: the product is ready on that computer. */
440
+ isInstalled: boolean;
441
+ /** Activates the product on that computer with a license the signed-in customer owns. */
442
+ fulfillLicense: () => Promise<void>;
443
+ /** Starts a free trial on that computer, optionally signing the customer up for the newsletter. */
444
+ fulfillTrial: (newsletterOptIn?: boolean) => Promise<void>;
445
+ /** Turns the request down, as a customer who didn't make it would. */
446
+ cancel: () => Promise<void>;
447
+ }
448
+ /**
449
+ * Activating a product in the browser: the page an app opens with a `token` when its customer chooses
450
+ * to activate online. Loads the request, again when someone signs in, and once it has been granted
451
+ * waits for the app to pick it up. Without a token, as on a link that lost it, it loads nothing.
452
+ */
453
+ declare function useActivationRequest(token: string | null | undefined): ActivationRequestState;
454
+
455
+ interface Auth extends StorefrontAuth {
456
+ /** The signed-in customer, or null. */
457
+ user: User | null;
458
+ /**
459
+ * Whether the storefront has asked Moonbase who is signed in. Until it has, `user` can be null for a
460
+ * customer who is, so hold back anything that would show them "Sign in".
461
+ */
462
+ loaded: boolean;
463
+ }
464
+ /** The signed-in customer, and signing in, out and up. Every function keeps its identity across renders. */
465
+ declare function useAuth(): Auth;
466
+
467
+ interface Cart extends StorefrontCart {
468
+ /** The cart's lines, with their products or bundles and the prices the cart shows. */
469
+ items: CartItem[];
470
+ /**
471
+ * Lines whose product, or a product their bundle includes, has sold out. The checkout takes no
472
+ * payment for a cart holding one, so they have to come out first.
473
+ */
474
+ soldOutItems: CartItem[];
475
+ /** The currency the cart shows and checks out in: the one the store suggests for this visitor. */
476
+ currency: string;
477
+ total: {
478
+ amount: number;
479
+ currency: string;
480
+ };
481
+ /**
482
+ * The cart priced the way Moonbase prices it: product discounts and pricing tiers, then each line's
483
+ * own offer, then the cart offer. Before taxes, which the checkout works out from the billing address.
484
+ */
485
+ breakdown: CartTotal;
486
+ cartOffer: CartTotal['cartOffer'];
487
+ }
488
+ /** The cart, and changing it. Every function keeps its identity across renders. */
489
+ declare function useCart(): Cart;
490
+
491
+ /**
492
+ * Buying straight away, without the cart: the function a "Buy now" button calls.
493
+ *
494
+ * ```tsx
495
+ * const checkout = useCheckout()
496
+ * <button onClick={() => checkout([{ item: product }])}>Buy now</button>
497
+ * ```
498
+ *
499
+ * It opens the checkout over the page, or on a phone sends the buyer to Moonbase's own checkout page
500
+ * (see `redirect`), and settles once the overlay closes or the page is on its way.
501
+ */
502
+ declare function useCheckout(): (items: CheckoutItem[], options?: CheckoutOptions) => Promise<CheckoutResult>;
503
+
504
+ type CommunicationsEndpoints = MoonbaseClient['communications'];
505
+ interface Communications {
506
+ /** Signs someone up for the store's newsletter, with the attribution and ad signals the visit came with. */
507
+ subscribe: (input: SubscribeInput) => ReturnType<CommunicationsEndpoints['subscribe']>;
508
+ /** Confirms a newsletter sign-up from the link in its confirmation email. */
509
+ confirm: (email: string, token: string) => ReturnType<CommunicationsEndpoints['confirm']>;
510
+ get: (email: string, token: string) => ReturnType<CommunicationsEndpoints['getPreferences']>;
511
+ update: (email: string, token: string, preferences: CommunicationPreferencesInput) => ReturnType<CommunicationsEndpoints['updatePreferences']>;
512
+ unsubscribe: (email: string, token: string) => ReturnType<CommunicationsEndpoints['unsubscribe']>;
513
+ }
514
+ /** Newsletter sign-ups, and the preferences page an email's footer links to. */
515
+ declare function useCommunicationPreferences(): Communications;
516
+
517
+ interface Groups {
518
+ /**
519
+ * Joins the signed-in customer to a customer list of the store's that has been opened to sign-ups.
520
+ *
521
+ * Throws `NotAuthenticatedError` when nobody is signed in, and `NotFoundError` for every reason the
522
+ * join can be refused, which Moonbase deliberately does not tell apart. Joining twice is fine.
523
+ */
524
+ join: (groupId: string) => Promise<void>;
525
+ }
526
+ declare function useGroups(): Groups;
527
+
528
+ type Inventory = MoonbaseClient['inventory'];
529
+ /** What the signed-in customer owns: products, licenses, the computers they're on, and subscriptions. */
530
+ interface StorefrontInventory {
531
+ getLicenses: (nextUrl?: string) => ReturnType<Inventory['licenses']['get']>;
532
+ getLicenseActivations: (licenseId: string, nextUrl?: string) => ReturnType<Inventory['licenses']['getActivations']>;
533
+ getProduct: (productId: string, version?: string) => ReturnType<Inventory['products']['get']>;
534
+ getProductReleases: (productId: string, nextUrl?: string) => ReturnType<Inventory['products']['getReleases']>;
535
+ getProducts: (nextUrl?: string) => ReturnType<Inventory['products']['getOwned']>;
536
+ getProductLicenses: (productId: string, nextUrl?: string) => ReturnType<Inventory['products']['getLicenses']>;
537
+ getProductActivations: (productId: string, nextUrl?: string) => ReturnType<Inventory['products']['getActivations']>;
538
+ /** Frees the seat an activation takes, so the license can go on another computer. */
539
+ revokeActivation: (activation: Activation) => ReturnType<Inventory['licenses']['revokeActivation']>;
540
+ /** Activates a product on the computer a device token is from, as the activation page and offline activation do. */
541
+ activateProduct: (deviceToken: string, activationMethod: ActivationMethod) => ReturnType<Inventory['activation']['activate']>;
542
+ /** Starts downloading a file, as the browser downloads anything. */
543
+ downloadProduct: (download: Download) => Promise<void>;
544
+ getSubscriptions: (nextUrl?: string) => ReturnType<Inventory['subscriptions']['get']>;
545
+ getSubscription: (subscriptionId: string) => ReturnType<Inventory['subscriptions']['getById']>;
546
+ cancelSubscription: (subscriptionId: string, feedback?: SubscriptionCancellationFeedback) => ReturnType<Inventory['subscriptions']['cancel']>;
547
+ /** The plans a subscription can switch to when its paid period ends. */
548
+ getSubscriptionPlanOptions: (subscriptionId: string) => ReturnType<Inventory['subscriptions']['getPlanOptions']>;
549
+ /** Switches a subscription to another plan of its product when its paid period ends. Nothing is charged until then. */
550
+ changeSubscriptionPlan: (subscriptionId: string, variationId: string) => ReturnType<Inventory['subscriptions']['changePlan']>;
551
+ cancelSubscriptionPlanChange: (subscriptionId: string) => ReturnType<Inventory['subscriptions']['cancelPlanChange']>;
552
+ /** Opens the checkout to renew a subscription that has lapsed, the way the cart's checkout opens. */
553
+ renewSubscription: (subscriptionId: string, options?: CheckoutRedirectOptions) => Promise<CheckoutResult>;
554
+ /** Opens Moonbase's form to change the card a subscription is paid with, over the page. */
555
+ updateSubscriptionPaymentMethod: (subscription: Subscription, options?: {
556
+ returnUrl?: string;
557
+ }) => Promise<{
558
+ completed: boolean;
559
+ }>;
560
+ }
561
+
562
+ /**
563
+ * What the signed-in customer owns, and managing it: products and their downloads, licenses and the
564
+ * computers they're activated on, and subscriptions.
565
+ */
566
+ declare function useInventory(): StorefrontInventory;
567
+
568
+ interface Orders {
569
+ /**
570
+ * The signed-in customer's completed orders, newest first, a page at a time. Pass a page's `next` to
571
+ * get the one after it. Throws `NotAuthenticatedError` when nobody is signed in.
572
+ */
573
+ getOrders: (nextUrl?: string) => Promise<Page<CompletedOrder>>;
574
+ /** The receipt for one of their orders, as a PDF, for your own download link or viewer. */
575
+ getReceipt: (order: Pick<CompletedOrder, 'id'>) => Promise<Blob>;
576
+ /** Saves the receipt for one of their orders, as the browser saves any download. */
577
+ downloadReceipt: (order: Pick<CompletedOrder, 'id'>) => Promise<void>;
578
+ }
579
+ /** The signed-in customer's purchases, for an account area of your own. */
580
+ declare function useOrders(): Orders;
581
+
582
+ type Reviews = MoonbaseClient['reviews'];
583
+ interface ProductReviews {
584
+ /** Whether the store takes reviews. Off until the catalog has loaded, and on older backends. */
585
+ enabled: boolean;
586
+ /** A product's published reviews, the first page. */
587
+ getReviews: (productId: string, filter?: {
588
+ sort?: ProductReviewSort;
589
+ stars?: number | null;
590
+ }) => ReturnType<Reviews['get']>;
591
+ /** The page after one `getReviews` or `getMoreReviews` returned, from its `next`. */
592
+ getMoreReviews: (next: string) => ReturnType<Reviews['getMore']>;
593
+ /** The signed-in customer's own review of a product. */
594
+ getMyReview: (productId: string) => ReturnType<Reviews['getMine']>;
595
+ /** Writes the customer's review, or rewrites the one they already have. */
596
+ saveReview: (productId: string, review: SubmitReviewRequest, existing: boolean) => ReturnType<Reviews['submit']>;
597
+ withdrawReview: (productId: string) => ReturnType<Reviews['withdraw']>;
598
+ /** Marks someone else's review helpful or not. */
599
+ voteOnReview: (productId: string, reviewId: string, direction: ReviewVoteDirection) => ReturnType<Reviews['vote']>;
600
+ }
601
+ /**
602
+ * The reviews of the store's products: reading them, writing your own, and voting on others'. Each
603
+ * product's `rating` comes with the catalog, and `hasRating(rating)` says whether there is a score
604
+ * worth showing yet.
605
+ */
606
+ declare function useReviews(): ProductReviews;
607
+
608
+ interface VendorState {
609
+ /** The store's name, logo and contact details, or null until they load or if they can't. */
610
+ vendor: Vendor | null;
611
+ loading: boolean;
612
+ }
613
+ /** Who runs the store: its name, logo and contact details. */
614
+ declare function useVendor(): VendorState;
615
+
616
+ interface Vouchers {
617
+ /** What a voucher code gives, without redeeming it. */
618
+ peek: (code: string) => Promise<Voucher>;
619
+ /** Redeems a voucher code for the signed-in customer. */
620
+ redeem: (code: string) => Promise<Voucher>;
621
+ }
622
+ /** Voucher codes: what one gives, and redeeming it. An unknown code throws `Voucher code invalid`. */
623
+ declare function useVoucher(): Vouchers;
624
+
625
+ interface StorefrontProviderProps {
626
+ /** The storefront `createStorefront` made, once, outside of any component. */
627
+ storefront: MoonbaseStorefront;
628
+ children?: ReactNode;
629
+ }
630
+ /** Makes a storefront available to every hook below it. */
631
+ declare function StorefrontProvider({ storefront, children }: StorefrontProviderProps): ReactNode;
632
+ /** The storefront from the nearest `<StorefrontProvider>`. */
633
+ declare function useStorefront(): MoonbaseStorefront;
634
+ /**
635
+ * Part of the storefront's state, and a render whenever that part changes. `selector` has to hand back
636
+ * something already in the state, such as `state => state.user`, rather than build a new object or
637
+ * array: anything worked out from the state belongs in a `useMemo` after this.
638
+ */
639
+ declare function useStorefrontState<T>(selector: (state: StorefrontState) => T): T;
640
+ /**
641
+ * Calls `handler` each time the storefront reports `event`, for as long as the component is mounted.
642
+ * The latest `handler` is always the one called, so it can use the component's current props and state
643
+ * without subscribing again on every render.
644
+ *
645
+ * ```tsx
646
+ * useStorefrontEvent('checkoutCompleted', order => setThanks(order))
647
+ * ```
648
+ */
649
+ declare function useStorefrontEvent<K extends keyof StorefrontEvents>(event: K, handler: StorefrontEvents[K]): void;
650
+
651
+ /**
652
+ * Connects to a Moonbase store, such as `https://demo.moonbase.sh`. Make it once, as the page loads
653
+ * and outside of any component, and hand it to `<StorefrontProvider>`:
654
+ *
655
+ * ```tsx
656
+ * const storefront = createStorefront('https://demo.moonbase.sh')
657
+ *
658
+ * createRoot(document.getElementById('root')!).render(
659
+ * <StorefrontProvider storefront={storefront}>
660
+ * <App />
661
+ * </StorefrontProvider>,
662
+ * )
663
+ * ```
664
+ *
665
+ * Coming back from the hosted checkout, it takes Moonbase's parameters off the address as it is made,
666
+ * so make it before a router that reads the address.
667
+ */
668
+ declare function createStorefront(endpoint: string, options?: StorefrontOptions): MoonbaseStorefront;
669
+
670
+ export { type ActivationRequestState, type AddToCartOptions, type Auth, type Cart, type CartCheckoutOptions, type CartItem, type CartOfferState, type CheckoutItem, type CheckoutOptions, type CheckoutRedirectOptions, type CheckoutResult, type Communications, type Groups, type LockedOffer, MoonbaseStorefront, type Orders, type ProductReviews, type StorefrontAuth, type StorefrontCart, type StorefrontEvents, type StorefrontInventory, type StorefrontOptions, StorefrontProvider, type StorefrontProviderProps, type StorefrontState, type VendorState, type Vouchers, createStorefront, useActivationRequest, useAuth, useBundle, useBundles, useCart, useCartOffer, useCatalog, useCheckout, useCommunicationPreferences, useEligibleOffers, useGroups, useInventory, useLockedOffers, useOffer, useOffers, useOrders, useProduct, useProducts, usePromotions, useReviews, useStorefront, useStorefrontEvent, useStorefrontState, useVendor, useVoucher };