@joy-loyalty/hydrogen 0.0.0-stage → 0.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.
Files changed (127) hide show
  1. package/LICENSE +3 -0
  2. package/README.md +134 -2
  3. package/dist/cache-control.d.ts +8 -0
  4. package/dist/cache-control.js +6 -0
  5. package/dist/csp.d.ts +14 -0
  6. package/dist/csp.js +33 -0
  7. package/dist/headless-host-adapter.d.ts +5 -0
  8. package/dist/headless-host-adapter.js +197 -0
  9. package/dist/host-adapter/capabilities.d.ts +3 -0
  10. package/dist/host-adapter/capabilities.js +12 -0
  11. package/dist/host-adapter/data-source.d.ts +3 -0
  12. package/dist/host-adapter/data-source.js +49 -0
  13. package/dist/host-adapter/product-fetcher.d.ts +2 -0
  14. package/dist/host-adapter/product-fetcher.js +37 -0
  15. package/dist/host-adapter/promoted-collections.d.ts +2 -0
  16. package/dist/host-adapter/promoted-collections.js +43 -0
  17. package/dist/host-adapter/types.d.ts +212 -0
  18. package/dist/host-adapter/types.js +1 -0
  19. package/dist/hydrogen-cart-port.d.ts +134 -0
  20. package/dist/hydrogen-cart-port.js +245 -0
  21. package/dist/index.d.ts +26 -0
  22. package/dist/index.js +15 -0
  23. package/dist/joy-widget.d.ts +29 -0
  24. package/dist/joy-widget.js +291 -0
  25. package/dist/lib/JoyProvider.d.ts +47 -0
  26. package/dist/lib/JoyProvider.js +95 -0
  27. package/dist/lib/account-links.d.ts +5 -0
  28. package/dist/lib/account-links.js +65 -0
  29. package/dist/lib/apply-behavior.d.ts +12 -0
  30. package/dist/lib/apply-behavior.js +26 -0
  31. package/dist/lib/core-loader.d.ts +63 -0
  32. package/dist/lib/core-loader.js +160 -0
  33. package/dist/lib/core-manifest.d.ts +7 -0
  34. package/dist/lib/core-manifest.js +54 -0
  35. package/dist/lib/core-preload-links.d.ts +8 -0
  36. package/dist/lib/core-preload-links.js +8 -0
  37. package/dist/lib/coupon-mapper.d.ts +95 -0
  38. package/dist/lib/coupon-mapper.js +167 -0
  39. package/dist/lib/custom-links.d.ts +22 -0
  40. package/dist/lib/custom-links.js +56 -0
  41. package/dist/lib/deeplink.d.ts +25 -0
  42. package/dist/lib/deeplink.js +92 -0
  43. package/dist/lib/earn-signup-gate.d.ts +3 -0
  44. package/dist/lib/earn-signup-gate.js +31 -0
  45. package/dist/lib/facebook-ref-link.d.ts +13 -0
  46. package/dist/lib/facebook-ref-link.js +31 -0
  47. package/dist/lib/headless-referral-origin.d.ts +2 -0
  48. package/dist/lib/headless-referral-origin.js +24 -0
  49. package/dist/lib/headless-source.d.ts +8 -0
  50. package/dist/lib/headless-source.js +71 -0
  51. package/dist/lib/image.d.ts +2 -0
  52. package/dist/lib/image.js +14 -0
  53. package/dist/lib/metafield-blob.d.ts +33 -0
  54. package/dist/lib/metafield-blob.js +76 -0
  55. package/dist/lib/money.d.ts +6 -0
  56. package/dist/lib/money.js +25 -0
  57. package/dist/lib/order-mapper.d.ts +44 -0
  58. package/dist/lib/order-mapper.js +141 -0
  59. package/dist/lib/place-order-scope.d.ts +6 -0
  60. package/dist/lib/place-order-scope.js +22 -0
  61. package/dist/lib/points.d.ts +5 -0
  62. package/dist/lib/points.js +10 -0
  63. package/dist/lib/recently-viewed-tracker.d.ts +1 -0
  64. package/dist/lib/recently-viewed-tracker.js +34 -0
  65. package/dist/lib/recommended-loader.d.ts +43 -0
  66. package/dist/lib/recommended-loader.js +111 -0
  67. package/dist/lib/referral-share.d.ts +4 -0
  68. package/dist/lib/referral-share.js +33 -0
  69. package/dist/lib/safe-navigation-url.d.ts +1 -0
  70. package/dist/lib/safe-navigation-url.js +9 -0
  71. package/dist/lib/server-token.d.ts +41 -0
  72. package/dist/lib/server-token.js +87 -0
  73. package/dist/lib/shop-locale.d.ts +1 -0
  74. package/dist/lib/shop-locale.js +21 -0
  75. package/dist/lib/social-earn.d.ts +11 -0
  76. package/dist/lib/social-earn.js +25 -0
  77. package/dist/lib/storefront-fonts.d.ts +5 -0
  78. package/dist/lib/storefront-fonts.js +52 -0
  79. package/dist/lib/token.d.ts +14 -0
  80. package/dist/lib/token.js +135 -0
  81. package/dist/lib/write-review.d.ts +2 -0
  82. package/dist/lib/write-review.js +44 -0
  83. package/dist/loyalty-page/JoyLoyaltyPage.d.ts +151 -0
  84. package/dist/loyalty-page/JoyLoyaltyPage.js +447 -0
  85. package/dist/loyalty-page/compose-home.d.ts +35 -0
  86. package/dist/loyalty-page/compose-home.js +177 -0
  87. package/dist/loyalty-page/skeleton.d.ts +11 -0
  88. package/dist/loyalty-page/skeleton.js +99 -0
  89. package/dist/orchestrator/context.d.ts +61 -0
  90. package/dist/orchestrator/context.js +64 -0
  91. package/dist/orchestrator/gated.d.ts +1 -0
  92. package/dist/orchestrator/gated.js +14 -0
  93. package/dist/orchestrator/handlers/account.d.ts +19 -0
  94. package/dist/orchestrator/handlers/account.js +266 -0
  95. package/dist/orchestrator/handlers/birthday.d.ts +6 -0
  96. package/dist/orchestrator/handlers/birthday.js +128 -0
  97. package/dist/orchestrator/handlers/earn.d.ts +5 -0
  98. package/dist/orchestrator/handlers/earn.js +258 -0
  99. package/dist/orchestrator/handlers/milestone-tier.d.ts +5 -0
  100. package/dist/orchestrator/handlers/milestone-tier.js +123 -0
  101. package/dist/orchestrator/handlers/profile.d.ts +5 -0
  102. package/dist/orchestrator/handlers/profile.js +262 -0
  103. package/dist/orchestrator/handlers/redeem.d.ts +6 -0
  104. package/dist/orchestrator/handlers/redeem.js +464 -0
  105. package/dist/orchestrator/handlers/referral.d.ts +5 -0
  106. package/dist/orchestrator/handlers/referral.js +218 -0
  107. package/dist/orchestrator/render.d.ts +2 -0
  108. package/dist/orchestrator/render.js +193 -0
  109. package/dist/render-adapter.d.ts +50 -0
  110. package/dist/render-adapter.js +422 -0
  111. package/dist/routes/joy-place-order-scope.d.ts +12 -0
  112. package/dist/routes/joy-place-order-scope.js +32 -0
  113. package/dist/routes/joy-products.d.ts +48 -0
  114. package/dist/routes/joy-products.js +326 -0
  115. package/dist/routes/joy-token.d.ts +16 -0
  116. package/dist/routes/joy-token.js +32 -0
  117. package/dist/server/get-joy-initial-data.d.ts +38 -0
  118. package/dist/server/get-joy-initial-data.js +61 -0
  119. package/dist/server/get-joy-loyalty-page-data.d.ts +27 -0
  120. package/dist/server/get-joy-loyalty-page-data.js +99 -0
  121. package/dist/server/index.d.ts +8 -0
  122. package/dist/server/index.js +4 -0
  123. package/dist/widget-controller.d.ts +2 -0
  124. package/dist/widget-controller.js +1 -0
  125. package/dist/widget-orchestrator.d.ts +88 -0
  126. package/dist/widget-orchestrator.js +499 -0
  127. package/package.json +121 -4
