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