@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,160 @@
1
+ import { JOY_CDN_ORIGIN } from '../csp.js';
2
+ const WIDGET_CORE_PATH = '/widget-v4/latest/index.js';
3
+ const WIDGET_CORE_MANIFEST_PATH = '/widget-v4/latest/build.json';
4
+ export const SUPPORTED_CORE_API_VERSION = 1;
5
+ const CORE_SCRIPT_ATTR = 'data-joy-widget-core';
6
+ export const CORE_PRELOAD_ATTR = 'data-joy-widget-core-preload';
7
+ export const CORE_CSS_ATTR = 'data-joy-widget-core-css';
8
+ const PRECONNECT_ATTR = 'data-joy-widget-preconnect';
9
+ const CORE_GLOBAL = '__JOY_WIDGET_CORE__';
10
+ const LOAD_MEMO_GLOBAL = '__JOY_CORE_LOAD__';
11
+ let loadPromise = null;
12
+ export function loadWidgetCore(options = {}) {
13
+ if (loadPromise)
14
+ return loadPromise;
15
+ const shared = typeof window === 'undefined' ? undefined : window[LOAD_MEMO_GLOBAL];
16
+ if (shared)
17
+ return (loadPromise = shared);
18
+ const promise = resolveManifest(options.assetUrl, options.core).then(manifest => {
19
+ if (!isCoreApiCompatible(manifest))
20
+ return { loaded: false };
21
+ if (options.core)
22
+ preloadWidgetCore(options.core, { assetUrl: options.assetUrl, lazy: options.preloadLazy });
23
+ return loadViaScriptTag(versionedScriptUrl(options.assetUrl, manifest)).then(result => {
24
+ if (!result.loaded) {
25
+ forgetLoad(promise);
26
+ return result;
27
+ }
28
+ const core = readCoreGlobal();
29
+ return core ? { loaded: true, coreExports: core } : result;
30
+ });
31
+ });
32
+ loadPromise = promise;
33
+ if (typeof window !== 'undefined')
34
+ window[LOAD_MEMO_GLOBAL] = promise;
35
+ return promise;
36
+ }
37
+ function forgetLoad(promise) {
38
+ if (loadPromise === promise)
39
+ loadPromise = null;
40
+ if (typeof window === 'undefined')
41
+ return;
42
+ const w = window;
43
+ if (w[LOAD_MEMO_GLOBAL] === promise)
44
+ w[LOAD_MEMO_GLOBAL] = null;
45
+ }
46
+ function readCoreGlobal() {
47
+ if (typeof window === 'undefined')
48
+ return undefined;
49
+ return window[CORE_GLOBAL];
50
+ }
51
+ function loadViaScriptTag(url) {
52
+ return new Promise(resolve => {
53
+ const existing = document.querySelector(`script[${CORE_SCRIPT_ATTR}]`);
54
+ if (existing) {
55
+ if (readCoreGlobal() || customElements.get('joy-loyalty-widget')) {
56
+ resolve({ loaded: true });
57
+ return;
58
+ }
59
+ attach(existing, resolve);
60
+ return;
61
+ }
62
+ const script = document.createElement('script');
63
+ script.type = 'module';
64
+ script.crossOrigin = 'anonymous';
65
+ script.src = url;
66
+ script.setAttribute(CORE_SCRIPT_ATTR, '');
67
+ attach(script, resolve);
68
+ document.head.appendChild(script);
69
+ });
70
+ }
71
+ function attach(script, resolve) {
72
+ script.addEventListener('load', () => resolve({ loaded: true }), { once: true });
73
+ script.addEventListener('error', () => {
74
+ console.warn('[joy] failed to load the widget core from the CDN');
75
+ script.remove();
76
+ resolve({ loaded: false });
77
+ }, { once: true });
78
+ }
79
+ export function preconnectWidgetCore(options = {}) {
80
+ if (typeof document === 'undefined')
81
+ return;
82
+ const origin = resolveOrigin(options.assetUrl);
83
+ if (document.querySelector(`link[${PRECONNECT_ATTR}="${origin}"]`))
84
+ return;
85
+ const link = document.createElement('link');
86
+ link.rel = 'preconnect';
87
+ link.href = origin;
88
+ link.crossOrigin = 'anonymous';
89
+ link.setAttribute(PRECONNECT_ATTR, origin);
90
+ document.head.appendChild(link);
91
+ }
92
+ function resolveOrigin(assetUrl) {
93
+ return (assetUrl ?? JOY_CDN_ORIGIN).replace(/\/+$/, '');
94
+ }
95
+ export function resolveWidgetCoreAssetUrls(manifest, options = {}) {
96
+ const base = `${resolveOrigin(options.assetUrl)}/widget-v4/latest/`;
97
+ const lazy = (options.lazy ?? []).flatMap(group => manifest.lazy?.[group] ?? []);
98
+ const modules = [...(manifest.entry ? [manifest.entry] : []), ...(manifest.imports ?? []), ...lazy].map(path => base + path);
99
+ const css = (manifest.css ?? []).map(path => ({ href: base + path, name: path.split('/').pop() ?? path }));
100
+ return { modules, css };
101
+ }
102
+ export function preloadWidgetCore(manifest, options = {}) {
103
+ if (typeof document === 'undefined')
104
+ return;
105
+ const { modules, css } = resolveWidgetCoreAssetUrls(manifest, options);
106
+ for (const href of modules) {
107
+ if (document.querySelector(`link[${CORE_PRELOAD_ATTR}][href="${href}"]`))
108
+ continue;
109
+ const link = document.createElement('link');
110
+ link.rel = 'modulepreload';
111
+ link.href = href;
112
+ link.crossOrigin = 'anonymous';
113
+ link.setAttribute(CORE_PRELOAD_ATTR, '');
114
+ document.head.appendChild(link);
115
+ }
116
+ for (const { href, name } of css) {
117
+ if (document.querySelector(`link[${CORE_CSS_ATTR}="${name}"]`))
118
+ continue;
119
+ const link = document.createElement('link');
120
+ link.rel = 'stylesheet';
121
+ link.href = href;
122
+ link.setAttribute(CORE_CSS_ATTR, name);
123
+ document.head.appendChild(link);
124
+ }
125
+ }
126
+ export function isCoreApiCompatible(manifest) {
127
+ const version = manifest?.coreApiVersion ?? 1;
128
+ if (version > SUPPORTED_CORE_API_VERSION) {
129
+ console.error(`[joy] the widget core on the CDN is API v${version}; this @joy-loyalty/hydrogen build supports v${SUPPORTED_CORE_API_VERSION}. ` +
130
+ 'The widget will not load — upgrade @joy-loyalty/hydrogen.');
131
+ return false;
132
+ }
133
+ if (version < SUPPORTED_CORE_API_VERSION) {
134
+ console.warn(`[joy] the widget core on the CDN is API v${version}, older than the v${SUPPORTED_CORE_API_VERSION} this @joy-loyalty/hydrogen build expects — loading with reduced features.`);
135
+ }
136
+ return true;
137
+ }
138
+ async function resolveManifest(assetUrl, core) {
139
+ if (core?.buildId)
140
+ return core;
141
+ try {
142
+ const res = await fetch(`${resolveOrigin(assetUrl)}${WIDGET_CORE_MANIFEST_PATH}`, { cache: 'no-store' });
143
+ if (!res.ok)
144
+ return undefined;
145
+ const body = (await res.json());
146
+ if (typeof body?.buildId !== 'string' || !body.buildId)
147
+ return undefined;
148
+ return {
149
+ buildId: body.buildId,
150
+ ...(Number.isInteger(body.coreApiVersion) ? { coreApiVersion: body.coreApiVersion } : {})
151
+ };
152
+ }
153
+ catch {
154
+ return undefined;
155
+ }
156
+ }
157
+ function versionedScriptUrl(assetUrl, manifest) {
158
+ const url = `${resolveOrigin(assetUrl)}${WIDGET_CORE_PATH}`;
159
+ return manifest ? `${url}?v=${encodeURIComponent(manifest.buildId)}` : url;
160
+ }
@@ -0,0 +1,7 @@
1
+ import type { WidgetCoreManifest } from './core-loader.js';
2
+ export interface GetWidgetCoreManifestOptions {
3
+ assetUrl?: string;
4
+ fetch?: typeof fetch;
5
+ }
6
+ export declare function getWidgetCoreManifest(options?: GetWidgetCoreManifestOptions): Promise<WidgetCoreManifest | undefined>;
7
+ export declare function clearWidgetCoreManifestCache(): void;
@@ -0,0 +1,54 @@
1
+ import { JOY_CDN_ORIGIN } from '../csp.js';
2
+ const MANIFEST_PATH = '/widget-v4/latest/build.json';
3
+ const MANIFEST_TTL_MS = 60_000;
4
+ const cache = new Map();
5
+ export function getWidgetCoreManifest(options = {}) {
6
+ const origin = (options.assetUrl ?? JOY_CDN_ORIGIN).replace(/\/+$/, '');
7
+ const now = Date.now();
8
+ const hit = cache.get(origin);
9
+ if (hit && hit.expires > now)
10
+ return hit.value;
11
+ const fetchImpl = options.fetch ?? globalThis.fetch;
12
+ const value = fetchManifest(fetchImpl, `${origin}${MANIFEST_PATH}`).then(manifest => {
13
+ if (!manifest)
14
+ cache.delete(origin);
15
+ return manifest;
16
+ });
17
+ cache.set(origin, { expires: now + MANIFEST_TTL_MS, value });
18
+ return value;
19
+ }
20
+ export function clearWidgetCoreManifestCache() {
21
+ cache.clear();
22
+ }
23
+ async function fetchManifest(fetchImpl, url) {
24
+ try {
25
+ const res = await fetchImpl(url);
26
+ if (!res.ok)
27
+ return undefined;
28
+ const body = (await res.json());
29
+ if (!body || typeof body.buildId !== 'string' || !body.buildId)
30
+ return undefined;
31
+ return {
32
+ buildId: body.buildId,
33
+ ...(Number.isInteger(body.coreApiVersion) ? { coreApiVersion: body.coreApiVersion } : {}),
34
+ ...(typeof body.entry === 'string' ? { entry: body.entry } : {}),
35
+ ...(Array.isArray(body.imports) ? { imports: body.imports.filter(isString) } : {}),
36
+ ...(Array.isArray(body.css) ? { css: body.css.filter(isString) } : {}),
37
+ ...(body.lazy && typeof body.lazy === 'object' ? { lazy: pickStringLists(body.lazy) } : {})
38
+ };
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ function isString(value) {
45
+ return typeof value === 'string';
46
+ }
47
+ function pickStringLists(value) {
48
+ const out = {};
49
+ for (const [key, list] of Object.entries(value)) {
50
+ if (Array.isArray(list))
51
+ out[key] = list.filter(isString);
52
+ }
53
+ return out;
54
+ }
@@ -0,0 +1,8 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { WidgetCoreManifest } from './core-loader.js';
3
+ export interface WidgetCorePreloadLinksProps {
4
+ core?: WidgetCoreManifest | null;
5
+ assetUrl?: string;
6
+ lazy?: string[];
7
+ }
8
+ export declare function WidgetCorePreloadLinks({ core, assetUrl, lazy }: WidgetCorePreloadLinksProps): ReactNode;
@@ -0,0 +1,8 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { CORE_CSS_ATTR, CORE_PRELOAD_ATTR, resolveWidgetCoreAssetUrls } from './core-loader.js';
3
+ export function WidgetCorePreloadLinks({ core, assetUrl, lazy }) {
4
+ if (!core)
5
+ return null;
6
+ const { modules, css } = resolveWidgetCoreAssetUrls(core, { assetUrl, lazy });
7
+ return (_jsxs(_Fragment, { children: [modules.map(href => (_jsx("link", { rel: "modulepreload", href: href, crossOrigin: "anonymous", [CORE_PRELOAD_ATTR]: '' }, href))), css.map(({ href, name }) => (_jsx("link", { rel: "stylesheet", href: href, precedence: "joy-widget-core", [CORE_CSS_ATTR]: name }, href)))] }));
8
+ }
@@ -0,0 +1,95 @@
1
+ export interface HeadlessRedeemedReward {
2
+ rewardId: string;
3
+ programId: string | null;
4
+ key: string;
5
+ title: string;
6
+ description?: string;
7
+ rewardType: string | null;
8
+ rewardValue: number | null;
9
+ couponCode: string | null;
10
+ status: string;
11
+ expiresAt: string | null;
12
+ startsAt?: string | null;
13
+ giftVariantId: string | null;
14
+ conditions?: string[];
15
+ balanceRemaining?: number | null;
16
+ partiallyUsed?: boolean;
17
+ freeGiftProducts?: SdkGiftProductLike[];
18
+ freeGiftMode?: 'all' | 'one' | null;
19
+ freeGiftSelectedVariantId?: string | null;
20
+ }
21
+ export interface SdkGiftProductLike {
22
+ id?: string;
23
+ title?: string;
24
+ image?: string | null;
25
+ handle?: string | null;
26
+ variants?: Array<{
27
+ id?: string;
28
+ title?: string;
29
+ }>;
30
+ }
31
+ export interface HeadlessReceivedReward extends HeadlessRedeemedReward {
32
+ senderName?: string;
33
+ senderEmail?: string;
34
+ }
35
+ export interface SpendingProgramLike {
36
+ id?: string;
37
+ event?: string;
38
+ freeProductQuantity?: string;
39
+ variantId?: string | number;
40
+ variantIds?: Array<string | number>;
41
+ specificProducts?: SpecificProductLike[];
42
+ sendRewardToFriend?: boolean;
43
+ }
44
+ interface SpecificProductLike {
45
+ id?: string | number;
46
+ title?: string;
47
+ handle?: string;
48
+ image?: {
49
+ src?: string;
50
+ } | string | null;
51
+ variants?: Array<{
52
+ id?: string | number;
53
+ title?: string;
54
+ src?: string;
55
+ }>;
56
+ }
57
+ export interface HeadlessFreeGiftProduct {
58
+ title: string;
59
+ image: string;
60
+ handle: string;
61
+ quantity: number;
62
+ variantId: string;
63
+ variantTitle: string;
64
+ }
65
+ export interface HeadlessCouponItem {
66
+ discount: string;
67
+ label: string;
68
+ title: string;
69
+ code: string;
70
+ expiry: string;
71
+ rewardId?: string;
72
+ programId?: string;
73
+ status?: 'available' | 'used' | 'expired' | 'revoked';
74
+ event?: string;
75
+ type?: 'amount_off' | 'percentage_off' | 'free_shipping' | 'free_product' | 'free_collection';
76
+ conditions?: string[];
77
+ programDescription?: string;
78
+ sendRewardToFriend?: boolean;
79
+ freeGiftProducts?: HeadlessFreeGiftProduct[];
80
+ freeGiftMode?: 'all' | 'one';
81
+ freeGiftSelectedVariantId?: string;
82
+ source?: 'received';
83
+ senderName?: string;
84
+ senderEmail?: string;
85
+ partiallyUsed?: boolean;
86
+ }
87
+ export interface MapCouponOptions {
88
+ spendingPrograms?: SpendingProgramLike[];
89
+ translation?: Record<string, string>;
90
+ currency?: string;
91
+ locale?: string;
92
+ }
93
+ export declare function mapRedeemedRewardsToCoupons(redeemed: readonly HeadlessRedeemedReward[] | undefined, options?: MapCouponOptions): HeadlessCouponItem[];
94
+ export declare function mapReceivedRewardsToCoupons(received: readonly HeadlessReceivedReward[] | undefined, options?: MapCouponOptions): HeadlessCouponItem[];
95
+ export {};
@@ -0,0 +1,167 @@
1
+ const DEFAULT_VARIANT_TITLE = 'Default Title';
2
+ const REWARD_TYPE_TO_COUPON_TYPE = {
3
+ percentage: 'percentage_off',
4
+ fixed_amount: 'amount_off',
5
+ free_shipping: 'free_shipping',
6
+ free_product: 'free_product'
7
+ };
8
+ function translate(translation, key) {
9
+ return translation[`[[WidgetV4]]${key}`] || key;
10
+ }
11
+ function productImage(product) {
12
+ const img = product.image;
13
+ if (typeof img === 'string')
14
+ return img;
15
+ if (img && typeof img === 'object' && img.src)
16
+ return img.src;
17
+ return product.variants?.[0]?.src || '';
18
+ }
19
+ function mapStatus(status) {
20
+ if (status === 'used')
21
+ return 'used';
22
+ if (status === 'expired')
23
+ return 'expired';
24
+ return 'available';
25
+ }
26
+ function formatExpiry(iso, locale) {
27
+ if (!iso)
28
+ return '';
29
+ const date = new Date(iso);
30
+ return Number.isNaN(date.getTime()) ? '' : date.toLocaleDateString(locale || undefined);
31
+ }
32
+ function buildDiscountLabel(reward, translation, currency) {
33
+ if (reward.key === 'gift_card') {
34
+ const tpl = translate(translation, '{{amount}} gift card');
35
+ const value = reward.balanceRemaining ?? reward.rewardValue ?? 0;
36
+ const amount = currency ? `${currency} ${value}` : `${value}`;
37
+ return { discount: tpl.replace('{{amount}}', amount), label: '' };
38
+ }
39
+ switch (reward.rewardType) {
40
+ case 'free_product':
41
+ return { discount: translate(translation, 'Free Gift'), label: '' };
42
+ case 'free_shipping':
43
+ return { discount: translate(translation, 'Free Shipping'), label: '' };
44
+ case 'percentage': {
45
+ const tpl = translate(translation, '{{amount}} discount');
46
+ return { discount: tpl.replace('{{amount}}', `${reward.rewardValue ?? 0}%`), label: '' };
47
+ }
48
+ case 'fixed_amount': {
49
+ const tpl = translate(translation, '{{amount}} discount');
50
+ const amount = currency ? `${currency} ${reward.rewardValue ?? 0}` : `${reward.rewardValue ?? 0}`;
51
+ return { discount: tpl.replace('{{amount}}', amount), label: '' };
52
+ }
53
+ default:
54
+ return { discount: reward.title || translate(translation, 'Reward'), label: '' };
55
+ }
56
+ }
57
+ function buildFreeGiftProducts(program, mode, selectedVariantId) {
58
+ const specificProducts = Array.isArray(program?.specificProducts) ? program.specificProducts : [];
59
+ const allowed = mode === 'one' && selectedVariantId
60
+ ? new Set([String(selectedVariantId)])
61
+ : program?.variantIds?.length
62
+ ? new Set(program.variantIds.map(String))
63
+ : null;
64
+ return specificProducts.filter(Boolean).flatMap(product => {
65
+ const image = productImage(product);
66
+ return (product.variants || [])
67
+ .filter(variant => variant?.id != null && (!allowed || allowed.has(String(variant.id))))
68
+ .map(variant => ({
69
+ title: product.title || '',
70
+ image: variant.src || image,
71
+ handle: product.handle || '',
72
+ quantity: 1,
73
+ variantId: String(variant.id),
74
+ variantTitle: variant.title === DEFAULT_VARIANT_TITLE ? '' : variant.title || ''
75
+ }));
76
+ });
77
+ }
78
+ function mapSdkGiftProducts(products, mode, selectedVariantId) {
79
+ const allowed = mode === 'one' && selectedVariantId ? new Set([String(selectedVariantId)]) : null;
80
+ return products.filter(Boolean).flatMap(product => {
81
+ const image = product.image || '';
82
+ return (product.variants || [])
83
+ .filter(variant => variant?.id != null && (!allowed || allowed.has(String(variant.id))))
84
+ .map(variant => ({
85
+ title: product.title || '',
86
+ image,
87
+ handle: product.handle || '',
88
+ quantity: 1,
89
+ variantId: String(variant.id),
90
+ variantTitle: variant.title === DEFAULT_VARIANT_TITLE ? '' : variant.title || ''
91
+ }));
92
+ });
93
+ }
94
+ function buildContext(options) {
95
+ const { spendingPrograms = [], translation = {}, currency = '', locale } = options;
96
+ const programsById = new Map();
97
+ for (const program of spendingPrograms) {
98
+ if (program?.id)
99
+ programsById.set(String(program.id), program);
100
+ }
101
+ return { programsById, translation, currency, locale };
102
+ }
103
+ function buildCoupon(reward, ctx) {
104
+ const { programsById, translation, currency, locale } = ctx;
105
+ const program = reward.programId ? programsById.get(String(reward.programId)) : undefined;
106
+ const { discount, label } = buildDiscountLabel(reward, translation, currency);
107
+ const coupon = {
108
+ discount,
109
+ label,
110
+ title: reward.title || translate(translation, 'Reward'),
111
+ code: reward.couponCode || '',
112
+ expiry: formatExpiry(reward.expiresAt, locale),
113
+ rewardId: reward.rewardId,
114
+ programId: reward.programId || '',
115
+ status: mapStatus(reward.status),
116
+ event: reward.key || '',
117
+ conditions: reward.conditions || [],
118
+ programDescription: reward.description || '',
119
+ sendRewardToFriend: Boolean(program?.sendRewardToFriend),
120
+ partiallyUsed: !!reward.partiallyUsed
121
+ };
122
+ const isFreeGift = reward.rewardType === 'free_product' || reward.key === 'free_gift';
123
+ if (isFreeGift) {
124
+ const mode = reward.freeGiftMode === 'one' || reward.freeGiftMode === 'all'
125
+ ? reward.freeGiftMode
126
+ : program?.freeProductQuantity === 'one'
127
+ ? 'one'
128
+ : 'all';
129
+ const chosenVariantId = reward.freeGiftSelectedVariantId ?? reward.giftVariantId;
130
+ const selectedVariantId = mode === 'one' && chosenVariantId ? String(chosenVariantId) : undefined;
131
+ let freeGiftProducts = reward.freeGiftProducts?.length
132
+ ? mapSdkGiftProducts(reward.freeGiftProducts, mode, selectedVariantId)
133
+ : buildFreeGiftProducts(program, mode, selectedVariantId);
134
+ if (!freeGiftProducts.length && reward.giftVariantId) {
135
+ freeGiftProducts = [
136
+ { title: coupon.title, image: '', handle: '', quantity: 1, variantId: String(reward.giftVariantId), variantTitle: '' }
137
+ ];
138
+ }
139
+ if (freeGiftProducts.length) {
140
+ coupon.freeGiftProducts = freeGiftProducts;
141
+ coupon.freeGiftMode = mode;
142
+ coupon.freeGiftSelectedVariantId = selectedVariantId || '';
143
+ coupon.type = 'free_product';
144
+ return coupon;
145
+ }
146
+ }
147
+ const type = reward.rewardType ? REWARD_TYPE_TO_COUPON_TYPE[reward.rewardType] : undefined;
148
+ if (type)
149
+ coupon.type = type;
150
+ return coupon;
151
+ }
152
+ export function mapRedeemedRewardsToCoupons(redeemed, options = {}) {
153
+ const ctx = buildContext(options);
154
+ return (redeemed || []).filter(reward => reward.couponCode).map(reward => buildCoupon(reward, ctx));
155
+ }
156
+ export function mapReceivedRewardsToCoupons(received, options = {}) {
157
+ const ctx = buildContext(options);
158
+ return (received || [])
159
+ .filter(reward => reward.couponCode)
160
+ .map(reward => ({
161
+ ...buildCoupon(reward, ctx),
162
+ source: 'received',
163
+ senderName: reward.senderName || '',
164
+ senderEmail: reward.senderEmail || '',
165
+ partiallyUsed: !!reward.partiallyUsed
166
+ }));
167
+ }
@@ -0,0 +1,22 @@
1
+ export interface CustomLinkSettings {
2
+ customLogin: boolean;
3
+ loginUrl: string;
4
+ signUpUrl: string;
5
+ openWidgetAfterLogin: boolean;
6
+ replaceAccountLink: boolean;
7
+ accountLinkSelector: string;
8
+ }
9
+ type RawSettings = Record<string, unknown> & {
10
+ version?: unknown;
11
+ links?: Record<string, unknown>;
12
+ };
13
+ export declare function getCustomLinkSettings(settings?: RawSettings | null): CustomLinkSettings;
14
+ export declare function appendJoyHash(url: string, hash?: string): string;
15
+ export declare function resolveAuthUrls(settings: RawSettings | null | undefined, defaults: {
16
+ loginUrl: string;
17
+ registerUrl: string;
18
+ }): {
19
+ loginUrl: string;
20
+ registerUrl: string;
21
+ };
22
+ export {};
@@ -0,0 +1,56 @@
1
+ const JOY_OPEN_HASH = 'joy-open';
2
+ const str = (value) => (typeof value === 'string' ? value : '');
3
+ export function getCustomLinkSettings(settings) {
4
+ const s = settings ?? {};
5
+ const links = s.links ?? {};
6
+ if (s.version) {
7
+ return {
8
+ customLogin: Boolean(links.customLogin),
9
+ loginUrl: str(links.loginUrl),
10
+ signUpUrl: str(links.signUpUrl),
11
+ openWidgetAfterLogin: Boolean(links.openWidgetAfterLogin),
12
+ replaceAccountLink: Boolean(links.replaceAccountLink),
13
+ accountLinkSelector: str(links.accountLinkSelector)
14
+ };
15
+ }
16
+ return {
17
+ customLogin: Boolean(s.isCustomLoginLink),
18
+ loginUrl: str(s.loginLinkRedirect),
19
+ signUpUrl: str(s.signUpLinkRedirect),
20
+ openWidgetAfterLogin: Boolean(links.openWidgetAfterLogin ?? s.openWidgetAfterLogin),
21
+ replaceAccountLink: false,
22
+ accountLinkSelector: ''
23
+ };
24
+ }
25
+ export function appendJoyHash(url, hash = JOY_OPEN_HASH) {
26
+ if (!url)
27
+ return url;
28
+ let parsed;
29
+ try {
30
+ parsed = new URL(url, 'https://_invalid_base.local');
31
+ }
32
+ catch {
33
+ return url;
34
+ }
35
+ const returnTo = parsed.searchParams.get('return_to');
36
+ if (returnTo) {
37
+ const [base, existingHash = ''] = returnTo.split('#');
38
+ const nextHash = existingHash && !existingHash.startsWith('joy-') ? existingHash : hash;
39
+ parsed.searchParams.set('return_to', `${base}#${nextHash}`);
40
+ }
41
+ else if (!parsed.hash || parsed.hash.startsWith('#joy-')) {
42
+ parsed.hash = `#${hash}`;
43
+ }
44
+ return url.startsWith('/') ? `${parsed.pathname}${parsed.search}${parsed.hash}` : parsed.toString();
45
+ }
46
+ export function resolveAuthUrls(settings, defaults) {
47
+ const links = getCustomLinkSettings(settings);
48
+ const withHash = (url) => (links.openWidgetAfterLogin ? appendJoyHash(url) : url);
49
+ if (!links.customLogin) {
50
+ return { loginUrl: withHash(defaults.loginUrl), registerUrl: defaults.registerUrl };
51
+ }
52
+ return {
53
+ loginUrl: withHash(links.loginUrl || '/account/login'),
54
+ registerUrl: links.signUpUrl || '/account/register'
55
+ };
56
+ }
@@ -0,0 +1,25 @@
1
+ import type { WidgetCoreExports } from './core-loader.js';
2
+ export interface DeeplinkEntry {
3
+ hash: string;
4
+ view: string | null;
5
+ activeTab: 'earn' | 'redeem' | null;
6
+ requiresLogin: boolean;
7
+ }
8
+ export interface DeeplinkCatalog {
9
+ getDeeplinkByHash(hash: string): DeeplinkEntry | null;
10
+ resolveDeeplinkHash(param: string | null): string | null;
11
+ }
12
+ export interface DeeplinkWidgetElement extends Pick<HTMLElement, 'hasAttribute'> {
13
+ open(): void;
14
+ loggedIn?: boolean;
15
+ _isOpen?: boolean;
16
+ navigateTo?(view: string): void;
17
+ focusProgramArea?(area: 'earn' | 'redeem'): void;
18
+ _activeTab?: string;
19
+ }
20
+ export declare function resolveDeeplinkCatalog(coreExports?: WidgetCoreExports): DeeplinkCatalog;
21
+ export declare function readDeeplinkHash(catalog: DeeplinkCatalog, location: Pick<Location, 'hash' | 'search'>): string;
22
+ export declare function isDeeplinkAreaDisabled(el: Pick<HTMLElement, 'hasAttribute'>, view: string): boolean;
23
+ export declare function navigateToDeeplink(el: DeeplinkWidgetElement, entry: DeeplinkEntry): void;
24
+ export declare function applyDeeplinkFromUrl(el: DeeplinkWidgetElement, catalog: DeeplinkCatalog): boolean;
25
+ export declare function installDeeplinkHandling(el: DeeplinkWidgetElement, catalog: DeeplinkCatalog): () => void;