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