@@ -0,0 +1,464 @@
1
+ import { mapReceivedRewardsToCoupons, mapRedeemedRewardsToCoupons } from '../../lib/coupon-mapper.js';
2
+ import { followApplyBehavior } from '../../lib/apply-behavior.js';
3
+ import { resolveActiveTranslation } from '../../render-adapter.js';
4
+ import { detail, writeProps } from '../../widget-orchestrator.js';
5
+ import { safeNavigationUrl } from '../../lib/safe-navigation-url.js';
6
+ const RECEIVED_PAGE_SIZE = 10;
7
+ const OWN_COUPON_PAGE_SIZE = 10;
8
+ const AUTO_ADD_GIFT_BEHAVIORS = ['auto_add_to_cart', 'auto_add_to_cart_drawer_hide_modal'];
9
+ function giftVariantIds(program, variantIdSelected) {
10
+ return ((program.freeProductQuantity || 'all') === 'all' ? program.programVariantIds || [] : [variantIdSelected])
11
+ .filter((id) => Boolean(id))
12
+ .map(String);
13
+ }
14
+ function giftQuantities(program) {
15
+ const quantityByVariant = new Map();
16
+ for (const product of program.specificProducts ?? []) {
17
+ const raw = Number.parseInt(String(product.quantity ?? '1'), 10);
18
+ const quantity = Number.isFinite(raw) && raw > 0 ? raw : 1;
19
+ for (const variant of product.variants ?? [])
20
+ quantityByVariant.set(String(variant.id), quantity);
21
+ }
22
+ return quantityByVariant;
23
+ }
24
+ const MISSING_VARIANT_IDS_KEY = '__missingVariantIds';
25
+ function readSpendingPrograms(blob) {
26
+ const program = blob && typeof blob === 'object' ? blob.program : undefined;
27
+ const spending = program && typeof program === 'object' ? program.spending : undefined;
28
+ return Array.isArray(spending) ? spending : [];
29
+ }
30
+ function toVariantGid(raw) {
31
+ return raw.startsWith('gid://') ? raw : `gid://shopify/ProductVariant/${raw}`;
32
+ }
33
+ function extractCartLines(d) {
34
+ if (Array.isArray(d.lines))
35
+ return d.lines;
36
+ const products = Array.isArray(d.products) ? d.products : [];
37
+ return products.flatMap(product => {
38
+ const variantId = product.variantId ?? product.id;
39
+ if (variantId == null)
40
+ return [];
41
+ return [{ id: toVariantGid(String(variantId)), quantity: product.quantity ?? 1 }];
42
+ });
43
+ }
44
+ function getInvalidVariantIds(stockMap, variantIds) {
45
+ const missing = stockMap[MISSING_VARIANT_IDS_KEY] ?? [];
46
+ if (!missing.length)
47
+ return [];
48
+ const missingSet = new Set(missing.map(String));
49
+ return variantIds.filter(id => missingSet.has(String(id)));
50
+ }
51
+ function filterAvailableVariantIds(stockMap, variantIds) {
52
+ const invalid = new Set(getInvalidVariantIds(stockMap, variantIds));
53
+ const candidates = variantIds.filter(id => !invalid.has(id));
54
+ const productKeys = Object.keys(stockMap).filter(key => key !== MISSING_VARIANT_IDS_KEY);
55
+ if (!productKeys.length)
56
+ return candidates;
57
+ return candidates.filter(id => {
58
+ const entry = productKeys
59
+ .map(key => stockMap[key])
60
+ .find(p => !Array.isArray(p) && p?.variants && Object.prototype.hasOwnProperty.call(p.variants, id));
61
+ if (!entry?.variants)
62
+ return true;
63
+ return entry.variants[id] !== false;
64
+ });
65
+ }
66
+ export function registerRedeemHandlers(ctx) {
67
+ const { element, controller, hostAdapter, cart, caps, renderContext, surface, toast } = ctx;
68
+ let activeCouponTab = 'available';
69
+ let availableCoupons = [];
70
+ let rewardsRequestId = 0;
71
+ let receivedRequestId = 0;
72
+ function currentRedeemResult() {
73
+ const existing = element.redeemResult;
74
+ return existing && typeof existing === 'object' ? existing : {};
75
+ }
76
+ function applySettings() {
77
+ return (ctx.activeBlob?.settings ?? {});
78
+ }
79
+ function followBehavior() {
80
+ followApplyBehavior(applySettings(), {
81
+ navigate: url => {
82
+ const safe = safeNavigationUrl(url);
83
+ if (safe)
84
+ window.location.replace(url);
85
+ },
86
+ cartRoute: `${hostAdapter.context().routesRoot || '/'}cart`,
87
+ openCartDrawer: ctx.openCartDrawer,
88
+ onCartDrawerOpen: () => element.close?.()
89
+ });
90
+ }
91
+ async function autoAddGiftAfterRedeem(option, variantIdSelected, couponCode) {
92
+ const settings = applySettings();
93
+ if (!cart || option?.event !== 'free_gift' || option.appliedTo !== 'sf_product')
94
+ return { handled: false, applied: false };
95
+ if (!AUTO_ADD_GIFT_BEHAVIORS.includes(settings.customerFreeGiftBehavior || ''))
96
+ return { handled: false, applied: false };
97
+ const variantIds = giftVariantIds(option, variantIdSelected);
98
+ if (!variantIds.length)
99
+ return { handled: true, applied: false };
100
+ const stockMap = (freeGiftStockMap()[option.id ?? ''] ?? {});
101
+ const inStock = filterAvailableVariantIds(stockMap, variantIds);
102
+ if (!inStock.length)
103
+ return { handled: true, applied: false };
104
+ try {
105
+ const quantities = giftQuantities(option);
106
+ const added = await cart
107
+ .addGiftLines(inStock.map(id => ({ id: toVariantGid(id), quantity: quantities.get(id) ?? 1 })))
108
+ .catch(error => {
109
+ if (inStock.length === 1)
110
+ throw error;
111
+ console.warn('[joy] some free gift lines could not be added', error);
112
+ return inStock.length;
113
+ });
114
+ if (!added) {
115
+ toast('All products are currently out of stock');
116
+ return { handled: true, applied: false };
117
+ }
118
+ const result = await cart.applyDiscount(couponCode);
119
+ if (!result.ok)
120
+ return { handled: true, applied: false };
121
+ followBehavior();
122
+ return { handled: true, applied: !!result.applied };
123
+ }
124
+ catch (error) {
125
+ console.warn('[joy] auto-add free gift after redeem failed', error);
126
+ return { handled: true, applied: false };
127
+ }
128
+ }
129
+ function shouldAutoApply(event) {
130
+ if (event === 'gift_card')
131
+ return false;
132
+ const behavior = element.getAttribute('redeem-coupon-behavior');
133
+ return !behavior || behavior === 'auto_apply';
134
+ }
135
+ const redeemKeys = new Map();
136
+ const redeemsInFlight = new Set();
137
+ async function runRedeem(programId, d) {
138
+ const options = {
139
+ points: d.redeemPoints ?? d.option?.points,
140
+ variantId: d.variantIdSelected,
141
+ recipient: d.recipient ?? undefined
142
+ };
143
+ const intent = JSON.stringify([programId, options.points ?? null, options.variantId ?? null, options.recipient ?? null]);
144
+ if (redeemsInFlight.has(intent))
145
+ return;
146
+ redeemsInFlight.add(intent);
147
+ let idempotencyKey = redeemKeys.get(intent);
148
+ if (!idempotencyKey) {
149
+ idempotencyKey = crypto.randomUUID();
150
+ redeemKeys.set(intent, idempotencyKey);
151
+ }
152
+ let result;
153
+ try {
154
+ result = await hostAdapter.data.redeem(programId, { ...options, idempotencyKey });
155
+ redeemKeys.delete(intent);
156
+ }
157
+ catch (error) {
158
+ if (error?.code !== 'NETWORK_ERROR')
159
+ redeemKeys.delete(intent);
160
+ writeProps(element, { redeemResult: { ...currentRedeemResult() } });
161
+ throw error;
162
+ }
163
+ finally {
164
+ redeemsInFlight.delete(intent);
165
+ }
166
+ if (result.remainingPointsKnown !== false)
167
+ writeProps(element, { points: result.remainingPoints });
168
+ const couponCode = result.couponCode ?? '';
169
+ const baseResult = { ...currentRedeemResult(), couponCode, sentToFriend: d.recipient != null };
170
+ if (couponCode) {
171
+ const gift = await autoAddGiftAfterRedeem(d.option, d.variantIdSelected, couponCode);
172
+ if (gift.handled) {
173
+ writeProps(element, { redeemResult: { ...baseResult, couponApplied: gift.applied } });
174
+ return;
175
+ }
176
+ }
177
+ if (couponCode && cart && shouldAutoApply(d.option?.event)) {
178
+ const applyResult = await cart.applyDiscount(couponCode);
179
+ writeProps(element, { redeemResult: { ...baseResult, couponApplied: !!(applyResult.ok && applyResult.applied) } });
180
+ if (!applyResult.ok) {
181
+ element.dispatchEvent(new CustomEvent('joy-error', {
182
+ bubbles: true,
183
+ composed: true,
184
+ detail: { message: applyResult.reason || 'Could not apply the discount code' }
185
+ }));
186
+ }
187
+ return;
188
+ }
189
+ writeProps(element, { redeemResult: baseResult });
190
+ }
191
+ function couponMapOptions() {
192
+ return {
193
+ spendingPrograms: readSpendingPrograms(ctx.activeBlob),
194
+ translation: renderContext ? resolveActiveTranslation(ctx.activeBlob?.translation, renderContext.locale) : {},
195
+ currency: renderContext?.currency ?? '',
196
+ locale: renderContext?.locale
197
+ };
198
+ }
199
+ function loadRewards(query) {
200
+ const tab = activeCouponTab;
201
+ const effectiveQuery = tab === 'unavailable' ? undefined : query;
202
+ const before = effectiveQuery?.get('before') ?? undefined;
203
+ const after = effectiveQuery?.get('after') ?? undefined;
204
+ const isFreshLoad = !before && !after;
205
+ let rewardsQuery = effectiveQuery;
206
+ if (tab !== 'unavailable') {
207
+ rewardsQuery = new URLSearchParams(effectiveQuery);
208
+ rewardsQuery.set('limit', String(OWN_COUPON_PAGE_SIZE));
209
+ }
210
+ const requestId = ++rewardsRequestId;
211
+ const receivedId = isFreshLoad ? ++receivedRequestId : 0;
212
+ writeProps(element, { couponsLoading: true });
213
+ surface(Promise.all([
214
+ hostAdapter.data.getRewards({ query: rewardsQuery, couponStatus: tab }),
215
+ isFreshLoad && tab === 'available' && caps.receivedRewards
216
+ ? hostAdapter.data.getReceivedRewards({ limit: RECEIVED_PAGE_SIZE }).catch(() => null)
217
+ : Promise.resolve(null)
218
+ ])
219
+ .then(([rewards, receivedPage]) => {
220
+ if (requestId !== rewardsRequestId)
221
+ return;
222
+ const mapOptions = couponMapOptions();
223
+ const coupons = mapRedeemedRewardsToCoupons(rewards.redeemed, mapOptions);
224
+ if (tab === 'available')
225
+ availableCoupons = coupons;
226
+ writeProps(element, {
227
+ coupons,
228
+ ...(isFreshLoad && receivedId === receivedRequestId
229
+ ? { receivedCoupons: mapReceivedRewardsToCoupons(receivedPage?.received, mapOptions) }
230
+ : {})
231
+ });
232
+ const el = element;
233
+ const isUnavailableTab = tab === 'unavailable';
234
+ el.updateCouponPagination?.({
235
+ hasNext: isUnavailableTab ? false : (rewards.pagination?.hasNext ?? false),
236
+ hasPrev: isUnavailableTab ? false : (rewards.pagination?.hasPre ?? false),
237
+ totalCount: coupons.length,
238
+ before,
239
+ after,
240
+ isFreshLoad,
241
+ ...(isFreshLoad ? { receivedHasNext: receivedPage?.pagination?.hasNext ?? false, receivedHasPrev: false } : {})
242
+ });
243
+ })
244
+ .finally(() => {
245
+ if (requestId === rewardsRequestId)
246
+ writeProps(element, { couponsLoading: false });
247
+ }));
248
+ }
249
+ function loadReceived(direction, cursor) {
250
+ const params = { limit: RECEIVED_PAGE_SIZE };
251
+ if (direction && cursor)
252
+ params[direction] = cursor;
253
+ const requestId = ++receivedRequestId;
254
+ surface(hostAdapter.data.getReceivedRewards(params).then(page => {
255
+ if (requestId !== receivedRequestId)
256
+ return;
257
+ writeProps(element, {
258
+ receivedCoupons: mapReceivedRewardsToCoupons(page.received, couponMapOptions())
259
+ });
260
+ const el = element;
261
+ el.updateReceivedCouponPagination?.({
262
+ hasNext: page.pagination?.hasNext ?? false,
263
+ hasPrev: page.pagination?.hasPre ?? false,
264
+ before: params.before,
265
+ after: params.after
266
+ });
267
+ }));
268
+ }
269
+ function runApplyCoupon(code, program, variantIdSelected) {
270
+ const el = element;
271
+ if (el.applyingCouponCode)
272
+ return;
273
+ el.applyingCouponCode = code;
274
+ const settle = () => {
275
+ el.applyingCouponCode = '';
276
+ const redeemDetail = element.shadowRoot?.querySelector('joy-redeem-detail');
277
+ if (redeemDetail)
278
+ redeemDetail.loading = false;
279
+ };
280
+ void (async () => {
281
+ try {
282
+ const gift = await addFreeGiftToCart(program, variantIdSelected);
283
+ if (!gift.ok) {
284
+ if (gift.errorKey)
285
+ toast(gift.errorKey);
286
+ return;
287
+ }
288
+ const result = await cart.applyDiscount(code);
289
+ if (result.ok && result.applied) {
290
+ const current = currentRedeemResult();
291
+ if (current.couponCode === code) {
292
+ writeProps(element, { redeemResult: { ...current, couponApplied: true } });
293
+ }
294
+ toast('Applied coupon successfully!');
295
+ followBehavior();
296
+ return;
297
+ }
298
+ toastApplyCouponFailed();
299
+ }
300
+ catch {
301
+ toastApplyCouponFailed();
302
+ }
303
+ finally {
304
+ settle();
305
+ }
306
+ })();
307
+ }
308
+ function runAddGiftCoupon(code, lines) {
309
+ const el = element;
310
+ if (el.applyingCouponCode)
311
+ return;
312
+ el.applyingCouponCode = code;
313
+ void (async () => {
314
+ try {
315
+ let added;
316
+ try {
317
+ added = await cart.addGiftLines(lines);
318
+ }
319
+ catch {
320
+ toast('Failed to add to cart');
321
+ return;
322
+ }
323
+ if (!added) {
324
+ toast('All products are currently out of stock');
325
+ return;
326
+ }
327
+ const result = await cart.applyDiscount(code);
328
+ if (!result.ok || !result.applied) {
329
+ toastApplyCouponFailed();
330
+ return;
331
+ }
332
+ toast('Added to cart');
333
+ followBehavior();
334
+ }
335
+ catch {
336
+ toastApplyCouponFailed();
337
+ }
338
+ finally {
339
+ el.applyingCouponCode = '';
340
+ }
341
+ })();
342
+ }
343
+ async function addFreeGiftToCart(program, variantIdSelected) {
344
+ if (!cart || !program || program.event !== 'free_gift')
345
+ return { ok: true };
346
+ if ((program.appliedTo || 'sf_product') !== 'sf_product')
347
+ return { ok: true };
348
+ if (applySettings().customerFreeGiftBehavior === 'auto_add_to_cart')
349
+ return { ok: true };
350
+ const variantIds = giftVariantIds(program, variantIdSelected);
351
+ if (!variantIds.length)
352
+ return { ok: true };
353
+ const stockMap = (freeGiftStockMap()[program.id ?? ''] ?? {});
354
+ const invalid = getInvalidVariantIds(stockMap, variantIds);
355
+ if (invalid.length === variantIds.length) {
356
+ return { ok: false, errorKey: 'This reward is temporarily unavailable, please contact the store' };
357
+ }
358
+ const available = filterAvailableVariantIds(stockMap, variantIds);
359
+ if (!available.length)
360
+ return { ok: false, errorKey: 'All products are currently out of stock' };
361
+ const quantityByVariant = giftQuantities(program);
362
+ const added = await cart.addGiftLines(available.map(id => ({ id: toVariantGid(id), quantity: quantityByVariant.get(id) ?? 1 })));
363
+ if (!added)
364
+ return { ok: false, errorKey: 'All products are currently out of stock' };
365
+ return { ok: true };
366
+ }
367
+ function freeGiftStockMap() {
368
+ return ((element._freeGiftStockMap) ?? {});
369
+ }
370
+ function toastApplyCouponFailed() {
371
+ const translation = resolveActiveTranslation(ctx.activeBlob?.translation, renderContext?.locale);
372
+ const message = translation.failedToApplyCoupon ||
373
+ 'Failed to apply coupon. Please check if the coupon is valid or has expired.';
374
+ element.showToast?.(message);
375
+ }
376
+ function loadFreeGiftStock(programId) {
377
+ if (!programId)
378
+ return;
379
+ const existing = (element._freeGiftStockMap) ?? {};
380
+ if (existing[programId])
381
+ return;
382
+ surface(hostAdapter.data.getFreeGiftStock(programId).then((stock) => {
383
+ const map = {};
384
+ for (const product of stock.products ?? []) {
385
+ const variants = {};
386
+ for (const variant of product.variants ?? [])
387
+ variants[variant.variantId] = variant.available;
388
+ map[product.productId] = { available: product.available, variants };
389
+ }
390
+ if (Array.isArray(stock.missingVariantIds) && stock.missingVariantIds.length) {
391
+ map['__missingVariantIds'] = stock.missingVariantIds;
392
+ }
393
+ element._freeGiftStockMap = {
394
+ ...existing,
395
+ [programId]: map
396
+ };
397
+ }));
398
+ }
399
+ function restoreAvailableCouponsOnLeave(view) {
400
+ if (view !== 'coupons' && activeCouponTab === 'unavailable') {
401
+ rewardsRequestId++;
402
+ activeCouponTab = 'available';
403
+ writeProps(element, { coupons: availableCoupons });
404
+ }
405
+ }
406
+ function openCouponsView() {
407
+ activeCouponTab = 'available';
408
+ loadRewards();
409
+ }
410
+ controller.on('joy-redeem-action', event => {
411
+ const d = detail(event);
412
+ const programId = d.option?.id ?? d.programId;
413
+ if (!programId)
414
+ return;
415
+ surface(runRedeem(programId, d));
416
+ });
417
+ controller.on('joy-coupon-tab-change', event => {
418
+ const { isAvailable } = detail(event);
419
+ activeCouponTab = isAvailable === false ? 'unavailable' : 'available';
420
+ loadRewards();
421
+ });
422
+ controller.on('joy-coupon-page-change', event => {
423
+ const { direction, cursor } = detail(event);
424
+ loadRewards(direction && cursor ? new URLSearchParams({ [direction]: cursor }) : undefined);
425
+ });
426
+ controller.on('joy-received-page-change', event => {
427
+ const { direction, cursor } = detail(event);
428
+ loadReceived(direction, cursor);
429
+ });
430
+ controller.on('joy-add-to-cart', event => {
431
+ if (!cart)
432
+ return;
433
+ const d = detail(event);
434
+ const lines = extractCartLines(d);
435
+ if (!lines.length)
436
+ return;
437
+ if (d.code)
438
+ return runAddGiftCoupon(d.code, lines);
439
+ surface(cart.addLines(lines));
440
+ });
441
+ controller.on('joy-apply-coupon', event => {
442
+ if (!cart)
443
+ return;
444
+ const { code, program, variantIdSelected } = detail(event);
445
+ if (code)
446
+ runApplyCoupon(code, program, variantIdSelected);
447
+ });
448
+ controller.on('joy-revoke-coupon', event => {
449
+ if (!cart)
450
+ return;
451
+ const { code } = detail(event);
452
+ if (code)
453
+ surface(cart.removeDiscount(code));
454
+ });
455
+ controller.on('joy-copy-coupon', event => {
456
+ event.preventDefault?.();
457
+ });
458
+ controller.on('joy-fetch-free-gift-stock', event => {
459
+ const { programId } = detail(event);
460
+ loadFreeGiftStock(programId);
461
+ });
462
+ ctx.loadRewards = loadRewards;
463
+ return { restoreAvailableCouponsOnLeave, openCouponsView };
464
+ }
@@ -0,0 +1,5 @@
1
+ import type { OrchestratorContext } from '../context.js';
2
+ export interface ReferralHandlers {
3
+ loadReferralHistory(direction?: 'before' | 'after', cursor?: string): void;
4
+ }
5
+ export declare function registerReferralHandlers(ctx: OrchestratorContext): ReferralHandlers;
@@ -0,0 +1,218 @@
1
+ import { JoyApiError } from '@joy-loyalty/sdk/client';
2
+ import { toHeadlessReferralLink } from '../../lib/headless-referral-origin.js';
3
+ import { CONTENT_MAIL_SHARE_LINK_REFERRAL, getLinkSocial, getShareEmailUrl, SOCIAL_EMAIL } from '../../lib/referral-share.js';
4
+ import { detail, writeCachedReferralLink, writeProps } from '../../widget-orchestrator.js';
5
+ function readReferralProgramStatus(blob) {
6
+ const referral = blob && typeof blob === 'object' ? blob.referralProgram : undefined;
7
+ return !!(referral && typeof referral === 'object' && referral.status);
8
+ }
9
+ function readReferralShareSocials(blob) {
10
+ const referral = blob && typeof blob === 'object' ? blob.referralProgram : undefined;
11
+ const socials = referral && typeof referral === 'object' ? referral.shareSocials : undefined;
12
+ return Array.isArray(socials) ? socials : [];
13
+ }
14
+ function readShopName(blob) {
15
+ const shop = blob && typeof blob === 'object' ? blob.shop : undefined;
16
+ const name = shop && typeof shop === 'object' ? shop.name : undefined;
17
+ return typeof name === 'string' ? name : '';
18
+ }
19
+ function headlessReferralLink(link, blob) {
20
+ const shop = blob && typeof blob === 'object' ? blob.shop : undefined;
21
+ return toHeadlessReferralLink(link, shop, window.location.origin);
22
+ }
23
+ const REFERRAL_SEND_ERROR_LABELS = {
24
+ REFERRAL_SELF_REFERRAL: 'You cannot refer yourself. Please use a different email.',
25
+ REFERRAL_EMAIL_COOLDOWN: "You've already sent a referral to this email. Please wait 24 hours before sending again, or copy your referral link to share it manually.",
26
+ REFERRAL_EMAIL_LIMIT_REACHED: "You've reached the sharing limit. Please try again later.",
27
+ REFERRAL_EMAIL_SHARING_DISABLED: 'Email sharing is not available.',
28
+ REFERRAL_EMAIL_NOTIFICATION_DISABLED: 'Email sharing is not available.',
29
+ INVALID_EMAIL_FORMAT: 'Please enter a valid email address',
30
+ CUSTOMER_NOT_FOUND: 'Customer not found. Please try again.'
31
+ };
32
+ function referralSendErrorLabel(element, error) {
33
+ const labels = element.labels || {};
34
+ const code = error instanceof JoyApiError ? error.code : undefined;
35
+ const english = (code && REFERRAL_SEND_ERROR_LABELS[code]) || 'Something went wrong. Please try again.';
36
+ return labels[`[[WidgetV4]]${english}`] || english;
37
+ }
38
+ export function registerReferralHandlers(ctx) {
39
+ const { element, controller, hostAdapter, surface, toast, isAuthed } = ctx;
40
+ function loadReferral() {
41
+ const markLoaded = () => writeProps(element, { 'referral-loaded': true });
42
+ if (!readReferralProgramStatus(ctx.activeBlob)) {
43
+ markLoaded();
44
+ return;
45
+ }
46
+ if (!isAuthed()) {
47
+ markLoaded();
48
+ return;
49
+ }
50
+ surface(hostAdapter.data.getReferral().then(referral => {
51
+ const completed = referral.stats?.completed ?? 0;
52
+ const pending = referral.stats?.pending ?? 0;
53
+ writeProps(element, {
54
+ 'referral-link': headlessReferralLink(referral.referralLink ?? '', ctx.activeBlob),
55
+ 'referral-completed-count': completed,
56
+ 'referral-pending-count': pending,
57
+ 'referral-total-count': completed + pending,
58
+ 'referral-loaded': true
59
+ });
60
+ }));
61
+ }
62
+ function runGuestReferralLink(email) {
63
+ const el = element;
64
+ el.referralGetLinkLoading = true;
65
+ void hostAdapter.data
66
+ .generateReferralLink(email)
67
+ .then(result => {
68
+ if (result?.urlReferral) {
69
+ writeProps(element, {
70
+ 'referral-link': headlessReferralLink(result.urlReferral, ctx.activeBlob),
71
+ 'referral-loaded': true
72
+ });
73
+ toast('Referral link generated!');
74
+ return;
75
+ }
76
+ writeProps(element, { 'referral-loaded': true });
77
+ toast('Could not generate referral link');
78
+ })
79
+ .catch(() => {
80
+ writeProps(element, { 'referral-loaded': true });
81
+ toast('Could not generate referral link');
82
+ })
83
+ .finally(() => {
84
+ el.referralGetLinkLoading = false;
85
+ });
86
+ }
87
+ function loadReferralHistory(direction, cursor) {
88
+ if (!readReferralProgramStatus(ctx.activeBlob) || !isAuthed())
89
+ return;
90
+ const el = element;
91
+ const params = direction && cursor ? { [direction]: cursor } : undefined;
92
+ writeProps(element, { 'referral-activities-loading': true });
93
+ surface(hostAdapter.data
94
+ .getReferralHistory(params)
95
+ .then((page) => {
96
+ el.referralActivities = page.items.map(item => ({
97
+ id: item.id,
98
+ email: item.email,
99
+ status: item.status,
100
+ date: item.createdAt ?? undefined
101
+ }));
102
+ const current = el.referralActivitiesPage || 1;
103
+ el.referralActivitiesPage = direction === 'after' ? current + 1 : direction === 'before' ? Math.max(1, current - 1) : 1;
104
+ writeProps(element, {
105
+ 'referral-activities-has-next': page.pagination.hasNext,
106
+ 'referral-activities-has-prev': page.pagination.hasPre
107
+ });
108
+ })
109
+ .finally(() => {
110
+ writeProps(element, { 'referral-activities-loading': false });
111
+ }));
112
+ }
113
+ let sendToFriendInFlight = false;
114
+ async function runSendToFriend(recipient) {
115
+ const el = element;
116
+ const context = el.getSendToFriendContext?.();
117
+ const email = recipient?.recipientEmail;
118
+ if (!context?.couponCode || !context?.programId || !email)
119
+ return;
120
+ if (sendToFriendInFlight)
121
+ return;
122
+ sendToFriendInFlight = true;
123
+ el.setSendToFriendState?.({ loading: true, errorMessage: '', success: false });
124
+ try {
125
+ await hostAdapter.data.sendRewardToFriend({
126
+ recipient: { email, name: recipient?.recipientName, message: recipient?.personalMessage },
127
+ couponCode: context.couponCode,
128
+ programId: context.programId
129
+ });
130
+ }
131
+ catch (error) {
132
+ const message = error instanceof Error ? error.message : String(error);
133
+ el.setSendToFriendState?.({ loading: false, errorMessage: message, success: false });
134
+ throw error;
135
+ }
136
+ finally {
137
+ sendToFriendInFlight = false;
138
+ }
139
+ el.setSendToFriendState?.({ loading: false, errorMessage: '', success: true });
140
+ }
141
+ function runShareReferral(d) {
142
+ const link = d.link || element.referralLink;
143
+ if (!link)
144
+ return;
145
+ const shareSocials = readReferralShareSocials(ctx.activeBlob);
146
+ const shareApp = d.app || (d.method === 'email' ? SOCIAL_EMAIL : '');
147
+ const socialConfig = shareSocials.find(s => s?.app === shareApp);
148
+ const rawMessage = typeof socialConfig?.message === 'string' ? socialConfig.message : '';
149
+ const shareMessage = rawMessage ? rawMessage.replaceAll('{{shop_name}}', readShopName(ctx.activeBlob)) : '';
150
+ if (shareApp === SOCIAL_EMAIL || d.method === 'email') {
151
+ const bodyPrefix = shareMessage ? `${getShareEmailUrl(shareMessage)}%20` : CONTENT_MAIL_SHARE_LINK_REFERRAL;
152
+ window.location.href = `${bodyPrefix}${encodeURIComponent(link)}`;
153
+ return;
154
+ }
155
+ if (shareApp) {
156
+ const socialUrl = getLinkSocial(shareApp, `${shareMessage} ${link}`.trim());
157
+ if (socialUrl) {
158
+ window.open(socialUrl, '_blank', 'noopener,noreferrer');
159
+ return;
160
+ }
161
+ }
162
+ if (d.method === 'social') {
163
+ const labels = element.labels || {};
164
+ const shareTitle = labels.referFriend || 'Refer a Friend';
165
+ const shareText = shareMessage || labels.referralDefaultSubtitle || 'Invite friends and earn rewards';
166
+ if (navigator.share)
167
+ navigator.share({ title: shareTitle, text: shareText, url: link }).catch(() => { });
168
+ return;
169
+ }
170
+ const copiedMessage = element.labels?.copied || 'Copied!';
171
+ if (navigator.clipboard)
172
+ navigator.clipboard.writeText(link).catch(() => { });
173
+ element.showToast?.(copiedMessage);
174
+ }
175
+ controller.on('joy-get-referral-link', event => {
176
+ const { email } = detail(event);
177
+ if (email) {
178
+ runGuestReferralLink(email);
179
+ return;
180
+ }
181
+ loadReferral();
182
+ });
183
+ controller.on('joy-share-referral', event => {
184
+ runShareReferral(detail(event));
185
+ });
186
+ controller.on('joy-send-referral-email', event => {
187
+ const { refereeEmail } = detail(event);
188
+ const setResult = (ok, message) => {
189
+ element.setReferralSendResult?.(ok, message);
190
+ };
191
+ if (!refereeEmail) {
192
+ setResult(false);
193
+ return;
194
+ }
195
+ void hostAdapter.data
196
+ .sendReferralEmail(refereeEmail)
197
+ .then(() => setResult(true))
198
+ .catch((error) => setResult(false, referralSendErrorLabel(element, error)));
199
+ });
200
+ controller.on('joy-referral-cache-change', event => {
201
+ const { showInvite } = detail(event);
202
+ writeCachedReferralLink(!!showInvite);
203
+ writeProps(element, { 'cached-referral-link': !!showInvite });
204
+ });
205
+ controller.on('joy-referral-page-change', event => {
206
+ const { direction, cursor } = detail(event);
207
+ loadReferralHistory(direction, cursor);
208
+ });
209
+ controller.on('joy-send-to-friend-submit', event => {
210
+ const { recipient } = detail(event);
211
+ surface(runSendToFriend(recipient));
212
+ });
213
+ controller.on('joy-send-to-friend-reset', () => {
214
+ element.resetSendToFriend?.();
215
+ });
216
+ ctx.loadReferral = loadReferral;
217
+ return { loadReferralHistory };
218
+ }
@@ -0,0 +1,2 @@
1
+ import type { OrchestratorContext } from './context.js';
2
+ export declare function attachRenderCore(ctx: OrchestratorContext): void;