@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.
package/dist/index.js ADDED
@@ -0,0 +1,1631 @@
1
+ // src/index.ts
2
+ import { MoonbaseClient } from "@moonbase.sh/storefront-api";
3
+
4
+ // package.json
5
+ var version = "1.1.0";
6
+
7
+ // src/storefront.ts
8
+ import {
9
+ adClicksOf,
10
+ closeCheckout as closeCheckout2,
11
+ copyConsent,
12
+ forgetPurchase as forgetPurchase3,
13
+ grantsClickIds,
14
+ hasCampaignData,
15
+ isSameArrival,
16
+ landingHere,
17
+ mountCheckout as mountCheckout3,
18
+ mountSubscription,
19
+ NotAuthenticatedError,
20
+ NotAuthorizedError,
21
+ NotFoundError,
22
+ OrderStatus as OrderStatus3,
23
+ parseLanding,
24
+ parseOffSiteReferrer,
25
+ pruneRememberedPurchase,
26
+ readStorage,
27
+ removeStorage,
28
+ resolveDisplayCurrency as resolveDisplayCurrency3,
29
+ resolveUtm,
30
+ schemas as schemas2,
31
+ StoreClosedError,
32
+ TokenStore,
33
+ withoutClickIds,
34
+ withoutHandshakeParams as withoutHandshakeParams2,
35
+ writeStorage
36
+ } from "@moonbase.sh/storefront-api";
37
+
38
+ // src/auth.ts
39
+ import { forgetPurchase, schemas } from "@moonbase.sh/storefront-api";
40
+ function createAuth(storefront, internals) {
41
+ const { setUser } = internals;
42
+ const signedIn = () => storefront.getState().user !== null;
43
+ const refreshCatalog = () => {
44
+ storefront.refreshCatalog().catch((err) => console.error("Could not load the Moonbase catalog", err));
45
+ };
46
+ return {
47
+ signIn: async (email, password) => {
48
+ const user = await storefront.client.identity.signIn(email, password);
49
+ setUser(user);
50
+ refreshCatalog();
51
+ return user;
52
+ },
53
+ signUp: async (name, email, password, address, acceptedPrivacyPolicy, acceptedTermsAndConditions, communicationOptIn, options) => {
54
+ var _a, _b;
55
+ const result = await storefront.client.identity.signUp(
56
+ name,
57
+ email,
58
+ password,
59
+ address,
60
+ acceptedPrivacyPolicy,
61
+ acceptedTermsAndConditions,
62
+ communicationOptIn,
63
+ {
64
+ ...options,
65
+ // The tags the visitor arrived with, as orders carry them, unless the caller names its own.
66
+ utm: (_a = options == null ? void 0 : options.utm) != null ? _a : storefront.hasUtmOrReferrer ? storefront.getState().utm : void 0,
67
+ signals: (_b = options == null ? void 0 : options.signals) != null ? _b : storefront.adSignals()
68
+ }
69
+ );
70
+ if (result.status === "signed-in") {
71
+ setUser(result.user);
72
+ refreshCatalog();
73
+ }
74
+ return result;
75
+ },
76
+ signOut: async () => {
77
+ const revoked = storefront.client.identity.signOut();
78
+ setUser(null);
79
+ storefront.resetOrder({ keepItems: true });
80
+ forgetPurchase();
81
+ await storefront.refreshCatalog();
82
+ await revoked;
83
+ },
84
+ getAccessToken: () => storefront.client.tokenStore.getAccessToken(),
85
+ update: async (name, email, emailConfirmationToken, communicationPreferences) => {
86
+ const result = await storefront.client.identity.update(name, email, emailConfirmationToken, communicationPreferences);
87
+ if (signedIn())
88
+ setUser(result.user);
89
+ return result;
90
+ },
91
+ updateAddress: async (address) => {
92
+ const user = await storefront.client.identity.updateAddress(address);
93
+ if (signedIn())
94
+ setUser(user);
95
+ return user;
96
+ },
97
+ setPassword: (currentPassword, newPassword) => storefront.client.identity.setPassword(currentPassword, newPassword),
98
+ forgotPassword: (email) => storefront.client.identity.forgotPassword(email),
99
+ resetPassword: (email, newPassword, code) => storefront.client.identity.resetPassword(email, newPassword, code),
100
+ confirmAccount: async (email, code) => {
101
+ const result = await storefront.client.identity.confirmAccount(email, code);
102
+ if (result.status === "SignedIn") {
103
+ setUser(schemas.identity.userSchema.parse(storefront.client.tokenStore.user));
104
+ refreshCatalog();
105
+ }
106
+ return result;
107
+ },
108
+ confirmEmail: (email, code) => storefront.client.identity.confirmEmail(email, code),
109
+ confirmEmailChange: async (email, code) => {
110
+ await storefront.client.identity.confirmEmailChange(email, code);
111
+ return await storefront.refreshUser();
112
+ },
113
+ getConnectionUrl: (provider, redirectUri, loginId) => storefront.client.identity.getConnectionUrl(provider, redirectUri, loginId),
114
+ disconnectAccount: async (provider) => {
115
+ await storefront.client.identity.disconnectAccount(provider);
116
+ return await storefront.refreshUser();
117
+ },
118
+ refreshUser: () => storefront.refreshUser()
119
+ };
120
+ }
121
+
122
+ // src/cart.ts
123
+ import {
124
+ buildHostedRedirectUrl as buildHostedRedirectUrl2,
125
+ CartUtils as CartUtils3,
126
+ lineItemId as lineItemId2,
127
+ MoonbaseError as MoonbaseError2,
128
+ mountCheckout as mountCheckout2,
129
+ OfferUtils as OfferUtils2,
130
+ OrderStatus as OrderStatus2,
131
+ recordCheckoutGroups as recordCheckoutGroups2,
132
+ resolveDisplayCurrency as resolveDisplayCurrency2,
133
+ resolveRedirect as resolveRedirect2,
134
+ targetLicenseId as targetLicenseId2,
135
+ upgradeVariation as upgradeVariation2
136
+ } from "@moonbase.sh/storefront-api";
137
+
138
+ // src/checkout.ts
139
+ import {
140
+ buildHostedRedirectUrl,
141
+ CartUtils,
142
+ closeCheckout,
143
+ currentPageUrl,
144
+ forgetPurchase as forgetPurchase2,
145
+ hasCoupon,
146
+ hideCheckoutLoader,
147
+ isClosedOrderRefusal,
148
+ lineItemId,
149
+ MoonbaseError,
150
+ mountCheckout,
151
+ recordCheckoutGroups,
152
+ rememberPurchase,
153
+ resolveRedirect,
154
+ resumePurchase,
155
+ showCheckoutLoader,
156
+ targetLicenseId,
157
+ upgradeVariation,
158
+ watchForTakeover,
159
+ withoutHandshakeParams
160
+ } from "@moonbase.sh/storefront-api";
161
+ import { v4 as uuidv4 } from "uuid";
162
+ var wrapperId = "moonbase-checkout-wrapper";
163
+ function checkoutInProgress() {
164
+ return typeof window !== "undefined" && !!document.getElementById(wrapperId);
165
+ }
166
+ function waitForCheckoutClose(onClose) {
167
+ return new Promise((resolve) => window.addEventListener("moonbase-checkout-closed", (event) => {
168
+ onClose == null ? void 0 : onClose();
169
+ const { detail } = event;
170
+ resolve({ next: detail.intent, completed: detail.completed, redirected: false });
171
+ }, { once: true }));
172
+ }
173
+ function checkoutReturnUrl(returnUrl) {
174
+ return withoutHandshakeParams(new URL(returnUrl != null ? returnUrl : currentPageUrl(), document.baseURI).href);
175
+ }
176
+ function lineQuantity(quantity) {
177
+ const parsed = Math.trunc(Number(quantity));
178
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
179
+ }
180
+ async function checkout(storefront, items, options = {}) {
181
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
182
+ if (checkoutInProgress())
183
+ return waitForCheckoutClose();
184
+ const redirect = resolveRedirect(options.redirect);
185
+ const lines = [];
186
+ for (const { item, ...line } of items) {
187
+ const licenseId = item.type === "Product" ? targetLicenseId(line.targetLicenseId) : void 0;
188
+ const variation = item.type === "Product" && licenseId ? upgradeVariation(item, licenseId, line.variation) : (_a = line.variation) != null ? _a : item.defaultVariation;
189
+ if (!variation)
190
+ throw new Error("Added item does not have a default variation, and none have been specified");
191
+ const quantity = licenseId ? 1 : lineQuantity(line.quantity);
192
+ const id = lineItemId(item.type, item.id, variation.id, licenseId);
193
+ if (licenseId && lines.some((l) => l.type === "Product" && l.targetLicenseId === licenseId))
194
+ continue;
195
+ if (item.type === "Bundle") {
196
+ lines.push({
197
+ id,
198
+ type: "Bundle",
199
+ bundleId: item.id,
200
+ bundle: item,
201
+ quantity,
202
+ variation,
203
+ variationId: variation.id,
204
+ price: variation.price,
205
+ appliedDiscount: variation.discount
206
+ });
207
+ } else if (item.type === "Product") {
208
+ lines.push({
209
+ id,
210
+ type: "Product",
211
+ productId: item.id,
212
+ product: item,
213
+ quantity,
214
+ variation,
215
+ variationId: variation.id,
216
+ price: variation.price,
217
+ appliedDiscount: variation.discount,
218
+ ...licenseId ? { targetLicenseId: licenseId } : {}
219
+ });
220
+ } else {
221
+ throw new MoonbaseError("Invalid input", `Could not handle item of type '${item.type}'`);
222
+ }
223
+ }
224
+ const userId = (_c = (_b = storefront.getState().user) == null ? void 0 : _b.id) != null ? _c : null;
225
+ showCheckoutLoader();
226
+ try {
227
+ const returnUrl = checkoutReturnUrl(options.returnUrl);
228
+ const pushOrder = (id) => storefront.client.orders.pushContent({
229
+ id,
230
+ currency: storefront.getState().catalog.suggestedCurrency,
231
+ items: lines
232
+ }, {
233
+ // Always sent. A redirected buyer has to come back for the storefront to report the completed
234
+ // checkout.
235
+ returnUrl,
236
+ // Saves minting a checkout login token for a hosted checkout URL that is about to be stripped.
237
+ embedded: !redirect
238
+ }, storefront.hasUtmOrReferrer ? storefront.getState().utm : void 0, storefront.adSignals());
239
+ let resumed = await resumePurchase(storefront.client, userId, options.couponCode);
240
+ let order;
241
+ try {
242
+ order = await pushOrder((_d = resumed == null ? void 0 : resumed.orderId) != null ? _d : uuidv4());
243
+ } catch (err) {
244
+ if (!resumed || !isClosedOrderRefusal(err))
245
+ throw err;
246
+ forgetPurchase2(resumed.orderId);
247
+ resumed = null;
248
+ order = await pushOrder(uuidv4());
249
+ }
250
+ await recordCheckoutGroups(storefront.client, order.id, options.groupIds);
251
+ let ownCoupon = (_e = resumed == null ? void 0 : resumed.couponCode) != null ? _e : null;
252
+ if (options.couponCode && !hasCoupon(order, options.couponCode)) {
253
+ try {
254
+ const withCoupon = await storefront.client.orders.addCouponCode(order.id, options.couponCode);
255
+ order = {
256
+ ...withCoupon,
257
+ checkoutUrl: (_f = withCoupon.checkoutUrl) != null ? _f : order.checkoutUrl,
258
+ hostedCheckoutUrl: (_g = withCoupon.hostedCheckoutUrl) != null ? _g : order.hostedCheckoutUrl,
259
+ embeddedCheckoutUrl: (_h = withCoupon.embeddedCheckoutUrl) != null ? _h : order.embeddedCheckoutUrl
260
+ };
261
+ ownCoupon = options.couponCode;
262
+ } catch (error) {
263
+ (_i = options.onCouponRejected) == null ? void 0 : _i.call(options, options.couponCode, error);
264
+ }
265
+ }
266
+ rememberPurchase(order.id, userId, ownCoupon);
267
+ if (!checkoutInProgress())
268
+ return { next: void 0, completed: false, redirected: false };
269
+ order.items = storefront.enrichLineItems(order.items);
270
+ const priced = CartUtils.total(storefront.getState().catalog, order, order.currency);
271
+ window.dispatchEvent(new CustomEvent("moonbase-checkout-initiated", {
272
+ detail: { order, total: { amount: priced.amount, currency: priced.currency } }
273
+ }));
274
+ const hostedUrl = redirect ? buildHostedRedirectUrl(order, returnUrl) : null;
275
+ if (hostedUrl) {
276
+ window.location.href = hostedUrl;
277
+ return { next: void 0, completed: false, redirected: true };
278
+ }
279
+ if (!order.embeddedCheckoutUrl)
280
+ throw new Error("No checkout URL found");
281
+ const stopWatching = watchForTakeover(order.id, closeCheckout);
282
+ const closed = waitForCheckoutClose(stopWatching);
283
+ mountCheckout(order.embeddedCheckoutUrl);
284
+ return await closed;
285
+ } catch (err) {
286
+ hideCheckoutLoader();
287
+ throw err;
288
+ }
289
+ }
290
+
291
+ // src/order.ts
292
+ import { CartUtils as CartUtils2, OfferUtils, OrderStatus, resolveDisplayCurrency } from "@moonbase.sh/storefront-api";
293
+ import { v4 as uuidv42 } from "uuid";
294
+ function emptyCatalog() {
295
+ return {
296
+ suggestedCurrency: "",
297
+ enabledCurrencies: [],
298
+ bundles: [],
299
+ products: [],
300
+ offers: [],
301
+ promotions: []
302
+ };
303
+ }
304
+ function newOrder(currency = "", items = []) {
305
+ return {
306
+ id: uuidv42(),
307
+ status: OrderStatus.Open,
308
+ currency,
309
+ items,
310
+ couponsApplied: []
311
+ };
312
+ }
313
+ function conditionContext(catalog, order) {
314
+ return CartUtils2.conditionContext(catalog, order, resolveDisplayCurrency(order, catalog));
315
+ }
316
+ function enrichLineItems(catalog, order, lineItems = order.items) {
317
+ const context = conditionContext(catalog, order);
318
+ return lineItems.map((item) => {
319
+ var _a, _b, _c, _d;
320
+ const offer = (_a = catalog.offers) == null ? void 0 : _a.find((o) => o.id === item.offerId);
321
+ if (item.type === "Product") {
322
+ const product = catalog.products.find((p) => p.id === item.productId);
323
+ let variation2 = CartUtils2.productLineVariation(product, item.variationId, item.targetLicenseId);
324
+ if (offer && variation2 && OfferUtils.eligible(offer, context))
325
+ variation2 = OfferUtils.applyToVariation(offer, variation2);
326
+ return {
327
+ ...item,
328
+ product,
329
+ variation: variation2,
330
+ price: variation2 == null ? void 0 : variation2.price,
331
+ appliedDiscount: (_b = variation2 == null ? void 0 : variation2.discount) != null ? _b : item.appliedDiscount
332
+ };
333
+ }
334
+ const bundle = catalog.bundles.find((b) => b.id === item.bundleId);
335
+ let variation = (_c = bundle == null ? void 0 : bundle.variations) == null ? void 0 : _c.find((v) => v.id === item.variationId);
336
+ if (offer && variation && OfferUtils.eligible(offer, context))
337
+ variation = OfferUtils.applyToVariation(offer, variation);
338
+ return {
339
+ ...item,
340
+ bundle,
341
+ variation,
342
+ price: variation == null ? void 0 : variation.price,
343
+ appliedDiscount: (_d = variation == null ? void 0 : variation.discount) != null ? _d : item.appliedDiscount
344
+ };
345
+ });
346
+ }
347
+ function withBestCartOffer(catalog, order) {
348
+ if (order.status !== OrderStatus.Open)
349
+ return order;
350
+ const best = CartUtils2.bestCartOffer(catalog, order, resolveDisplayCurrency(order, catalog));
351
+ if ((best == null ? void 0 : best.id) === order.offerId)
352
+ return order;
353
+ return { ...order, offerId: best == null ? void 0 : best.id };
354
+ }
355
+ function draftOf(order) {
356
+ return { ...order, items: order.items.map((item) => ({ ...item })) };
357
+ }
358
+ function keepUnchangedLines(before, after) {
359
+ return after.map((line) => {
360
+ const previous = before.find((item) => item.id === line.id);
361
+ return previous && shallowEqual(previous, line) ? previous : line;
362
+ });
363
+ }
364
+ function shallowEqual(a, b) {
365
+ const aKeys = Object.keys(a);
366
+ const bKeys = Object.keys(b);
367
+ return aKeys.length === bKeys.length && aKeys.every((key) => Object.is(a[key], b[key]));
368
+ }
369
+
370
+ // src/cart.ts
371
+ function createCart(storefront, internals) {
372
+ function change(edit) {
373
+ const before = storefront.getState().order;
374
+ const draft = draftOf(before);
375
+ edit(draft);
376
+ pruneIneligibleOffers(draft);
377
+ applyEligibleItemOffers(draft);
378
+ const settled = withBestCartOffer(storefront.getState().catalog, draft);
379
+ internals.setOrder({ ...settled, items: keepUnchangedLines(before.items, settled.items) });
380
+ storefront.pushOrderContent();
381
+ }
382
+ function pruneIneligibleOffers(draft) {
383
+ var _a;
384
+ const catalog = storefront.getState().catalog;
385
+ const context = conditionContext(catalog, draft);
386
+ for (const item of draft.items) {
387
+ if (!item.offerId)
388
+ continue;
389
+ const offer = (_a = catalog.offers) == null ? void 0 : _a.find((o) => o.id === item.offerId);
390
+ if (!offer || !OfferUtils2.eligible(offer, context))
391
+ item.offerId = void 0;
392
+ }
393
+ }
394
+ function applyEligibleItemOffers(draft) {
395
+ if (!storefront.autoApplyItemOffers || draft.status !== OrderStatus2.Open)
396
+ return;
397
+ const catalog = storefront.getState().catalog;
398
+ const context = conditionContext(catalog, draft);
399
+ for (const { itemId, offerId } of CartUtils3.assignItemOffers(catalog, draft, resolveDisplayCurrency2(draft, catalog), context)) {
400
+ const item = draft.items.find((i) => i.id === itemId);
401
+ if (item)
402
+ item.offerId = offerId;
403
+ }
404
+ }
405
+ function productLineRecurrence(lineItem) {
406
+ var _a, _b, _c, _d;
407
+ if (lineItem.type !== "Product")
408
+ return void 0;
409
+ return (_d = (_c = lineItem.variation) != null ? _c : (_b = (_a = storefront.getState().catalog.products.find((p) => p.id === lineItem.productId)) == null ? void 0 : _a.variations) == null ? void 0 : _b.find((v) => v.id === lineItem.variationId)) == null ? void 0 : _d.recurrence;
410
+ }
411
+ function addReplacedBundleProducts(draft, cartItem, insertAt) {
412
+ var _a, _b, _c;
413
+ if (cartItem.type !== "Bundle" || !((_a = cartItem.replaced) == null ? void 0 : _a.length))
414
+ return;
415
+ const catalog = storefront.getState().catalog;
416
+ let cursor = insertAt;
417
+ for (const composite of cartItem.replaced) {
418
+ const [productId, variationId] = composite.split("/");
419
+ const product = catalog.products.find((p) => p.id === productId);
420
+ const variation = (_b = product == null ? void 0 : product.variations) == null ? void 0 : _b.find((v) => v.id === variationId);
421
+ const alreadyInCart = draft.items.some((i) => {
422
+ var _a2;
423
+ return i.type === "Product" && i.productId === productId && !i.targetLicenseId && ((_a2 = productLineRecurrence(i)) == null ? void 0 : _a2.type) === (variation == null ? void 0 : variation.recurrence.type);
424
+ });
425
+ if (!product || !variation || alreadyInCart)
426
+ continue;
427
+ const line = {
428
+ id: lineItemId2("Product", product.id, variationId),
429
+ type: "Product",
430
+ productId: product.id,
431
+ product,
432
+ quantity: 1,
433
+ variation,
434
+ variationId,
435
+ price: variation.price,
436
+ appliedDiscount: variation.discount,
437
+ isDefaultVariation: variation.id === ((_c = product.defaultVariation) == null ? void 0 : _c.id)
438
+ };
439
+ if (cursor !== void 0)
440
+ draft.items.splice(cursor++, 0, line);
441
+ else
442
+ draft.items.push(line);
443
+ }
444
+ }
445
+ function addToCart(item, variation, offer, options) {
446
+ const licenseId = item.type === "Product" ? targetLicenseId2(options == null ? void 0 : options.targetLicenseId) : void 0;
447
+ const chosen = item.type === "Product" && licenseId ? upgradeVariation2(item, licenseId, variation) : variation != null ? variation : item.defaultVariation;
448
+ if (!chosen)
449
+ throw new Error("Added item does not have a default variation, and none have been specified");
450
+ const id = lineItemId2(item.type, item.id, chosen.id, licenseId);
451
+ change((draft) => {
452
+ var _a, _b, _c, _d, _e, _f;
453
+ if (licenseId) {
454
+ const index = draft.items.findIndex((i) => {
455
+ var _a2;
456
+ return i.type === "Product" && i.id !== id && ((_a2 = i.targetLicenseId) == null ? void 0 : _a2.toLowerCase()) === licenseId;
457
+ });
458
+ if (index >= 0)
459
+ draft.items.splice(index, 1);
460
+ }
461
+ const existing = draft.items.find((i) => i.id === id);
462
+ if (existing) {
463
+ if (existing.type === "Product" && existing.targetLicenseId)
464
+ existing.quantity = 1;
465
+ else
466
+ existing.quantity += 1;
467
+ (_a = existing.offerId) != null ? _a : existing.offerId = offer == null ? void 0 : offer.id;
468
+ (_b = existing.variation) != null ? _b : existing.variation = chosen;
469
+ if (!existing.price)
470
+ existing.price = chosen.price;
471
+ if (!existing.appliedDiscount && chosen.discount)
472
+ existing.appliedDiscount = chosen.discount;
473
+ if (existing.type === "Product" && item.type === "Product")
474
+ (_c = existing.product) != null ? _c : existing.product = item;
475
+ if (existing.type === "Bundle" && item.type === "Bundle")
476
+ (_d = existing.bundle) != null ? _d : existing.bundle = item;
477
+ return;
478
+ }
479
+ if (item.type === "Bundle") {
480
+ const line = {
481
+ id,
482
+ type: "Bundle",
483
+ bundleId: item.id,
484
+ bundle: item,
485
+ quantity: 1,
486
+ variation: chosen,
487
+ variationId: chosen.id,
488
+ offerId: offer == null ? void 0 : offer.id,
489
+ price: chosen.price,
490
+ appliedDiscount: chosen.discount,
491
+ isDefaultVariation: chosen.id === ((_e = item.defaultVariation) == null ? void 0 : _e.id)
492
+ };
493
+ if ((options == null ? void 0 : options.bundleBehaviour) === "replace") {
494
+ const recurrenceType = chosen.recurrence.type;
495
+ const replaced = draft.items.filter((i) => {
496
+ var _a2;
497
+ return i.type === "Product" && !i.targetLicenseId && item.products.some((p) => p.included && p.id === i.productId) && ((_a2 = productLineRecurrence(i)) == null ? void 0 : _a2.type) === recurrenceType;
498
+ });
499
+ draft.items = draft.items.filter((i) => !replaced.includes(i));
500
+ line.replaced = replaced.flatMap((i) => i.type === "Product" ? [`${i.productId}/${i.variationId}`] : []);
501
+ }
502
+ draft.items.push(line);
503
+ } else if (item.type === "Product") {
504
+ draft.items.push({
505
+ id,
506
+ type: "Product",
507
+ productId: item.id,
508
+ product: item,
509
+ quantity: 1,
510
+ variation: chosen,
511
+ variationId: chosen.id,
512
+ offerId: offer == null ? void 0 : offer.id,
513
+ price: chosen.price,
514
+ appliedDiscount: chosen.discount,
515
+ isDefaultVariation: chosen.id === ((_f = item.defaultVariation) == null ? void 0 : _f.id),
516
+ ...licenseId ? { targetLicenseId: licenseId } : {}
517
+ });
518
+ } else {
519
+ throw new MoonbaseError2("Invalid input", `Could not handle item of type '${item.type}'`);
520
+ }
521
+ });
522
+ return storefront.getState().order.items.find((i) => i.id === id);
523
+ }
524
+ function setQuantity(cartItem, quantity) {
525
+ var _a;
526
+ if (!storefront.getState().order.items.some((i) => i.id === cartItem.id))
527
+ throw new Error("Cart item not found");
528
+ change((draft) => {
529
+ const index = draft.items.findIndex((i) => i.id === cartItem.id);
530
+ const line = draft.items[index];
531
+ line.quantity = line.type === "Product" && line.targetLicenseId ? Math.min(quantity, 1) : quantity;
532
+ if (line.quantity <= 0) {
533
+ draft.items.splice(index, 1);
534
+ addReplacedBundleProducts(draft, cartItem, index);
535
+ }
536
+ });
537
+ return (_a = storefront.getState().order.items.find((i) => i.id === cartItem.id)) != null ? _a : cartItem;
538
+ }
539
+ function removeFromCart(cartItem) {
540
+ if (!storefront.getState().order.items.some((i) => i.id === cartItem.id))
541
+ return;
542
+ change((draft) => {
543
+ const index = draft.items.findIndex((i) => i.id === cartItem.id);
544
+ draft.items.splice(index, 1);
545
+ addReplacedBundleProducts(draft, cartItem, index);
546
+ });
547
+ }
548
+ async function checkout2(options = {}) {
549
+ if (checkoutInProgress())
550
+ return waitForCheckoutClose();
551
+ const redirect = resolveRedirect2(options.redirect);
552
+ const returnUrl = checkoutReturnUrl(options.returnUrl);
553
+ storefront.reconcileCartOffer();
554
+ const updatedOrder = await storefront.client.orders.pushContent(storefront.getState().order, {
555
+ // Always sent. A redirected buyer has to come back for the storefront to report the completed
556
+ // checkout and clear the cart.
557
+ returnUrl,
558
+ // Saves minting a checkout login token for a hosted checkout URL that is about to be stripped.
559
+ embedded: !redirect
560
+ }, storefront.hasUtmOrReferrer ? storefront.getState().utm : void 0, storefront.adSignals());
561
+ await recordCheckoutGroups2(storefront.client, updatedOrder.id, options.groupIds);
562
+ updatedOrder.items = storefront.enrichLineItems(updatedOrder.items);
563
+ const { catalog, order } = storefront.getState();
564
+ const breakdown = CartUtils3.total(catalog, order, resolveDisplayCurrency2(order, catalog));
565
+ window.dispatchEvent(new CustomEvent("moonbase-checkout-initiated", {
566
+ detail: { order: updatedOrder, total: { amount: breakdown.amount, currency: breakdown.currency } }
567
+ }));
568
+ const hostedUrl = redirect ? buildHostedRedirectUrl2(updatedOrder, returnUrl) : null;
569
+ if (hostedUrl) {
570
+ window.location.href = hostedUrl;
571
+ return { next: void 0, completed: false, redirected: true };
572
+ }
573
+ if (!updatedOrder.embeddedCheckoutUrl)
574
+ throw new Error("No checkout URL found");
575
+ const closed = waitForCheckoutClose();
576
+ mountCheckout2(updatedOrder.embeddedCheckoutUrl);
577
+ return closed;
578
+ }
579
+ return {
580
+ addToCart,
581
+ setQuantity,
582
+ removeFromCart,
583
+ checkout: checkout2,
584
+ removeCartOffer: () => storefront.removeCartOffer()
585
+ };
586
+ }
587
+
588
+ // src/storefront.ts
589
+ var windowEvents = {
590
+ checkoutInitiated: ["moonbase-checkout-initiated", (detail) => [detail.order, detail.total]],
591
+ checkoutBillingDetailsAdded: ["moonbase-checkout-billing-details-updated", (detail) => [detail.order]],
592
+ checkoutPaymentStarted: ["moonbase-checkout-payment-started", (detail) => [detail.order]],
593
+ checkoutPaymentFailed: ["moonbase-checkout-payment-failed", (detail) => [detail.order, detail.error]],
594
+ checkoutCouponApplied: ["moonbase-checkout-coupon-applied", (detail) => [detail.order, detail.code]],
595
+ checkoutCouponRemoved: ["moonbase-checkout-coupon-removed", (detail) => [detail.order, detail.code]],
596
+ checkoutCouponRejected: ["moonbase-checkout-coupon-rejected", (detail) => [detail.code, detail.message]],
597
+ checkoutCompleted: ["moonbase-checkout-completed", (detail) => [detail.order]],
598
+ checkoutClosed: ["moonbase-checkout-closed", (detail) => [detail.intent, detail.completed === true, detail.order]],
599
+ catalogUpdated: ["moonbase-storefront-updated", (detail) => [detail.storefront]],
600
+ sessionEnded: ["moonbase-session-ended", (detail) => [detail.user]]
601
+ };
602
+ function hasUtmOrReferrer(utm) {
603
+ return !!utm && Object.values(utm).some((v) => !!v);
604
+ }
605
+ var _MoonbaseStorefront = class _MoonbaseStorefront {
606
+ constructor(configuration, client, options = {}) {
607
+ this.configuration = configuration;
608
+ this.client = client;
609
+ this.listeners = /* @__PURE__ */ new Set();
610
+ this.refreshOrderAbortController = new AbortController();
611
+ // Catalog refreshes are numbered as they start, and one only lands if no later one has landed first.
612
+ // They overlap: a checkout's billing details and its completion each start one a moment apart, and
613
+ // when the first to start is the last to answer, its catalog is from before the purchase and would
614
+ // put `owned` back to `false`.
615
+ this.catalogRefreshesStarted = 0;
616
+ this.catalogRefreshLanded = 0;
617
+ /** The current state. A new object whenever anything in it changes, and the same one otherwise. */
618
+ this.getState = () => this.state;
619
+ /**
620
+ * The state a server renders with, and so what React hydrates against: the initial catalog, if any,
621
+ * an empty cart and nobody signed in. On the server itself, where there is nothing to hydrate, the
622
+ * current state, so a page that awaits `refreshCatalog()` before rendering renders with it.
623
+ */
624
+ this.getServerState = () => typeof window === "undefined" ? this.state : this.serverState;
625
+ /** Calls `listener` after every change to the state, and returns the function that stops it. */
626
+ this.subscribe = (listener) => {
627
+ this.listeners.add(listener);
628
+ return () => {
629
+ this.listeners.delete(listener);
630
+ };
631
+ };
632
+ var _a;
633
+ this.autoApplyItemOffers = (_a = options.autoApplyItemOffers) != null ? _a : false;
634
+ this.catalogLoadedPromise = new Promise((resolve) => this.resolveCatalogLoaded = resolve);
635
+ this.userLoadedPromise = new Promise((resolve) => this.resolveUserLoaded = resolve);
636
+ this.auth = createAuth(this, { setUser: (user2) => this.setState({ user: user2 }) });
637
+ this.cart = createCart(this, { setOrder: (order2) => this.setState({ order: order2 }) });
638
+ const initialCatalog = options.initialCatalog ? _MoonbaseStorefront.normalizeCatalog(options.initialCatalog) : emptyCatalog();
639
+ this.serverState = {
640
+ catalog: initialCatalog,
641
+ catalogLoaded: !!options.initialCatalog,
642
+ closed: false,
643
+ order: newOrder(initialCatalog.suggestedCurrency),
644
+ user: null,
645
+ userLoaded: false,
646
+ utm: void 0
647
+ };
648
+ if (typeof window === "undefined") {
649
+ this.state = this.serverState;
650
+ if (this.serverState.catalogLoaded)
651
+ this.resolveCatalogLoaded();
652
+ this.resolveUserLoaded();
653
+ return;
654
+ }
655
+ window.addEventListener("storage", (event) => this.handleStorageUpdate(event));
656
+ this.client.tokenStore.onSessionEnded(() => this.endSession());
657
+ const urlParams = new URLSearchParams(window.location.search);
658
+ const fresh = {
659
+ referrer: parseOffSiteReferrer(window.document.referrer, window.location.origin),
660
+ source: urlParams.get("utm_source") || void 0,
661
+ medium: urlParams.get("utm_medium") || void 0,
662
+ campaign: urlParams.get("utm_campaign") || void 0,
663
+ term: urlParams.get("utm_term") || void 0,
664
+ content: urlParams.get("utm_content") || void 0,
665
+ id: urlParams.get("utm_id") || void 0,
666
+ gadSource: urlParams.get("gad_source") || void 0,
667
+ gadCampaignId: urlParams.get("gad_campaignid") || void 0,
668
+ gclid: urlParams.get("gclid") || void 0,
669
+ gbraid: urlParams.get("gbraid") || void 0,
670
+ wbraid: urlParams.get("wbraid") || void 0,
671
+ fbclid: urlParams.get("fbclid") || void 0,
672
+ msclkid: urlParams.get("msclkid") || void 0,
673
+ ttclid: urlParams.get("ttclid") || void 0
674
+ };
675
+ fresh.adClicks = adClicksOf(fresh);
676
+ this.attributionConsentSetting = copyConsent(configuration.attributionConsent);
677
+ const sessionRaw = readStorage(_MoonbaseStorefront.utmKey, "session");
678
+ const sessionCached = _MoonbaseStorefront.parseCachedUtm(sessionRaw);
679
+ const cached = sessionCached != null ? sessionCached : configuration.persistUtm && this.attributionConsent ? _MoonbaseStorefront.parseCachedUtm(readStorage(_MoonbaseStorefront.utmKey, "local")) : void 0;
680
+ const full = resolveUtm(cached, fresh);
681
+ this.arrival = full;
682
+ const resolved = this.consentedUtm(full);
683
+ const sessionLanding = parseLanding(readStorage(_MoonbaseStorefront.arrivalKey, "session"));
684
+ if (!hasCampaignData(full))
685
+ this.landing = void 0;
686
+ else if (full !== fresh)
687
+ this.landing = full === sessionCached ? sessionLanding : parseLanding(readStorage(_MoonbaseStorefront.arrivalKey, "local"));
688
+ else if (sessionCached && sessionLanding && isSameArrival(sessionCached, fresh))
689
+ this.landing = sessionLanding;
690
+ else
691
+ this.landing = landingHere();
692
+ const refused = grantsClickIds(this.attributionConsentSetting) === false;
693
+ if (hasUtmOrReferrer(resolved) && (full !== sessionCached || refused) && JSON.stringify(resolved) !== sessionRaw)
694
+ writeStorage(_MoonbaseStorefront.utmKey, JSON.stringify(resolved), "session");
695
+ if (this.landing !== sessionLanding)
696
+ this.storeLanding("session");
697
+ if (configuration.persistUtm && this.attributionConsent && hasUtmOrReferrer(resolved)) {
698
+ writeStorage(_MoonbaseStorefront.utmKey, JSON.stringify(resolved), "local");
699
+ this.storeLanding("local");
700
+ } else if (configuration.persistUtm && refused) {
701
+ removeStorage(_MoonbaseStorefront.utmKey, "local");
702
+ removeStorage(_MoonbaseStorefront.arrivalKey, "local");
703
+ }
704
+ const cachedCatalogJson = readStorage(_MoonbaseStorefront.storefrontKey);
705
+ const cachedCatalog = cachedCatalogJson ? _MoonbaseStorefront.parseCachedCatalog(cachedCatalogJson) : null;
706
+ const catalog = cachedCatalog != null ? cachedCatalog : this.serverState.catalog;
707
+ const cachedOrder = _MoonbaseStorefront.parseCachedOrder(readStorage(_MoonbaseStorefront.sessionKey));
708
+ const order = cachedOrder != null ? cachedOrder : newOrder();
709
+ let user = null;
710
+ if (this.client.tokenStore.user) {
711
+ try {
712
+ user = schemas2.identity.userSchema.parse(this.client.tokenStore.user);
713
+ } catch (err) {
714
+ console.warn("Could not read the stored Moonbase user, signing out", err);
715
+ this.client.tokenStore.clear();
716
+ }
717
+ }
718
+ this.state = {
719
+ catalog,
720
+ catalogLoaded: !!cachedCatalog || this.serverState.catalogLoaded,
721
+ closed: false,
722
+ // The order's currency starts from the catalog's suggestion, so the first paint uses the same
723
+ // source of truth the refreshes settle on, rather than a possibly stale one stored with the cart.
724
+ order: { ...order, currency: resolveDisplayCurrency3(order, catalog) },
725
+ user,
726
+ userLoaded: false,
727
+ utm: resolved
728
+ };
729
+ if (this.state.catalogLoaded)
730
+ this.resolveCatalogLoaded();
731
+ if (cachedOrder) {
732
+ void this.refreshOrder();
733
+ } else if (this.hasUtmOrReferrer && this.attributionConsent) {
734
+ this.pushOrderContent();
735
+ }
736
+ pruneRememberedPurchase();
737
+ this.refreshInBackground();
738
+ const intent = urlParams.get("mb_intent");
739
+ const endpoint = urlParams.get("mb_endpoint");
740
+ if ((intent === "checkout" || intent === "update_subscription") && urlParams.get("mb_complete") && endpoint) {
741
+ const parameters = Object.fromEntries([...urlParams.entries()].filter(([key]) => !key.startsWith("mb_")));
742
+ const finalEndpoint = new URL(decodeURIComponent(endpoint));
743
+ for (const [key, value] of Object.entries(parameters))
744
+ finalEndpoint.searchParams.append(key, value);
745
+ if (intent === "checkout")
746
+ mountCheckout3(finalEndpoint.toString());
747
+ else
748
+ mountSubscription(finalEndpoint.toString());
749
+ window.history.replaceState(window.history.state, "", withoutHandshakeParams2(window.location.href));
750
+ }
751
+ window.addEventListener("moonbase-checkout-billing-details-updated", () => {
752
+ this.refreshInBackground();
753
+ });
754
+ window.addEventListener("moonbase-checkout-completed", (event) => {
755
+ const completed = event.detail.order;
756
+ if (completed.id === this.state.order.id)
757
+ this.resetOrder();
758
+ forgetPurchase3(completed.id);
759
+ this.refreshInBackground();
760
+ });
761
+ }
762
+ /**
763
+ * Calls `callback` each time the storefront reports `event`, and returns the function that stops it.
764
+ * In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
765
+ */
766
+ on(event, callback) {
767
+ if (typeof window === "undefined")
768
+ return () => {
769
+ };
770
+ const [name, read] = windowEvents[event];
771
+ const listener = (e) => callback(...read(e.detail));
772
+ window.addEventListener(name, listener);
773
+ return () => window.removeEventListener(name, listener);
774
+ }
775
+ get hasUtm() {
776
+ const utm = this.state.utm;
777
+ return !!utm && !!(utm.source || utm.medium || utm.campaign || utm.term || utm.content || utm.id || utm.gadSource || utm.gadCampaignId);
778
+ }
779
+ get hasUtmOrReferrer() {
780
+ return hasUtmOrReferrer(this.state.utm);
781
+ }
782
+ /** Whether the storefront may keep and send ad click IDs and record an arrival before any action. */
783
+ get attributionConsent() {
784
+ var _a;
785
+ return (_a = grantsClickIds(this.attributionConsentSetting)) != null ? _a : this.storeAllowsAttribution === true;
786
+ }
787
+ /**
788
+ * Buys these items straight away, without touching the cart: the "Buy now" path. Opens the checkout
789
+ * over the page, or on a phone sends the buyer to Moonbase's own checkout page (see `redirect`), and
790
+ * settles once the overlay closes or the page is on its way.
791
+ */
792
+ checkout(items, options = {}) {
793
+ return checkout(this, items, options);
794
+ }
795
+ /** Closes the checkout overlay, if one is open. */
796
+ closeCheckout() {
797
+ closeCheckout2();
798
+ }
799
+ /**
800
+ * Say whether the visitor has agreed to marketing cookies, typically from a cookie banner's callback.
801
+ * `StorefrontOptions.attributionConsent` sets where it starts. Until either says, the storefront
802
+ * follows the store's own setting in Moonbase, which the catalog reports for this visitor once it
803
+ * loads. A banner that asks for Google's two parts separately can pass `{ adUserData, adPersonalization }`,
804
+ * which counts as granted here when `adUserData` is.
805
+ *
806
+ * Granting it adds the ad click IDs the visitor arrived with in this tab (`gclid`, `fbclid` and the
807
+ * rest) to `utm`, and records the arrival on a new cart if there is none yet, so a visitor who leaves
808
+ * and comes back to buy is still put down to it. Withdrawing it drops the click IDs from `utm` and the
809
+ * browser's storage again. What has already been sent stays with the order.
810
+ */
811
+ setAttributionConsent(granted) {
812
+ const before = this.attributionConsent;
813
+ this.attributionConsentSetting = copyConsent(granted);
814
+ this.attributionConsentChanged(before);
815
+ if (grantsClickIds(this.attributionConsentSetting) === false && typeof window !== "undefined") {
816
+ if (this.hasUtmOrReferrer)
817
+ writeStorage(_MoonbaseStorefront.utmKey, JSON.stringify(this.state.utm), "session");
818
+ if (this.configuration.persistUtm) {
819
+ removeStorage(_MoonbaseStorefront.utmKey, "local");
820
+ removeStorage(_MoonbaseStorefront.arrivalKey, "local");
821
+ }
822
+ }
823
+ }
824
+ /**
825
+ * What the storefront's requests say of the visit for ad measurement, beside `utm`: what the site last
826
+ * reported of the visitor's consent, left out until it says, and when and on which page the visit's
827
+ * tagged arrival landed, left out for a visit without tags.
828
+ */
829
+ adSignals() {
830
+ const landing = hasCampaignData(this.state.utm) ? this.landing : void 0;
831
+ return {
832
+ consent: copyConsent(this.attributionConsentSetting),
833
+ arrivedAt: landing == null ? void 0 : landing.arrivedAt,
834
+ landingPage: landing == null ? void 0 : landing.landingPage
835
+ };
836
+ }
837
+ /** Asks Moonbase who is signed in. `state.user` is null when nobody is, or the session has run out. */
838
+ async refreshUser() {
839
+ const requested = this.client.tokenStore.user;
840
+ try {
841
+ const user = await this.client.identity.get();
842
+ this.setState({ user, userLoaded: true });
843
+ } catch (err) {
844
+ const stored = this.client.tokenStore.user;
845
+ if (stored !== null && stored !== requested) {
846
+ this.setState({ userLoaded: true });
847
+ return this.state.user;
848
+ }
849
+ if (!(err instanceof NotAuthenticatedError || err instanceof StoreClosedError))
850
+ console.error("Could not load user", err);
851
+ this.setState({ user: null, userLoaded: true });
852
+ }
853
+ return this.state.user;
854
+ }
855
+ /** Asks Moonbase for the catalog again, for this visitor and whoever is signed in. */
856
+ async refreshCatalog() {
857
+ const refresh = ++this.catalogRefreshesStarted;
858
+ let latest;
859
+ try {
860
+ latest = await this.client.storefront.get(this.hasUtmOrReferrer ? this.state.utm : void 0);
861
+ } catch (err) {
862
+ if (!(err instanceof StoreClosedError))
863
+ throw err;
864
+ this.closeStore();
865
+ return this.state.catalog;
866
+ }
867
+ if (refresh < this.catalogRefreshLanded || !latest)
868
+ return this.state.catalog;
869
+ this.catalogRefreshLanded = refresh;
870
+ writeStorage(_MoonbaseStorefront.storefrontKey, JSON.stringify(latest));
871
+ const current = this.state.order;
872
+ const order = { ...current, currency: resolveDisplayCurrency3(current, latest) };
873
+ order.items = enrichLineItems(latest, order);
874
+ const withOffer = withBestCartOffer(latest, order);
875
+ this.setState({ catalog: latest, catalogLoaded: true, order: withOffer });
876
+ if (withOffer !== order && withOffer.items.length > 0)
877
+ this.pushOrderContent();
878
+ const consentedBefore = this.attributionConsent;
879
+ this.storeAllowsAttribution = latest.cookieConsentRequired === false;
880
+ this.attributionConsentChanged(consentedBefore);
881
+ if (typeof window !== "undefined")
882
+ window.dispatchEvent(new CustomEvent("moonbase-storefront-updated", { detail: { storefront: latest } }));
883
+ return latest;
884
+ }
885
+ /**
886
+ * Saves the cart in this browser and sends it to Moonbase, half a second after the last change, so a
887
+ * buyer pressing "+" five times sends one request.
888
+ */
889
+ pushOrderContent() {
890
+ writeStorage(_MoonbaseStorefront.sessionKey, JSON.stringify(this.state.order));
891
+ this.refreshOrderAbortController.abort();
892
+ this.refreshOrderAbortController = new AbortController();
893
+ const pushed = this.state.order;
894
+ clearTimeout(this.pushTimeout);
895
+ this.pushTimeout = setTimeout(() => {
896
+ const latest = this.state.order;
897
+ const order = latest.id === pushed.id ? latest : pushed;
898
+ this.client.orders.pushContent(order, void 0, this.hasUtmOrReferrer ? this.state.utm : void 0, this.adSignals()).catch((err) => console.warn("Could not save the Moonbase cart", err));
899
+ }, 500);
900
+ }
901
+ /**
902
+ * Starts a new, empty cart, or with `keepItems` a new cart holding the same lines, under a new ID.
903
+ * Coupons are not carried over: they are checked again for each order and customer.
904
+ */
905
+ resetOrder(opts) {
906
+ var _a;
907
+ const keep = (_a = opts == null ? void 0 : opts.keepItems) != null ? _a : false;
908
+ const order = newOrder(this.state.catalog.suggestedCurrency || "", keep ? this.state.order.items : []);
909
+ this.setState({ order });
910
+ if (keep && order.items.length > 0)
911
+ writeStorage(_MoonbaseStorefront.sessionKey, JSON.stringify(order));
912
+ else
913
+ removeStorage(_MoonbaseStorefront.sessionKey);
914
+ }
915
+ /** Takes the billing details off the cart's order in Moonbase, as a buyer leaving it would want. */
916
+ async surrenderOrder() {
917
+ try {
918
+ await this.client.orders.removeBillingDetails(this.state.order.id);
919
+ } catch (err) {
920
+ if (err instanceof NotFoundError)
921
+ return;
922
+ console.warn("Could not surrender order:", err);
923
+ }
924
+ }
925
+ /** The lines with their products, bundles and prices from the current catalog. */
926
+ enrichLineItems(lineItems, order = this.state.order) {
927
+ return enrichLineItems(this.state.catalog, order, lineItems);
928
+ }
929
+ /** The context an offer's condition is judged against: the cart, unless another order is given. */
930
+ offerConditionContext(order = this.state.order) {
931
+ return conditionContext(this.state.catalog, order);
932
+ }
933
+ /** Puts the best cart offer the cart qualifies for on it, returning whether that changed anything. */
934
+ reconcileCartOffer() {
935
+ const order = withBestCartOffer(this.state.catalog, this.state.order);
936
+ if (order === this.state.order)
937
+ return false;
938
+ this.setState({ order });
939
+ return true;
940
+ }
941
+ /**
942
+ * Takes the cart offer off the order without sending the cart again. Cart offers apply themselves,
943
+ * but a page driving the cart itself may want to.
944
+ */
945
+ async removeCartOffer() {
946
+ let order = this.state.order;
947
+ if (order.status === OrderStatus3.Open && order.offerId) {
948
+ order = { ...order, offerId: void 0 };
949
+ this.setState({ order });
950
+ }
951
+ writeStorage(_MoonbaseStorefront.sessionKey, JSON.stringify(order));
952
+ await this.client.orders.removeOffer(order.id);
953
+ }
954
+ setState(patch) {
955
+ const keys = Object.keys(patch);
956
+ if (keys.every((key) => Object.is(this.state[key], patch[key])))
957
+ return;
958
+ this.state = { ...this.state, ...patch };
959
+ if (this.state.catalogLoaded)
960
+ this.resolveCatalogLoaded();
961
+ if (this.state.userLoaded)
962
+ this.resolveUserLoaded();
963
+ for (const listener of [...this.listeners])
964
+ listener();
965
+ }
966
+ /**
967
+ * The server refused to renew the buyer's session: they signed out of it elsewhere, changed their
968
+ * password, or stayed away too long. Goes anonymous the way signing out does, and says so, since
969
+ * nobody on this page signed out and the page would otherwise never hear of it.
970
+ */
971
+ endSession() {
972
+ const user = this.state.user;
973
+ if (!user)
974
+ return;
975
+ this.resetOrder({ keepItems: true });
976
+ forgetPurchase3();
977
+ this.setState({ user: null });
978
+ window.dispatchEvent(new CustomEvent("moonbase-session-ended", { detail: { user } }));
979
+ this.refreshInBackground({ user: false });
980
+ }
981
+ refreshInBackground(what = {}) {
982
+ this.refreshCatalog().catch((err) => console.error("Could not load the Moonbase catalog", err));
983
+ if (what.user !== false)
984
+ void this.refreshUser();
985
+ }
986
+ /**
987
+ * The store has closed for good, so nothing kept for it is any use: not the catalog a returning
988
+ * visitor would otherwise be shown, not the cart, and not the buyer's session.
989
+ */
990
+ closeStore() {
991
+ removeStorage(_MoonbaseStorefront.storefrontKey);
992
+ this.setState({ closed: true, catalog: emptyCatalog(), catalogLoaded: true });
993
+ this.resetOrder();
994
+ this.client.tokenStore.clear();
995
+ this.setState({ user: null });
996
+ }
997
+ /** Brings `utm`, its storage and the cart in line with the visitor's consent, when that changed. */
998
+ attributionConsentChanged(before) {
999
+ var _a, _b;
1000
+ const granted = this.attributionConsent;
1001
+ if (typeof window === "undefined" || granted === before)
1002
+ return;
1003
+ if (granted && this.configuration.persistUtm) {
1004
+ const persisted = _MoonbaseStorefront.parseCachedUtm(readStorage(_MoonbaseStorefront.utmKey, "local"));
1005
+ const arrival = resolveUtm(persisted, (_a = this.arrival) != null ? _a : {});
1006
+ if (persisted && arrival === persisted)
1007
+ this.landing = hasCampaignData(persisted) ? parseLanding(readStorage(_MoonbaseStorefront.arrivalKey, "local")) : void 0;
1008
+ this.arrival = arrival;
1009
+ }
1010
+ const resolved = this.consentedUtm((_b = this.arrival) != null ? _b : {});
1011
+ this.setState({ utm: resolved });
1012
+ if (this.hasUtmOrReferrer) {
1013
+ writeStorage(_MoonbaseStorefront.utmKey, JSON.stringify(resolved), "session");
1014
+ this.storeLanding("session");
1015
+ if (granted && this.configuration.persistUtm) {
1016
+ writeStorage(_MoonbaseStorefront.utmKey, JSON.stringify(resolved), "local");
1017
+ this.storeLanding("local");
1018
+ }
1019
+ }
1020
+ if (granted && this.hasUtmOrReferrer && !readStorage(_MoonbaseStorefront.sessionKey))
1021
+ this.pushOrderContent();
1022
+ }
1023
+ /** Keeps `landing` beside the arrival in `kind` storage, or clears what is there for an arrival without one. */
1024
+ storeLanding(kind) {
1025
+ if (this.landing)
1026
+ writeStorage(_MoonbaseStorefront.arrivalKey, JSON.stringify(this.landing), kind);
1027
+ else
1028
+ removeStorage(_MoonbaseStorefront.arrivalKey, kind);
1029
+ }
1030
+ /** `utm` as the storefront may keep and send it: with its ad click IDs only once the visitor agreed. */
1031
+ consentedUtm(utm) {
1032
+ return this.attributionConsent ? utm : withoutClickIds(utm);
1033
+ }
1034
+ handleStorageUpdate(event) {
1035
+ var _a;
1036
+ switch (event.key) {
1037
+ case _MoonbaseStorefront.sessionKey:
1038
+ this.setState({
1039
+ order: (_a = _MoonbaseStorefront.parseCachedOrder(event.newValue)) != null ? _a : newOrder(this.state.catalog.suggestedCurrency || "")
1040
+ });
1041
+ break;
1042
+ case _MoonbaseStorefront.storefrontKey: {
1043
+ const catalog = event.newValue ? _MoonbaseStorefront.parseCachedCatalog(event.newValue) : null;
1044
+ if (catalog)
1045
+ this.setState({ catalog });
1046
+ break;
1047
+ }
1048
+ case _MoonbaseStorefront.utmKey: {
1049
+ const utm = _MoonbaseStorefront.parseCachedUtm(event.newValue);
1050
+ if (utm) {
1051
+ this.arrival = utm;
1052
+ this.setState({ utm: this.consentedUtm(utm) });
1053
+ }
1054
+ break;
1055
+ }
1056
+ case _MoonbaseStorefront.arrivalKey: {
1057
+ const landing = parseLanding(event.newValue);
1058
+ if (landing)
1059
+ this.landing = landing;
1060
+ break;
1061
+ }
1062
+ case TokenStore.storageKey:
1063
+ if (!event.newValue) {
1064
+ const user = this.state.user;
1065
+ this.setState({ user: null });
1066
+ if (user)
1067
+ window.dispatchEvent(new CustomEvent("moonbase-session-ended", { detail: { user } }));
1068
+ } else {
1069
+ try {
1070
+ this.setState({ user: schemas2.identity.userSchema.parse(JSON.parse(event.newValue)) });
1071
+ } catch (err) {
1072
+ console.warn("Could not read the updated Moonbase user", err);
1073
+ }
1074
+ }
1075
+ }
1076
+ }
1077
+ async refreshOrder() {
1078
+ const refreshingId = this.state.order.id;
1079
+ try {
1080
+ const latest = await this.client.orders.get(refreshingId, { abort: this.refreshOrderAbortController.signal });
1081
+ if (this.state.order.id !== refreshingId || !latest)
1082
+ return;
1083
+ if (latest.status !== OrderStatus3.Open) {
1084
+ this.resetOrder();
1085
+ return;
1086
+ }
1087
+ const catalog = this.state.catalog;
1088
+ const adopted = { ...latest, currency: resolveDisplayCurrency3(latest, catalog) };
1089
+ adopted.items = enrichLineItems(catalog, adopted, latest.items);
1090
+ writeStorage(_MoonbaseStorefront.sessionKey, JSON.stringify(adopted));
1091
+ this.setState({ order: adopted });
1092
+ if (this.state.catalogLoaded && this.reconcileCartOffer() && adopted.items.length > 0)
1093
+ this.pushOrderContent();
1094
+ } catch (err) {
1095
+ if (err instanceof NotAuthorizedError && this.state.order.id === refreshingId)
1096
+ this.resetOrder();
1097
+ }
1098
+ }
1099
+ static parseCachedUtm(raw) {
1100
+ if (!raw)
1101
+ return void 0;
1102
+ try {
1103
+ return JSON.parse(raw);
1104
+ } catch (err) {
1105
+ console.warn(`Could not parse cached UTM from ${_MoonbaseStorefront.utmKey}`, err);
1106
+ return void 0;
1107
+ }
1108
+ }
1109
+ static parseCachedOrder(raw) {
1110
+ if (!raw)
1111
+ return null;
1112
+ try {
1113
+ return JSON.parse(raw);
1114
+ } catch (err) {
1115
+ console.warn("Could not read the cart stored in this browser; starting a new one", err);
1116
+ return null;
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Reads a catalog out of local storage, normalising it through the schema, which fills in the
1121
+ * defaults a catalog cached by an older version lacks. One the schema rejects is still used as it
1122
+ * is: a catalog only partly understood beats an empty one while the refresh is in flight. Only
1123
+ * unreadable JSON gives up.
1124
+ */
1125
+ static parseCachedCatalog(json) {
1126
+ let raw;
1127
+ try {
1128
+ raw = JSON.parse(json);
1129
+ } catch (err) {
1130
+ console.warn("Could not parse the cached storefront; starting from an empty one", err);
1131
+ return null;
1132
+ }
1133
+ return _MoonbaseStorefront.normalizeCatalog(raw);
1134
+ }
1135
+ static normalizeCatalog(raw) {
1136
+ const parsed = schemas2.storefront.storefrontSchema.safeParse(raw);
1137
+ return parsed.success ? parsed.data : raw;
1138
+ }
1139
+ };
1140
+ _MoonbaseStorefront.sessionKey = "moonbase_session";
1141
+ _MoonbaseStorefront.storefrontKey = "moonbase_storefront";
1142
+ _MoonbaseStorefront.utmKey = "moonbase_utm";
1143
+ _MoonbaseStorefront.arrivalKey = "moonbase_arrival";
1144
+ var MoonbaseStorefront = _MoonbaseStorefront;
1145
+
1146
+ // src/provider.ts
1147
+ import { createContext, createElement, useContext, useEffect, useRef, useSyncExternalStore } from "react";
1148
+ var StorefrontContext = createContext(null);
1149
+ function StorefrontProvider({ storefront, children }) {
1150
+ return createElement(StorefrontContext.Provider, { value: storefront }, children);
1151
+ }
1152
+ function useStorefront() {
1153
+ const storefront = useContext(StorefrontContext);
1154
+ if (!storefront)
1155
+ throw new Error("No storefront configured: render this inside a <StorefrontProvider>");
1156
+ return storefront;
1157
+ }
1158
+ function useStorefrontState(selector) {
1159
+ const storefront = useStorefront();
1160
+ return useSyncExternalStore(
1161
+ storefront.subscribe,
1162
+ () => selector(storefront.getState()),
1163
+ () => selector(storefront.getServerState())
1164
+ );
1165
+ }
1166
+ function useStorefrontEvent(event, handler) {
1167
+ const storefront = useStorefront();
1168
+ const latest = useRef(handler);
1169
+ useEffect(() => {
1170
+ latest.current = handler;
1171
+ });
1172
+ useEffect(() => storefront.on(event, (...args) => latest.current(...args)), [storefront, event]);
1173
+ }
1174
+
1175
+ // src/hooks/catalog.ts
1176
+ var none = [];
1177
+ function useCatalog() {
1178
+ return useStorefrontState((state) => state.catalog);
1179
+ }
1180
+ function useProducts() {
1181
+ return useStorefrontState((state) => state.catalog.products);
1182
+ }
1183
+ function useProduct(productId) {
1184
+ return useStorefrontState((state) => {
1185
+ var _a;
1186
+ return (_a = state.catalog.products.find((p) => p.id === productId)) != null ? _a : null;
1187
+ });
1188
+ }
1189
+ function useBundles() {
1190
+ return useStorefrontState((state) => state.catalog.bundles);
1191
+ }
1192
+ function useBundle(bundleId) {
1193
+ return useStorefrontState((state) => {
1194
+ var _a;
1195
+ return (_a = state.catalog.bundles.find((b) => b.id === bundleId)) != null ? _a : null;
1196
+ });
1197
+ }
1198
+ function useOffers() {
1199
+ return useStorefrontState((state) => {
1200
+ var _a;
1201
+ return (_a = state.catalog.offers) != null ? _a : none;
1202
+ });
1203
+ }
1204
+ function useOffer(offerId) {
1205
+ return useStorefrontState((state) => {
1206
+ var _a, _b;
1207
+ return (_b = (_a = state.catalog.offers) == null ? void 0 : _a.find((o) => o.id === offerId)) != null ? _b : null;
1208
+ });
1209
+ }
1210
+ function usePromotions() {
1211
+ return useStorefrontState((state) => {
1212
+ var _a;
1213
+ return (_a = state.catalog.promotions) != null ? _a : none;
1214
+ });
1215
+ }
1216
+
1217
+ // src/hooks/offers.ts
1218
+ import { useMemo } from "react";
1219
+
1220
+ // src/offers.ts
1221
+ import { CartUtils as CartUtils4, OfferUtils as OfferUtils3, resolveDisplayCurrency as resolveDisplayCurrency4 } from "@moonbase.sh/storefront-api";
1222
+ function eligibleOffers(catalog, order) {
1223
+ var _a;
1224
+ const context = conditionContext(catalog, order);
1225
+ return ((_a = catalog.offers) != null ? _a : []).filter((o) => OfferUtils3.eligible(o, context) && !offerIsInCart(o, order) && !offerTargetIsInCart(o, order));
1226
+ }
1227
+ function lockedOffers(catalog, order) {
1228
+ var _a;
1229
+ const context = conditionContext(catalog, order);
1230
+ return ((_a = catalog.offers) != null ? _a : []).filter((o) => o.scope !== "Cart" && !offerIsInCart(o, order) && !offerTargetIsInCart(o, order)).map((offer) => ({ offer, progress: OfferUtils3.progress(offer, context) })).filter((locked) => locked.progress !== null && !locked.progress.eligible && locked.progress.unit === "Money" && locked.progress.remaining > 0).sort((a, b) => b.progress.fraction - a.progress.fraction);
1231
+ }
1232
+ function cartOfferState(catalog, order) {
1233
+ var _a, _b;
1234
+ const currency = resolveDisplayCurrency4(order, catalog);
1235
+ const offers = (_a = catalog.offers) != null ? _a : [];
1236
+ if (offers.length === 0 || order.items.length === 0)
1237
+ return null;
1238
+ const context = conditionContext(catalog, order);
1239
+ const breakdown = CartUtils4.total(catalog, order, currency);
1240
+ const applied = breakdown.cartOffer ? { offer: breakdown.cartOffer.offer, saving: breakdown.cartOffer.discount } : null;
1241
+ const candidates = offers.map((offer) => ({ offer, progress: OfferUtils3.progress(offer, context) })).filter((candidate) => candidate.progress !== null && !candidate.progress.eligible && candidate.progress.remaining > 0 && candidate.offer.scope === "Cart").sort((a, b) => b.progress.fraction - a.progress.fraction);
1242
+ const appliedValue = applied ? CartUtils4.cartOfferValue(catalog, order, applied.offer, currency, context) : 0;
1243
+ const next = (_b = applied ? candidates.find((c) => CartUtils4.cartOfferValue(catalog, order, c.offer, currency, context) > appliedValue) : candidates[0]) != null ? _b : null;
1244
+ if (!applied && !next)
1245
+ return null;
1246
+ return { applied, next, subtotal: breakdown.subtotal, currency };
1247
+ }
1248
+ function offerIsInCart(offer, order) {
1249
+ return order.items.some((i) => i.offerId === offer.id);
1250
+ }
1251
+ function offerTargetIsInCart(offer, order) {
1252
+ return OfferUtils3.allTargetsInCart(offer, order.items);
1253
+ }
1254
+
1255
+ // src/hooks/offers.ts
1256
+ function useEligibleOffers() {
1257
+ const catalog = useStorefrontState((state) => state.catalog);
1258
+ const order = useStorefrontState((state) => state.order);
1259
+ return useMemo(() => eligibleOffers(catalog, order), [catalog, order]);
1260
+ }
1261
+ function useLockedOffers() {
1262
+ const catalog = useStorefrontState((state) => state.catalog);
1263
+ const order = useStorefrontState((state) => state.order);
1264
+ return useMemo(() => lockedOffers(catalog, order), [catalog, order]);
1265
+ }
1266
+ function useCartOffer() {
1267
+ const catalog = useStorefrontState((state) => state.catalog);
1268
+ const order = useStorefrontState((state) => state.order);
1269
+ return useMemo(() => cartOfferState(catalog, order), [catalog, order]);
1270
+ }
1271
+
1272
+ // src/hooks/useActivationRequest.ts
1273
+ import { ActivationRequestStatus, NotAuthenticatedError as NotAuthenticatedError2 } from "@moonbase.sh/storefront-api";
1274
+ import { useCallback, useEffect as useEffect2, useState } from "react";
1275
+ var pollInterval = 1500;
1276
+ function useActivationRequest(token) {
1277
+ var _a;
1278
+ const storefront = useStorefront();
1279
+ const userId = useStorefrontState((state) => {
1280
+ var _a2, _b;
1281
+ return (_b = (_a2 = state.user) == null ? void 0 : _a2.id) != null ? _b : null;
1282
+ });
1283
+ const [activationRequest, setActivationRequest] = useState(null);
1284
+ const [fetched, setFetched] = useState(null);
1285
+ const [fulfilling, setFulfilling] = useState(false);
1286
+ const [completing, setCompleting] = useState(false);
1287
+ const [error, setError] = useState(null);
1288
+ const adopt = useCallback((request) => {
1289
+ setActivationRequest(request);
1290
+ if (request.status === ActivationRequestStatus.Fulfilled)
1291
+ setCompleting(true);
1292
+ }, []);
1293
+ const upToDate = !!token && (fetched == null ? void 0 : fetched.token) === token && (fetched.userId === userId || !!((_a = activationRequest == null ? void 0 : activationRequest.licenseEligibility) == null ? void 0 : _a.eligible));
1294
+ useEffect2(() => {
1295
+ if (!token || upToDate)
1296
+ return;
1297
+ let current = true;
1298
+ storefront.client.activationRequests.get(token).then((request) => current && adopt(request)).catch((err) => current && setError(err.message)).finally(() => current && setFetched({ token, userId }));
1299
+ return () => {
1300
+ current = false;
1301
+ };
1302
+ }, [storefront, token, userId, upToDate, adopt]);
1303
+ const requestId = activationRequest == null ? void 0 : activationRequest.id;
1304
+ useEffect2(() => {
1305
+ if (!completing || !requestId)
1306
+ return;
1307
+ let current = true;
1308
+ let timeout;
1309
+ const check = async () => {
1310
+ try {
1311
+ const completed = await storefront.client.activationRequests.isCompleted(requestId);
1312
+ if (!current)
1313
+ return;
1314
+ if (completed) {
1315
+ setActivationRequest((request) => request && { ...request, status: ActivationRequestStatus.Completed });
1316
+ setCompleting(false);
1317
+ return;
1318
+ }
1319
+ } catch (err) {
1320
+ console.warn("Could not check whether the activation has completed", err);
1321
+ }
1322
+ if (current)
1323
+ timeout = setTimeout(check, pollInterval);
1324
+ };
1325
+ void check();
1326
+ return () => {
1327
+ current = false;
1328
+ clearTimeout(timeout);
1329
+ };
1330
+ }, [storefront, completing, requestId]);
1331
+ const fulfillLicense = useCallback(async () => {
1332
+ if (!requestId)
1333
+ return;
1334
+ setFulfilling(true);
1335
+ try {
1336
+ adopt(await storefront.client.activationRequests.fulfillLicense(requestId));
1337
+ setCompleting(true);
1338
+ } finally {
1339
+ setFulfilling(false);
1340
+ }
1341
+ }, [storefront, requestId, adopt]);
1342
+ const fulfillTrial = useCallback(async (newsletterOptIn = false) => {
1343
+ if (!requestId)
1344
+ return;
1345
+ setFulfilling(true);
1346
+ try {
1347
+ const user = storefront.getState().user;
1348
+ if (newsletterOptIn && user && !user.communicationPreferences.newsletterOptIn) {
1349
+ await storefront.auth.update(user.name, user.email, void 0, { ...user.communicationPreferences, newsletterOptIn: true });
1350
+ }
1351
+ adopt(await storefront.client.activationRequests.fulfillTrial(
1352
+ requestId,
1353
+ storefront.hasUtmOrReferrer ? storefront.getState().utm : void 0,
1354
+ storefront.adSignals()
1355
+ ));
1356
+ setCompleting(true);
1357
+ } catch (err) {
1358
+ console.warn("Could not fulfill trial: ", err);
1359
+ setError(err instanceof NotAuthenticatedError2 ? "You need to be signed in to do this" : err.message);
1360
+ } finally {
1361
+ setFulfilling(false);
1362
+ }
1363
+ }, [storefront, requestId, adopt]);
1364
+ const cancel = useCallback(async () => {
1365
+ if (!activationRequest || activationRequest.status === ActivationRequestStatus.Cancelled)
1366
+ return;
1367
+ adopt(await storefront.client.activationRequests.cancel(activationRequest.id));
1368
+ }, [storefront, activationRequest, adopt]);
1369
+ return {
1370
+ activationRequest,
1371
+ loading: !!token && !upToDate,
1372
+ fulfilling,
1373
+ completing,
1374
+ error,
1375
+ isInstalled: (activationRequest == null ? void 0 : activationRequest.status) === ActivationRequestStatus.Completed,
1376
+ fulfillLicense,
1377
+ fulfillTrial,
1378
+ cancel
1379
+ };
1380
+ }
1381
+
1382
+ // src/hooks/useAuth.ts
1383
+ import { useMemo as useMemo2 } from "react";
1384
+ function useAuth() {
1385
+ const storefront = useStorefront();
1386
+ const user = useStorefrontState((state) => state.user);
1387
+ const loaded = useStorefrontState((state) => state.userLoaded);
1388
+ return useMemo2(() => ({ ...storefront.auth, user, loaded }), [storefront, user, loaded]);
1389
+ }
1390
+
1391
+ // src/hooks/useCart.ts
1392
+ import { CartUtils as CartUtils5, resolveDisplayCurrency as resolveDisplayCurrency5 } from "@moonbase.sh/storefront-api";
1393
+ import { useMemo as useMemo3 } from "react";
1394
+ function useCart() {
1395
+ const storefront = useStorefront();
1396
+ const catalog = useStorefrontState((state) => state.catalog);
1397
+ const order = useStorefrontState((state) => state.order);
1398
+ return useMemo3(() => {
1399
+ const currency = resolveDisplayCurrency5(order, catalog);
1400
+ const breakdown = CartUtils5.total(catalog, order, currency);
1401
+ const items = enrichLineItems(catalog, order);
1402
+ return {
1403
+ ...storefront.cart,
1404
+ items,
1405
+ soldOutItems: items.filter((item) => CartUtils5.isSoldOut(catalog, item)),
1406
+ currency,
1407
+ total: { amount: breakdown.amount, currency: breakdown.currency },
1408
+ breakdown,
1409
+ cartOffer: breakdown.cartOffer
1410
+ };
1411
+ }, [storefront, catalog, order]);
1412
+ }
1413
+
1414
+ // src/hooks/useCheckout.ts
1415
+ import { useCallback as useCallback2 } from "react";
1416
+ function useCheckout() {
1417
+ const storefront = useStorefront();
1418
+ return useCallback2((items, options) => storefront.checkout(items, options), [storefront]);
1419
+ }
1420
+
1421
+ // src/hooks/useCommunicationPreferences.ts
1422
+ import { useMemo as useMemo4 } from "react";
1423
+ function useCommunicationPreferences() {
1424
+ const storefront = useStorefront();
1425
+ return useMemo4(() => {
1426
+ const communications = storefront.client.communications;
1427
+ return {
1428
+ subscribe: (input) => communications.subscribe(input, storefront.adSignals()),
1429
+ confirm: (email, token) => communications.confirm(email, token),
1430
+ get: (email, token) => communications.getPreferences(email, token),
1431
+ update: (email, token, preferences) => communications.updatePreferences(email, token, preferences),
1432
+ unsubscribe: (email, token) => communications.unsubscribe(email, token)
1433
+ };
1434
+ }, [storefront]);
1435
+ }
1436
+
1437
+ // src/hooks/useGroups.ts
1438
+ import { useMemo as useMemo5 } from "react";
1439
+ function useGroups() {
1440
+ const storefront = useStorefront();
1441
+ return useMemo5(() => ({ join: (groupId) => storefront.client.groups.join(groupId) }), [storefront]);
1442
+ }
1443
+
1444
+ // src/hooks/useInventory.ts
1445
+ import { useMemo as useMemo6 } from "react";
1446
+
1447
+ // src/inventory.ts
1448
+ import { mountCheckout as mountCheckout4, mountSubscription as mountSubscription2, resolveRedirect as resolveRedirect3, withPriceFormat } from "@moonbase.sh/storefront-api";
1449
+ function createInventory(storefront) {
1450
+ const inventory = storefront.client.inventory;
1451
+ return {
1452
+ getLicenses: (nextUrl) => inventory.licenses.get(nextUrl),
1453
+ getLicenseActivations: (licenseId, nextUrl) => inventory.licenses.getActivations(licenseId, nextUrl),
1454
+ getProduct: (productId, version2) => inventory.products.get(productId, version2),
1455
+ getProductReleases: (productId, nextUrl) => inventory.products.getReleases(productId, nextUrl),
1456
+ getProducts: (nextUrl) => inventory.products.getOwned(nextUrl),
1457
+ getProductLicenses: (productId, nextUrl) => inventory.products.getLicenses(productId, nextUrl),
1458
+ getProductActivations: (productId, nextUrl) => inventory.products.getActivations(productId, nextUrl),
1459
+ revokeActivation: (activation) => inventory.licenses.revokeActivation(activation.licenseId, activation.id),
1460
+ activateProduct: (deviceToken, activationMethod) => inventory.activation.activate(deviceToken, activationMethod),
1461
+ downloadProduct: async (download) => {
1462
+ if (!download.path)
1463
+ throw new Error("Product is not downloadable");
1464
+ window.location.href = await inventory.products.getDownloadUrl(download.path, storefront.adSignals());
1465
+ },
1466
+ getSubscriptions: (nextUrl) => inventory.subscriptions.get(nextUrl),
1467
+ getSubscription: (subscriptionId) => inventory.subscriptions.getById(subscriptionId),
1468
+ cancelSubscription: (subscriptionId, feedback) => inventory.subscriptions.cancel(subscriptionId, feedback),
1469
+ getSubscriptionPlanOptions: (subscriptionId) => inventory.subscriptions.getPlanOptions(subscriptionId),
1470
+ changeSubscriptionPlan: (subscriptionId, variationId) => inventory.subscriptions.changePlan(subscriptionId, variationId),
1471
+ cancelSubscriptionPlanChange: (subscriptionId) => inventory.subscriptions.cancelPlanChange(subscriptionId),
1472
+ renewSubscription: async (subscriptionId, options = {}) => {
1473
+ if (checkoutInProgress())
1474
+ return waitForCheckoutClose();
1475
+ const redirect = resolveRedirect3(options.redirect);
1476
+ const { location: url } = await inventory.subscriptions.renew(subscriptionId, checkoutReturnUrl(options.returnUrl), !redirect);
1477
+ if (redirect) {
1478
+ window.location.href = withPriceFormat(url);
1479
+ return { next: void 0, completed: false, redirected: true };
1480
+ }
1481
+ const closed = waitForCheckoutClose();
1482
+ mountCheckout4(url);
1483
+ return closed;
1484
+ },
1485
+ updateSubscriptionPaymentMethod: async (subscription, options = {}) => {
1486
+ const response = await inventory.subscriptions.getById(subscription.id, {
1487
+ toUpdatePaymentMethod: true,
1488
+ returnUrl: checkoutReturnUrl(options.returnUrl)
1489
+ });
1490
+ window.dispatchEvent(new CustomEvent("moonbase-subscription-payment-method-update-initiated", {
1491
+ detail: { subscription }
1492
+ }));
1493
+ const url = response.embeddedUpdatePaymentUrl;
1494
+ if (!url)
1495
+ throw new Error("No update URL found");
1496
+ return new Promise((resolve) => {
1497
+ window.addEventListener("moonbase-subscription-closed", (event) => {
1498
+ resolve({ completed: event.detail.completed });
1499
+ }, { once: true });
1500
+ mountSubscription2(url);
1501
+ });
1502
+ }
1503
+ };
1504
+ }
1505
+
1506
+ // src/hooks/useInventory.ts
1507
+ function useInventory() {
1508
+ const storefront = useStorefront();
1509
+ return useMemo6(() => createInventory(storefront), [storefront]);
1510
+ }
1511
+
1512
+ // src/hooks/useOrders.ts
1513
+ import { useMemo as useMemo7 } from "react";
1514
+ function useOrders() {
1515
+ const storefront = useStorefront();
1516
+ return useMemo7(() => ({
1517
+ getOrders: (nextUrl) => storefront.client.orders.getHistory(nextUrl),
1518
+ getReceipt: (order) => storefront.client.orders.getReceipt(order.id),
1519
+ downloadReceipt: async (order) => {
1520
+ const receipt = await storefront.client.orders.getReceipt(order.id);
1521
+ const url = URL.createObjectURL(receipt);
1522
+ const link = document.createElement("a");
1523
+ link.href = url;
1524
+ link.download = `Receipt_${order.id}.pdf`;
1525
+ document.body.append(link);
1526
+ link.click();
1527
+ link.remove();
1528
+ setTimeout(() => URL.revokeObjectURL(url), 6e4);
1529
+ }
1530
+ }), [storefront]);
1531
+ }
1532
+
1533
+ // src/hooks/useReviews.ts
1534
+ import { useMemo as useMemo8 } from "react";
1535
+ function useReviews() {
1536
+ const storefront = useStorefront();
1537
+ const enabled = useStorefrontState((state) => !!state.catalog.reviewsEnabled);
1538
+ return useMemo8(() => {
1539
+ const reviews = storefront.client.reviews;
1540
+ return {
1541
+ enabled,
1542
+ getReviews: (productId, filter) => reviews.get(productId, filter),
1543
+ getMoreReviews: (next) => reviews.getMore(next),
1544
+ getMyReview: (productId) => reviews.getMine(productId),
1545
+ saveReview: (productId, review, existing) => existing ? reviews.edit(productId, review) : reviews.submit(productId, review),
1546
+ withdrawReview: (productId) => reviews.withdraw(productId),
1547
+ voteOnReview: (productId, reviewId, direction) => reviews.vote(productId, reviewId, direction)
1548
+ };
1549
+ }, [storefront, enabled]);
1550
+ }
1551
+
1552
+ // src/hooks/useVendor.ts
1553
+ import { useEffect as useEffect3, useState as useState2 } from "react";
1554
+ function useVendor() {
1555
+ const storefront = useStorefront();
1556
+ const [state, setState] = useState2({ vendor: null, loading: true });
1557
+ useEffect3(() => {
1558
+ let current = true;
1559
+ storefront.client.vendor.get().then((vendor) => current && setState({ vendor, loading: false })).catch(() => current && setState({ vendor: null, loading: false }));
1560
+ return () => {
1561
+ current = false;
1562
+ };
1563
+ }, [storefront]);
1564
+ return state;
1565
+ }
1566
+
1567
+ // src/hooks/useVoucher.ts
1568
+ import { NotFoundError as NotFoundError2 } from "@moonbase.sh/storefront-api";
1569
+ import { useMemo as useMemo9 } from "react";
1570
+ function useVoucher() {
1571
+ const storefront = useStorefront();
1572
+ return useMemo9(() => {
1573
+ const known = async (lookup) => {
1574
+ try {
1575
+ return await lookup;
1576
+ } catch (err) {
1577
+ if (err instanceof NotFoundError2)
1578
+ throw new Error("Voucher code invalid");
1579
+ throw err;
1580
+ }
1581
+ };
1582
+ return {
1583
+ peek: (code) => known(storefront.client.vouchers.peek(code)),
1584
+ redeem: (code) => known(storefront.client.vouchers.redeem(code))
1585
+ };
1586
+ }, [storefront]);
1587
+ }
1588
+
1589
+ // src/index.ts
1590
+ export * from "@moonbase.sh/storefront-api";
1591
+ function createStorefront(endpoint, options = {}) {
1592
+ var _a;
1593
+ const { initialCatalog, autoApplyItemOffers, ...config } = options;
1594
+ const configuration = {
1595
+ ...config,
1596
+ endpoint,
1597
+ // Named in `x-mb-client` ahead of `@moonbase.sh/storefront-api`, after any SDK wrapping this one.
1598
+ sdk: `${(_a = config.sdk) != null ? _a : ""} @moonbase.sh/react/${version}`.trim().replace(/\s+/g, " ")
1599
+ };
1600
+ return new MoonbaseStorefront(configuration, new MoonbaseClient(configuration), { initialCatalog, autoApplyItemOffers });
1601
+ }
1602
+ export {
1603
+ MoonbaseStorefront,
1604
+ StorefrontProvider,
1605
+ createStorefront,
1606
+ useActivationRequest,
1607
+ useAuth,
1608
+ useBundle,
1609
+ useBundles,
1610
+ useCart,
1611
+ useCartOffer,
1612
+ useCatalog,
1613
+ useCheckout,
1614
+ useCommunicationPreferences,
1615
+ useEligibleOffers,
1616
+ useGroups,
1617
+ useInventory,
1618
+ useLockedOffers,
1619
+ useOffer,
1620
+ useOffers,
1621
+ useOrders,
1622
+ useProduct,
1623
+ useProducts,
1624
+ usePromotions,
1625
+ useReviews,
1626
+ useStorefront,
1627
+ useStorefrontEvent,
1628
+ useStorefrontState,
1629
+ useVendor,
1630
+ useVoucher
1631
+ };