@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,4 @@
1
+ export { getJoyInitialData } from './get-joy-initial-data.js';
2
+ export { JOY_PERSONALIZED_CACHE_CONTROL, isJoyInitialDataPersonalized } from '../cache-control.js';
3
+ export { getJoyLoyaltyPageData } from './get-joy-loyalty-page-data.js';
4
+ export { getWidgetCoreManifest } from '../lib/core-manifest.js';
@@ -0,0 +1,2 @@
1
+ export * from '@joy-loyalty/sdk/host';
2
+ export type { WidgetControllerHandle } from '@joy-loyalty/sdk/ports';
@@ -0,0 +1 @@
1
+ export * from '@joy-loyalty/sdk/host';
@@ -0,0 +1,88 @@
1
+ import type { Program, Tier } from '@joy-loyalty/sdk/client';
2
+ import type { HeadlessHostAdapter, JoyInitialData } from './headless-host-adapter.js';
3
+ import type { HydrogenCartPort } from './hydrogen-cart-port.js';
4
+ import type { WidgetCoreExports } from './lib/core-loader.js';
5
+ import type { HeadlessRenderIdentity, JoyMetafieldBlob } from './render-adapter.js';
6
+ export interface WidgetOrchestratorHandle {
7
+ dispose(): void;
8
+ ready: Promise<void>;
9
+ }
10
+ export interface WidgetAppearance {
11
+ variant?: 'popup' | 'drawer' | 'floating-drawer';
12
+ position?: 'left' | 'right';
13
+ theme?: 'light' | 'dark';
14
+ primaryColor?: string;
15
+ fabLabel?: string;
16
+ collapsed?: boolean;
17
+ }
18
+ export interface HeadlessInitialData extends JoyInitialData {
19
+ blob?: JoyMetafieldBlob;
20
+ shopifyCustomer?: HeadlessRenderIdentity;
21
+ login_url?: string;
22
+ register_url?: string;
23
+ account_url?: string;
24
+ page?: {
25
+ type: string;
26
+ resourceId: string;
27
+ handle: string;
28
+ };
29
+ locale?: string;
30
+ token?: string;
31
+ }
32
+ export type BlobCustomer = JoyInitialData['customer'] | Record<string, unknown>;
33
+ export declare function buildAppearanceProps(appearance?: WidgetAppearance): {
34
+ variant: "popup" | "drawer" | "floating-drawer";
35
+ position: "left" | "right";
36
+ theme: "light" | "dark";
37
+ 'primary-color': string | undefined;
38
+ 'fab-label': string | undefined;
39
+ collapsed: boolean;
40
+ };
41
+ export declare function buildAppearanceOverrides(appearance?: WidgetAppearance): Record<string, unknown>;
42
+ export declare function buildProps(customer: JoyInitialData['customer'], programs: readonly Program[], tiers?: readonly Tier[]): {
43
+ 'logged-in': boolean;
44
+ 'customer-id': string;
45
+ points: number;
46
+ 'current-tier': string;
47
+ 'tier-id': string | null;
48
+ 'next-tier': string;
49
+ 'tier-progress': number | undefined;
50
+ 'tier-required': number | undefined;
51
+ 'progress-type': "points" | undefined;
52
+ earnPrograms: {
53
+ id: string;
54
+ icon: string;
55
+ title: string;
56
+ description: string;
57
+ points: number | undefined;
58
+ value: string;
59
+ }[];
60
+ redeemPrograms: {
61
+ id: string;
62
+ icon: string;
63
+ title: string;
64
+ description: string;
65
+ points: number;
66
+ value: string;
67
+ }[];
68
+ };
69
+ export declare function writeProps(element: HTMLElement, props: Record<string, unknown>): void;
70
+ export declare function detail<T>(event: Event): T;
71
+ export declare function openGuideModal(guide: string): Promise<void>;
72
+ export declare function createWidgetOrchestrator(container: HTMLElement, hostAdapter: HeadlessHostAdapter, initialData?: HeadlessInitialData | null, appearance?: WidgetAppearance, cart?: HydrogenCartPort, coreExports?: WidgetCoreExports, hostHooks?: {
73
+ openCartDrawer?: () => boolean | void;
74
+ }): WidgetOrchestratorHandle;
75
+ export declare const JOY_POINTS_UPDATED_EVENT = "joy:points-updated";
76
+ export declare function readEarningProgramByEvent(blob: JoyMetafieldBlob | undefined, event: string): Record<string, unknown> | undefined;
77
+ export declare function openInNewTab(url: string): void;
78
+ export declare function readCachedReferralLink(): boolean;
79
+ export declare function writeCachedReferralLink(showInvite: boolean): void;
80
+ export interface StoreCreditAccount {
81
+ id?: string;
82
+ amount: number;
83
+ currencyCode: string;
84
+ }
85
+ export declare function pickActiveMarketStoreCredit(accounts: StoreCreditAccount[] | undefined, activeCurrency?: string): {
86
+ balance: number;
87
+ currency: string;
88
+ };
@@ -0,0 +1,499 @@
1
+ import { buildHeadlessFacade } from './render-adapter.js';
2
+ import { hasCachedJoyToken, revokeAndClearJoyToken } from './lib/token.js';
3
+ import { loadRecommendedProducts } from './lib/recommended-loader.js';
4
+ import { createOrchestratorContext } from './orchestrator/context.js';
5
+ import { registerAccountHandlers } from './orchestrator/handlers/account.js';
6
+ import { registerEarnHandlers } from './orchestrator/handlers/earn.js';
7
+ import { registerBirthdayHandlers } from './orchestrator/handlers/birthday.js';
8
+ import { registerMilestoneTierHandlers } from './orchestrator/handlers/milestone-tier.js';
9
+ import { registerReferralHandlers } from './orchestrator/handlers/referral.js';
10
+ import { registerProfileHandlers } from './orchestrator/handlers/profile.js';
11
+ import { registerRedeemHandlers } from './orchestrator/handlers/redeem.js';
12
+ import { GATED_EVENTS } from './orchestrator/gated.js';
13
+ let warnedStaleRecentlyViewedCore = false;
14
+ export function buildAppearanceProps(appearance) {
15
+ return {
16
+ variant: appearance?.variant ?? 'floating-drawer',
17
+ position: appearance?.position ?? 'right',
18
+ theme: appearance?.theme ?? 'light',
19
+ 'primary-color': appearance?.primaryColor,
20
+ 'fab-label': appearance?.fabLabel,
21
+ collapsed: appearance?.collapsed ?? true
22
+ };
23
+ }
24
+ export function buildAppearanceOverrides(appearance) {
25
+ const overrides = {};
26
+ if (appearance?.variant !== undefined)
27
+ overrides.variant = appearance.variant;
28
+ if (appearance?.position !== undefined)
29
+ overrides.position = appearance.position;
30
+ if (appearance?.theme !== undefined)
31
+ overrides.theme = appearance.theme;
32
+ if (appearance?.primaryColor !== undefined)
33
+ overrides['primary-color'] = appearance.primaryColor;
34
+ if (appearance?.fabLabel !== undefined)
35
+ overrides['fab-label'] = appearance.fabLabel;
36
+ if (appearance?.collapsed !== undefined)
37
+ overrides.collapsed = appearance.collapsed;
38
+ return overrides;
39
+ }
40
+ function mapPrograms(programs) {
41
+ const earnPrograms = programs
42
+ .filter(program => program.programType === 'earning')
43
+ .map(program => ({
44
+ id: program.id,
45
+ icon: 'star',
46
+ title: program.title,
47
+ description: program.description,
48
+ points: program.points ?? undefined,
49
+ value: program.points != null ? `+${program.points} pts` : ''
50
+ }));
51
+ const redeemPrograms = programs
52
+ .filter(program => program.programType === 'spending')
53
+ .map(program => ({
54
+ id: program.id,
55
+ icon: 'gift',
56
+ title: program.title,
57
+ description: program.description,
58
+ points: program.pointsCost ?? 0,
59
+ value: program.pointsCost != null ? `${program.pointsCost} pts` : ''
60
+ }));
61
+ return { earnPrograms, redeemPrograms };
62
+ }
63
+ function buildTierBar(customer, tiers) {
64
+ const tierProgress = customer?.tierProgress;
65
+ if (!customer || !tierProgress || typeof customer.tierPoint !== 'number')
66
+ return {};
67
+ const tierPoint = customer.tierPoint;
68
+ if (typeof tierProgress.currentTarget === 'number') {
69
+ if (tierProgress.nextTarget == null) {
70
+ const full = Math.max(1, tierProgress.currentTarget);
71
+ return { progress: full, required: full };
72
+ }
73
+ return {
74
+ progress: Math.max(0, tierPoint - tierProgress.currentTarget),
75
+ required: Math.max(1, tierProgress.nextTarget - tierProgress.currentTarget)
76
+ };
77
+ }
78
+ const nextTarget = tierPoint + tierProgress.pointsToNext;
79
+ const threshold = customer.tier ? tiers?.find(tier => tier.id === customer.tier.id)?.threshold : undefined;
80
+ if (typeof threshold === 'number') {
81
+ return {
82
+ progress: Math.max(0, tierPoint - threshold),
83
+ required: Math.max(1, nextTarget - threshold)
84
+ };
85
+ }
86
+ const ratio = Math.max(0, Math.min(100, tierProgress.percentage));
87
+ return { progress: ratio, required: 100, progressType: 'points' };
88
+ }
89
+ export function buildProps(customer, programs, tiers) {
90
+ const { earnPrograms, redeemPrograms } = mapPrograms(programs);
91
+ const tierProgress = customer?.tierProgress ?? null;
92
+ const tierBar = buildTierBar(customer, tiers);
93
+ return {
94
+ 'logged-in': customer != null,
95
+ 'customer-id': customer?.id ?? '',
96
+ points: customer?.points ?? 0,
97
+ 'current-tier': customer?.tier?.name ?? '',
98
+ 'tier-id': customer?.tier?.id ?? null,
99
+ 'next-tier': tierProgress?.nextTierName ?? '',
100
+ 'tier-progress': tierBar.progress,
101
+ 'tier-required': tierBar.required,
102
+ 'progress-type': tierBar.progressType,
103
+ earnPrograms,
104
+ redeemPrograms
105
+ };
106
+ }
107
+ export function writeProps(element, props) {
108
+ for (const [key, value] of Object.entries(props)) {
109
+ if (value === undefined || value === null)
110
+ continue;
111
+ const property = key.replace(/-([a-z])/g, (_, character) => character.toUpperCase());
112
+ if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
113
+ element[property] = value;
114
+ }
115
+ else if (typeof value === 'boolean') {
116
+ element[property] = value;
117
+ element.toggleAttribute(key, value);
118
+ }
119
+ else {
120
+ element.setAttribute(key, String(value));
121
+ }
122
+ }
123
+ }
124
+ export function detail(event) {
125
+ return (event.detail ?? {});
126
+ }
127
+ const GUIDE_MODAL_STYLE_ID = 'Avada-Joy-modal-styles';
128
+ const GUIDE_MODAL_STYLE = `
129
+ #Avada-Joy-modal {
130
+ display: none;
131
+ position: fixed;
132
+ inset: 0;
133
+ z-index: 2147483647;
134
+ }
135
+ #Avada-Joy-modal.modal-show {
136
+ display: block;
137
+ }
138
+ #Avada-Joy-modal .Avada-modal-overlay {
139
+ position: fixed;
140
+ inset: 0;
141
+ background: rgba(0, 0, 0, 0.5);
142
+ opacity: 0.8;
143
+ }
144
+ #Avada-Joy-modal .Avada-modal-container {
145
+ position: fixed;
146
+ inset: 0;
147
+ display: flex;
148
+ align-items: center;
149
+ justify-content: center;
150
+ pointer-events: none;
151
+ }
152
+ #Avada-Joy-modal .modal-wrapper {
153
+ position: relative;
154
+ background: #fff;
155
+ border-radius: 12px;
156
+ max-width: 1000px;
157
+ max-height: 600px;
158
+ width: 90%;
159
+ overflow-y: auto;
160
+ padding: 24px;
161
+ pointer-events: auto;
162
+ box-shadow: 0 20px 60px rgba(0,0,0,0.3);
163
+ }
164
+ #Avada-Joy-modal .modal-content {
165
+ line-height: 1.6;
166
+ font-size: 14px;
167
+ color: #333;
168
+ }
169
+ #Avada-Joy-modal .modal-content img {
170
+ max-width: 100%;
171
+ height: auto;
172
+ }
173
+ #Avada-Joy-modal .modal-close {
174
+ position: absolute;
175
+ top: 12px;
176
+ right: 12px;
177
+ width: 32px;
178
+ height: 32px;
179
+ background: rgba(0,0,0,0.05);
180
+ border: none;
181
+ border-radius: 50%;
182
+ font-size: 20px;
183
+ line-height: 1;
184
+ cursor: pointer;
185
+ display: flex;
186
+ align-items: center;
187
+ justify-content: center;
188
+ color: #666;
189
+ transition: background 0.2s;
190
+ }
191
+ #Avada-Joy-modal .modal-close:hover {
192
+ background: rgba(0,0,0,0.1);
193
+ }
194
+ `;
195
+ export async function openGuideModal(guide) {
196
+ if (!guide)
197
+ return;
198
+ const { default: DOMPurify } = await import('dompurify');
199
+ let modalEl = document.getElementById('Avada-Joy-modal');
200
+ if (!modalEl) {
201
+ modalEl = document.createElement('div');
202
+ modalEl.id = 'Avada-Joy-modal';
203
+ document.body.appendChild(modalEl);
204
+ }
205
+ const modal = modalEl;
206
+ const handleEsc = (ev) => {
207
+ if (ev.key === 'Escape')
208
+ closeModal();
209
+ };
210
+ const closeModal = () => {
211
+ modal.classList.remove('modal-show');
212
+ document.removeEventListener('keydown', handleEsc);
213
+ setTimeout(() => {
214
+ modal.textContent = '';
215
+ }, 300);
216
+ };
217
+ document.addEventListener('keydown', handleEsc);
218
+ const overlay = document.createElement('div');
219
+ overlay.className = 'Avada-modal-overlay';
220
+ overlay.addEventListener('click', closeModal);
221
+ const container = document.createElement('div');
222
+ container.className = 'Avada-modal-container';
223
+ const wrapper = document.createElement('div');
224
+ wrapper.className = 'modal-wrapper';
225
+ const content = document.createElement('div');
226
+ content.id = 'avada-modal-content';
227
+ content.className = 'modal-content';
228
+ const clean = DOMPurify.sanitize(guide, { USE_PROFILES: { html: true }, ADD_ATTR: ['target'] });
229
+ const contentTemplate = document.createElement('template');
230
+ contentTemplate.innerHTML = clean;
231
+ content.appendChild(contentTemplate.content);
232
+ const closeBtn = document.createElement('button');
233
+ closeBtn.title = 'Close (Esc)';
234
+ closeBtn.type = 'button';
235
+ closeBtn.className = 'modal-close';
236
+ closeBtn.textContent = '×';
237
+ closeBtn.addEventListener('click', closeModal);
238
+ wrapper.appendChild(content);
239
+ wrapper.appendChild(closeBtn);
240
+ container.appendChild(wrapper);
241
+ modal.textContent = '';
242
+ modal.appendChild(overlay);
243
+ modal.appendChild(container);
244
+ if (!document.getElementById(GUIDE_MODAL_STYLE_ID)) {
245
+ const style = document.createElement('style');
246
+ style.id = GUIDE_MODAL_STYLE_ID;
247
+ style.textContent = GUIDE_MODAL_STYLE;
248
+ document.head.appendChild(style);
249
+ }
250
+ requestAnimationFrame(() => {
251
+ modal.classList.add('modal-show');
252
+ });
253
+ }
254
+ export function createWidgetOrchestrator(container, hostAdapter, initialData, appearance, cart, coreExports, hostHooks = {}) {
255
+ const ctx = createOrchestratorContext({
256
+ container,
257
+ hostAdapter,
258
+ initialData,
259
+ appearance,
260
+ cart,
261
+ coreExports,
262
+ openCartDrawer: hostHooks.openCartDrawer
263
+ });
264
+ const { element, controller, renderContext, useBlobPath, shouldLoad, render, surface, tLabel, isAuthed, refresh } = ctx;
265
+ bindEvents();
266
+ const ready = refresh();
267
+ loadRecentlyViewed();
268
+ loadRecommended();
269
+ const isGuestAtMount = !initialData?.customer && !initialData?.shopifyCustomer && !hasCachedJoyToken();
270
+ if (isGuestAtMount)
271
+ ctx.loadMilestone();
272
+ if (shouldLoad)
273
+ void ready.finally(() => writeProps(element, { loading: false }));
274
+ const authUnsubscribe = hostAdapter.auth.subscribe(state => {
275
+ const wasGuest = ctx.previousStatus === 'guest';
276
+ const wasAuthenticated = ctx.previousStatus === 'authenticated';
277
+ ctx.previousStatus = state.status;
278
+ if (wasGuest && state.status === 'authenticated') {
279
+ void refresh();
280
+ return;
281
+ }
282
+ if (wasAuthenticated && state.status === 'guest') {
283
+ revokeAndClearJoyToken({ apiBase: hostAdapter.context().apiUrl });
284
+ ctx.activeCustomer = undefined;
285
+ render(ctx.activeCustomer, initialData?.programs ?? []);
286
+ }
287
+ });
288
+ function onPointsUpdated(event) {
289
+ const points = event.detail?.points;
290
+ if (typeof points !== 'number' || !isAuthed())
291
+ return;
292
+ writeProps(element, { points });
293
+ ctx.patchCustomer({ point: points });
294
+ }
295
+ window.addEventListener(JOY_POINTS_UPDATED_EVENT, onPointsUpdated);
296
+ function bindEvents() {
297
+ const account = registerAccountHandlers(ctx);
298
+ const referral = registerReferralHandlers(ctx);
299
+ const profile = registerProfileHandlers(ctx);
300
+ const redeem = registerRedeemHandlers(ctx);
301
+ const { replaceEarnPrograms } = registerEarnHandlers(ctx);
302
+ registerBirthdayHandlers(ctx, { replaceEarnPrograms, buildLoaderFacade });
303
+ controller.on('joy-login-click', () => hostAdapter.navigate({ type: 'login' }));
304
+ registerMilestoneTierHandlers(ctx, { buildLoaderFacade });
305
+ controller.on('joy-signup-click', () => hostAdapter.navigate({ type: 'register' }));
306
+ controller.on('joy-host-navigate', event => {
307
+ const d = detail(event);
308
+ if (d.type === 'hash' && d.hash) {
309
+ hostAdapter.navigate({ type: 'hash', hash: d.hash });
310
+ return;
311
+ }
312
+ if (d.type && d.type !== 'hash') {
313
+ hostAdapter.navigate({ type: d.type, url: d.url, view: d.view });
314
+ return;
315
+ }
316
+ if (!d.url)
317
+ return;
318
+ if (isLogoutNavigation(d.url, hostAdapter.context().routesRoot)) {
319
+ revokeAndClearJoyToken({ apiBase: hostAdapter.context().apiUrl });
320
+ submitLogout(d.url);
321
+ return;
322
+ }
323
+ if (!isSafeNavigationUrl(d.url))
324
+ return;
325
+ if (d.sameTab)
326
+ hostAdapter.navigate({ type: 'external', url: d.url });
327
+ else
328
+ openInNewTab(d.url);
329
+ });
330
+ controller.on('joy-widget-toggle', event => {
331
+ const { isOpen } = detail(event);
332
+ if (typeof isOpen === 'boolean')
333
+ writeProps(element, { collapsed: !isOpen });
334
+ if (!isOpen)
335
+ return;
336
+ ctx.panelOpened = true;
337
+ if (ctx.preloadDeferred && isAuthed())
338
+ ctx.loadCustomerSections();
339
+ });
340
+ controller.on('joy-view-change', event => {
341
+ if (!isAuthed())
342
+ return;
343
+ const { view } = detail(event);
344
+ redeem.restoreAvailableCouponsOnLeave(view);
345
+ if (view === 'coupons')
346
+ redeem.openCouponsView();
347
+ else if (view === 'activities')
348
+ ctx.loadActivities();
349
+ else if (view === 'points-history')
350
+ ctx.loadActivities(undefined, undefined, 'pointHistory');
351
+ else if (view === 'profile')
352
+ profile.loadAddresses();
353
+ else if (view === 'referral') {
354
+ ctx.loadReferral();
355
+ referral.loadReferralHistory();
356
+ }
357
+ else if (view === 'milestone')
358
+ ctx.loadMilestone();
359
+ else if (view === 'perks')
360
+ ctx.loadTierPerks();
361
+ else if (view === 'orders')
362
+ account.loadOrders();
363
+ else if (view === 'store-credit-detail')
364
+ account.loadStoreCreditTransactions();
365
+ });
366
+ controller.on('joy-show-guide', event => {
367
+ const { guide } = detail(event);
368
+ if (guide)
369
+ void openGuideModal(guide);
370
+ });
371
+ for (const name of GATED_EVENTS) {
372
+ controller.on(name, event => {
373
+ event.preventDefault?.();
374
+ });
375
+ }
376
+ }
377
+ function buildLoaderFacade() {
378
+ if (!useBlobPath)
379
+ return null;
380
+ const built = buildHeadlessFacade({
381
+ blob: ctx.activeBlob,
382
+ customer: ctx.activeCustomer,
383
+ shopifyCustomer: initialData?.shopifyCustomer,
384
+ context: renderContext,
385
+ coreExports
386
+ });
387
+ if (!built)
388
+ return null;
389
+ const { facade } = built;
390
+ facade.hostAdapter.data = hostAdapter.data;
391
+ facade.widgetEl = element;
392
+ return facade;
393
+ }
394
+ function loadRecentlyViewed() {
395
+ const track = coreExports?.trackAndLoadRecentlyViewed;
396
+ const facade = typeof track === 'function' ? buildLoaderFacade() : null;
397
+ if (!track || !facade) {
398
+ element.recentlyViewedLoading = false;
399
+ if (!track && !warnedStaleRecentlyViewedCore) {
400
+ warnedStaleRecentlyViewedCore = true;
401
+ console.warn('[joy] recently viewed skipped: the loaded widget core has no `trackAndLoadRecentlyViewed` ' +
402
+ 'export (CDN artifact predates it — rebuild/republish, or point `assetUrl` at a local build)');
403
+ }
404
+ return;
405
+ }
406
+ surface(Promise.resolve(track(facade)));
407
+ }
408
+ function loadRecommended() {
409
+ const facade = buildLoaderFacade();
410
+ if (!facade)
411
+ return;
412
+ const settings = facade.data?.settings;
413
+ void loadRecommendedProducts({
414
+ widgetEl: element,
415
+ sections: Array.isArray(settings?.sections) ? settings.sections : [],
416
+ productCard: coreExports?.productCard,
417
+ currency: renderContext?.currency
418
+ });
419
+ }
420
+ return {
421
+ ready,
422
+ dispose: () => {
423
+ controller.dispose();
424
+ authUnsubscribe();
425
+ window.removeEventListener(JOY_POINTS_UPDATED_EVENT, onPointsUpdated);
426
+ }
427
+ };
428
+ }
429
+ export const JOY_POINTS_UPDATED_EVENT = 'joy:points-updated';
430
+ export function readEarningProgramByEvent(blob, event) {
431
+ const program = blob && typeof blob === 'object' ? blob.program : undefined;
432
+ const earning = program && typeof program === 'object' ? program.earning : undefined;
433
+ if (!Array.isArray(earning))
434
+ return undefined;
435
+ return earning.find(p => p?.event === event);
436
+ }
437
+ export function openInNewTab(url) {
438
+ if (typeof document === 'undefined')
439
+ return;
440
+ const a = document.createElement('a');
441
+ a.href = url;
442
+ a.target = '_blank';
443
+ a.rel = 'noopener noreferrer';
444
+ a.click();
445
+ }
446
+ function isSafeNavigationUrl(url) {
447
+ try {
448
+ const base = typeof location === 'undefined' ? 'https://localhost' : location.href;
449
+ return ['http:', 'https:', 'mailto:', 'tel:'].includes(new URL(url, base).protocol);
450
+ }
451
+ catch {
452
+ return false;
453
+ }
454
+ }
455
+ function isLogoutNavigation(url, routesRoot) {
456
+ const suffix = 'account/logout';
457
+ try {
458
+ const path = new URL(url, 'http://x/').pathname.replace(/^\/+|\/+$/g, '');
459
+ return path === suffix || path.endsWith(`/${suffix}`);
460
+ }
461
+ catch {
462
+ const expected = `${routesRoot || '/'}${suffix}`.replace(/\/+/g, '/');
463
+ return url === expected;
464
+ }
465
+ }
466
+ function submitLogout(url) {
467
+ if (typeof document === 'undefined')
468
+ return;
469
+ const form = document.createElement('form');
470
+ form.method = 'POST';
471
+ form.action = url;
472
+ form.style.display = 'none';
473
+ document.body.appendChild(form);
474
+ form.submit();
475
+ }
476
+ const REFERRAL_SHOW_INVITE_STORAGE_KEY = 'joy:referral:showInvite';
477
+ export function readCachedReferralLink() {
478
+ try {
479
+ return typeof localStorage === 'undefined' ? false : localStorage.getItem(REFERRAL_SHOW_INVITE_STORAGE_KEY) === 'true';
480
+ }
481
+ catch {
482
+ return false;
483
+ }
484
+ }
485
+ export function writeCachedReferralLink(showInvite) {
486
+ try {
487
+ if (typeof localStorage === 'undefined')
488
+ return;
489
+ localStorage.setItem(REFERRAL_SHOW_INVITE_STORAGE_KEY, String(showInvite));
490
+ }
491
+ catch {
492
+ }
493
+ }
494
+ export function pickActiveMarketStoreCredit(accounts, activeCurrency = '') {
495
+ if (!accounts?.length)
496
+ return { balance: 0, currency: activeCurrency };
497
+ const matched = activeCurrency ? accounts.find(a => a.currencyCode === activeCurrency) : accounts[0];
498
+ return { balance: matched?.amount || 0, currency: matched?.currencyCode || activeCurrency };
499
+ }