@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.
- package/LICENSE +3 -0
- package/README.md +134 -2
- package/dist/cache-control.d.ts +8 -0
- package/dist/cache-control.js +6 -0
- package/dist/csp.d.ts +14 -0
- package/dist/csp.js +33 -0
- package/dist/headless-host-adapter.d.ts +5 -0
- package/dist/headless-host-adapter.js +197 -0
- package/dist/host-adapter/capabilities.d.ts +3 -0
- package/dist/host-adapter/capabilities.js +12 -0
- package/dist/host-adapter/data-source.d.ts +3 -0
- package/dist/host-adapter/data-source.js +49 -0
- package/dist/host-adapter/product-fetcher.d.ts +2 -0
- package/dist/host-adapter/product-fetcher.js +37 -0
- package/dist/host-adapter/promoted-collections.d.ts +2 -0
- package/dist/host-adapter/promoted-collections.js +43 -0
- package/dist/host-adapter/types.d.ts +212 -0
- package/dist/host-adapter/types.js +1 -0
- package/dist/hydrogen-cart-port.d.ts +134 -0
- package/dist/hydrogen-cart-port.js +245 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +15 -0
- package/dist/joy-widget.d.ts +29 -0
- package/dist/joy-widget.js +291 -0
- package/dist/lib/JoyProvider.d.ts +47 -0
- package/dist/lib/JoyProvider.js +95 -0
- package/dist/lib/account-links.d.ts +5 -0
- package/dist/lib/account-links.js +65 -0
- package/dist/lib/apply-behavior.d.ts +12 -0
- package/dist/lib/apply-behavior.js +26 -0
- package/dist/lib/core-loader.d.ts +63 -0
- package/dist/lib/core-loader.js +160 -0
- package/dist/lib/core-manifest.d.ts +7 -0
- package/dist/lib/core-manifest.js +54 -0
- package/dist/lib/core-preload-links.d.ts +8 -0
- package/dist/lib/core-preload-links.js +8 -0
- package/dist/lib/coupon-mapper.d.ts +95 -0
- package/dist/lib/coupon-mapper.js +167 -0
- package/dist/lib/custom-links.d.ts +22 -0
- package/dist/lib/custom-links.js +56 -0
- package/dist/lib/deeplink.d.ts +25 -0
- package/dist/lib/deeplink.js +92 -0
- package/dist/lib/earn-signup-gate.d.ts +3 -0
- package/dist/lib/earn-signup-gate.js +31 -0
- package/dist/lib/facebook-ref-link.d.ts +13 -0
- package/dist/lib/facebook-ref-link.js +31 -0
- package/dist/lib/headless-referral-origin.d.ts +2 -0
- package/dist/lib/headless-referral-origin.js +24 -0
- package/dist/lib/headless-source.d.ts +8 -0
- package/dist/lib/headless-source.js +71 -0
- package/dist/lib/image.d.ts +2 -0
- package/dist/lib/image.js +14 -0
- package/dist/lib/metafield-blob.d.ts +33 -0
- package/dist/lib/metafield-blob.js +76 -0
- package/dist/lib/money.d.ts +6 -0
- package/dist/lib/money.js +25 -0
- package/dist/lib/order-mapper.d.ts +44 -0
- package/dist/lib/order-mapper.js +141 -0
- package/dist/lib/place-order-scope.d.ts +6 -0
- package/dist/lib/place-order-scope.js +22 -0
- package/dist/lib/points.d.ts +5 -0
- package/dist/lib/points.js +10 -0
- package/dist/lib/recently-viewed-tracker.d.ts +1 -0
- package/dist/lib/recently-viewed-tracker.js +34 -0
- package/dist/lib/recommended-loader.d.ts +43 -0
- package/dist/lib/recommended-loader.js +111 -0
- package/dist/lib/referral-share.d.ts +4 -0
- package/dist/lib/referral-share.js +33 -0
- package/dist/lib/safe-navigation-url.d.ts +1 -0
- package/dist/lib/safe-navigation-url.js +9 -0
- package/dist/lib/server-token.d.ts +41 -0
- package/dist/lib/server-token.js +87 -0
- package/dist/lib/shop-locale.d.ts +1 -0
- package/dist/lib/shop-locale.js +21 -0
- package/dist/lib/social-earn.d.ts +11 -0
- package/dist/lib/social-earn.js +25 -0
- package/dist/lib/storefront-fonts.d.ts +5 -0
- package/dist/lib/storefront-fonts.js +52 -0
- package/dist/lib/token.d.ts +14 -0
- package/dist/lib/token.js +135 -0
- package/dist/lib/write-review.d.ts +2 -0
- package/dist/lib/write-review.js +44 -0
- package/dist/loyalty-page/JoyLoyaltyPage.d.ts +151 -0
- package/dist/loyalty-page/JoyLoyaltyPage.js +447 -0
- package/dist/loyalty-page/compose-home.d.ts +35 -0
- package/dist/loyalty-page/compose-home.js +177 -0
- package/dist/loyalty-page/skeleton.d.ts +11 -0
- package/dist/loyalty-page/skeleton.js +99 -0
- package/dist/orchestrator/context.d.ts +61 -0
- package/dist/orchestrator/context.js +64 -0
- package/dist/orchestrator/gated.d.ts +1 -0
- package/dist/orchestrator/gated.js +14 -0
- package/dist/orchestrator/handlers/account.d.ts +19 -0
- package/dist/orchestrator/handlers/account.js +266 -0
- package/dist/orchestrator/handlers/birthday.d.ts +6 -0
- package/dist/orchestrator/handlers/birthday.js +128 -0
- package/dist/orchestrator/handlers/earn.d.ts +5 -0
- package/dist/orchestrator/handlers/earn.js +258 -0
- package/dist/orchestrator/handlers/milestone-tier.d.ts +5 -0
- package/dist/orchestrator/handlers/milestone-tier.js +123 -0
- package/dist/orchestrator/handlers/profile.d.ts +5 -0
- package/dist/orchestrator/handlers/profile.js +262 -0
- package/dist/orchestrator/handlers/redeem.d.ts +6 -0
- package/dist/orchestrator/handlers/redeem.js +464 -0
- package/dist/orchestrator/handlers/referral.d.ts +5 -0
- package/dist/orchestrator/handlers/referral.js +218 -0
- package/dist/orchestrator/render.d.ts +2 -0
- package/dist/orchestrator/render.js +193 -0
- package/dist/render-adapter.d.ts +50 -0
- package/dist/render-adapter.js +422 -0
- package/dist/routes/joy-place-order-scope.d.ts +12 -0
- package/dist/routes/joy-place-order-scope.js +32 -0
- package/dist/routes/joy-products.d.ts +48 -0
- package/dist/routes/joy-products.js +326 -0
- package/dist/routes/joy-token.d.ts +16 -0
- package/dist/routes/joy-token.js +32 -0
- package/dist/server/get-joy-initial-data.d.ts +38 -0
- package/dist/server/get-joy-initial-data.js +61 -0
- package/dist/server/get-joy-loyalty-page-data.d.ts +27 -0
- package/dist/server/get-joy-loyalty-page-data.js +99 -0
- package/dist/server/index.d.ts +8 -0
- package/dist/server/index.js +4 -0
- package/dist/widget-controller.d.ts +2 -0
- package/dist/widget-controller.js +1 -0
- package/dist/widget-orchestrator.d.ts +88 -0
- package/dist/widget-orchestrator.js +499 -0
- package/package.json +121 -4
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
const OPEN_ENTRY = { hash: '#joy-open', view: null, activeTab: null, requiresLogin: false };
|
|
2
|
+
const FALLBACK_CATALOG = {
|
|
3
|
+
getDeeplinkByHash: hash => {
|
|
4
|
+
const idx = hash ? hash.indexOf(OPEN_ENTRY.hash) : -1;
|
|
5
|
+
if (idx === -1)
|
|
6
|
+
return null;
|
|
7
|
+
const next = hash[idx + OPEN_ENTRY.hash.length];
|
|
8
|
+
return next === undefined || next === '?' || next === '&' || next === '#' ? OPEN_ENTRY : null;
|
|
9
|
+
},
|
|
10
|
+
resolveDeeplinkHash: param => (param === 'true' || param === '1' || param === 'joy-open' ? OPEN_ENTRY.hash : null)
|
|
11
|
+
};
|
|
12
|
+
export function resolveDeeplinkCatalog(coreExports) {
|
|
13
|
+
const byHash = coreExports?.getDeeplinkByHash;
|
|
14
|
+
const byParam = coreExports?.resolveDeeplinkHash;
|
|
15
|
+
if (typeof byHash !== 'function' || typeof byParam !== 'function')
|
|
16
|
+
return FALLBACK_CATALOG;
|
|
17
|
+
return {
|
|
18
|
+
getDeeplinkByHash: byHash,
|
|
19
|
+
resolveDeeplinkHash: byParam
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export function readDeeplinkHash(catalog, location) {
|
|
23
|
+
if (location.hash)
|
|
24
|
+
return location.hash;
|
|
25
|
+
return catalog.resolveDeeplinkHash(new URLSearchParams(location.search).get('open_joy')) ?? '';
|
|
26
|
+
}
|
|
27
|
+
export function isDeeplinkAreaDisabled(el, view) {
|
|
28
|
+
const has = (attr) => el.hasAttribute(attr);
|
|
29
|
+
switch (view) {
|
|
30
|
+
case 'perks':
|
|
31
|
+
return has('hide-tier-perks');
|
|
32
|
+
case 'referral':
|
|
33
|
+
return !has('show-referral');
|
|
34
|
+
case 'profile':
|
|
35
|
+
return has('hide-profile');
|
|
36
|
+
case 'store-credit-detail':
|
|
37
|
+
return !has('show-store-credit');
|
|
38
|
+
case 'activities':
|
|
39
|
+
return has('hide-activities');
|
|
40
|
+
case 'coupons':
|
|
41
|
+
return has('hide-coupons');
|
|
42
|
+
case 'milestone':
|
|
43
|
+
return has('hide-milestone');
|
|
44
|
+
default:
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export function navigateToDeeplink(el, entry) {
|
|
49
|
+
if (entry.requiresLogin && !el.loggedIn)
|
|
50
|
+
return;
|
|
51
|
+
if (entry.view && isDeeplinkAreaDisabled(el, entry.view))
|
|
52
|
+
return;
|
|
53
|
+
if (entry.view && entry.view !== 'main' && typeof el.navigateTo === 'function')
|
|
54
|
+
el.navigateTo(entry.view);
|
|
55
|
+
if (!entry.activeTab)
|
|
56
|
+
return;
|
|
57
|
+
if (typeof el.focusProgramArea === 'function')
|
|
58
|
+
el.focusProgramArea(entry.activeTab);
|
|
59
|
+
else
|
|
60
|
+
el._activeTab = entry.activeTab;
|
|
61
|
+
}
|
|
62
|
+
export function applyDeeplinkFromUrl(el, catalog) {
|
|
63
|
+
const hash = readDeeplinkHash(catalog, window.location);
|
|
64
|
+
const entry = catalog.getDeeplinkByHash(hash);
|
|
65
|
+
if (!window.location.hash && hash) {
|
|
66
|
+
const url = new URL(window.location.href);
|
|
67
|
+
url.searchParams.delete('open_joy');
|
|
68
|
+
history.replaceState(history.state, '', url.toString());
|
|
69
|
+
}
|
|
70
|
+
if (!entry)
|
|
71
|
+
return false;
|
|
72
|
+
if (!el._isOpen)
|
|
73
|
+
el.open();
|
|
74
|
+
requestAnimationFrame(() => navigateToDeeplink(el, entry));
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
export function installDeeplinkHandling(el, catalog) {
|
|
78
|
+
const trigger = () => applyDeeplinkFromUrl(el, catalog);
|
|
79
|
+
const onClick = (event) => {
|
|
80
|
+
const anchor = event.target?.closest?.('a[href*="#joy-"]');
|
|
81
|
+
if (!anchor || !catalog.getDeeplinkByHash(anchor.hash || ''))
|
|
82
|
+
return;
|
|
83
|
+
requestAnimationFrame(trigger);
|
|
84
|
+
};
|
|
85
|
+
trigger();
|
|
86
|
+
window.addEventListener('hashchange', trigger);
|
|
87
|
+
document.addEventListener('click', onClick);
|
|
88
|
+
return () => {
|
|
89
|
+
window.removeEventListener('hashchange', trigger);
|
|
90
|
+
document.removeEventListener('click', onClick);
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const STORAGE_KEY = 'joy:earn-signup-sent';
|
|
2
|
+
function store() {
|
|
3
|
+
try {
|
|
4
|
+
return typeof sessionStorage === 'undefined' ? null : sessionStorage;
|
|
5
|
+
}
|
|
6
|
+
catch {
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export function shouldSendEarnSignup(customerKey) {
|
|
11
|
+
try {
|
|
12
|
+
return store()?.getItem(STORAGE_KEY) !== customerKey;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function markEarnSignupSent(customerKey) {
|
|
19
|
+
try {
|
|
20
|
+
store()?.setItem(STORAGE_KEY, customerKey);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export function clearEarnSignupSent() {
|
|
26
|
+
try {
|
|
27
|
+
store()?.removeItem(STORAGE_KEY);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface FacebookRefLinkParams {
|
|
2
|
+
pageId: string;
|
|
3
|
+
shopId: string;
|
|
4
|
+
customerId: string;
|
|
5
|
+
shopifyCustomerId?: string;
|
|
6
|
+
shopDomain?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface FacebookRefLink {
|
|
9
|
+
link: string;
|
|
10
|
+
webLink: string;
|
|
11
|
+
mobileLink: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function generateFacebookRefLink({ pageId, shopId, customerId, shopifyCustomerId, shopDomain }: FacebookRefLinkParams): Promise<FacebookRefLink>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
async function hmacSha256Short(key, data) {
|
|
2
|
+
const encoder = new TextEncoder();
|
|
3
|
+
const cryptoKey = await crypto.subtle.importKey('raw', encoder.encode(key), { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);
|
|
4
|
+
const signature = await crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(data));
|
|
5
|
+
return Array.from(new Uint8Array(signature))
|
|
6
|
+
.map(byte => byte.toString(16).padStart(2, '0'))
|
|
7
|
+
.join('')
|
|
8
|
+
.substring(0, 8);
|
|
9
|
+
}
|
|
10
|
+
async function encodeRefData({ shopId, customerId, shopifyCustomerId = '', shopDomain = '' }) {
|
|
11
|
+
const json = JSON.stringify({
|
|
12
|
+
sid: shopId,
|
|
13
|
+
cid: customerId,
|
|
14
|
+
scid: shopifyCustomerId,
|
|
15
|
+
d: shopDomain,
|
|
16
|
+
t: Date.now()
|
|
17
|
+
});
|
|
18
|
+
const encoded = btoa(json).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
19
|
+
return `${encoded}.${await hmacSha256Short(shopId, encoded)}`;
|
|
20
|
+
}
|
|
21
|
+
function isMobileDevice() {
|
|
22
|
+
if (typeof navigator === 'undefined')
|
|
23
|
+
return false;
|
|
24
|
+
return /android|iphone|ipad|ipod|iemobile|blackberry|opera mini|mobile/i.test(navigator.userAgent || '');
|
|
25
|
+
}
|
|
26
|
+
export async function generateFacebookRefLink({ pageId, shopId, customerId, shopifyCustomerId = '', shopDomain = '' }) {
|
|
27
|
+
const ref = await encodeRefData({ shopId, customerId, shopifyCustomerId, shopDomain });
|
|
28
|
+
const webLink = `https://www.facebook.com/messages/t/${pageId}?ref=${ref}`;
|
|
29
|
+
const mobileLink = `https://m.me/${pageId}?ref=${ref}`;
|
|
30
|
+
return { link: isMobileDevice() ? mobileLink : webLink, webLink, mobileLink };
|
|
31
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export function withHeadlessReferralOrigin(shop, origin) {
|
|
2
|
+
if (!isRecord(shop) || !origin || shop.redirectionUrlReferral)
|
|
3
|
+
return shop;
|
|
4
|
+
return { ...shop, redirectionUrlReferral: origin };
|
|
5
|
+
}
|
|
6
|
+
export function toHeadlessReferralLink(link, shop, origin) {
|
|
7
|
+
if (!link || !origin || !isRecord(shop) || shop.redirectionUrlReferral)
|
|
8
|
+
return link;
|
|
9
|
+
let url;
|
|
10
|
+
try {
|
|
11
|
+
url = new URL(link);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return link;
|
|
15
|
+
}
|
|
16
|
+
const shopHosts = [shop.domain, shop.shopifyDomain].filter(h => typeof h === 'string' && h);
|
|
17
|
+
if (!shopHosts.includes(url.host) || !DEFAULT_LANDING_PATH.test(url.pathname))
|
|
18
|
+
return link;
|
|
19
|
+
return `${origin.replace(/\/+$/, '')}${url.pathname === '/' ? '' : url.pathname}${url.search}${url.hash}`;
|
|
20
|
+
}
|
|
21
|
+
const DEFAULT_LANDING_PATH = /^\/?(?:[a-z]{2}(?:-[a-z]{2})?\/?)?$/i;
|
|
22
|
+
function isRecord(value) {
|
|
23
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
24
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { JoyDataSource } from '../headless-host-adapter.js';
|
|
2
|
+
export interface CreateHeadlessSourceOptions {
|
|
3
|
+
apiUrl: string | null | undefined;
|
|
4
|
+
tokenRoute?: string;
|
|
5
|
+
locale?: string;
|
|
6
|
+
shopDomain?: string;
|
|
7
|
+
}
|
|
8
|
+
export declare function createHeadlessSource(options: CreateHeadlessSourceOptions): JoyDataSource | undefined;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createJoyDataSource } from '../headless-host-adapter.js';
|
|
2
|
+
import { ensureClient } from './JoyProvider.js';
|
|
3
|
+
import { DEFAULT_TOKEN_ROUTE, GUEST_INFO_SKIP, getJoyToken } from './token.js';
|
|
4
|
+
export function createHeadlessSource(options) {
|
|
5
|
+
const { apiUrl, tokenRoute = DEFAULT_TOKEN_ROUTE, locale, shopDomain } = options;
|
|
6
|
+
if (!apiUrl)
|
|
7
|
+
return undefined;
|
|
8
|
+
const client = ensureClient(apiUrl, tokenRoute, locale, shopDomain);
|
|
9
|
+
const base = createJoyDataSource(client);
|
|
10
|
+
const ready = getJoyToken({ tokenRoute }).then(token => {
|
|
11
|
+
if (token)
|
|
12
|
+
client.setToken(token);
|
|
13
|
+
});
|
|
14
|
+
const withToken = (run) => ready.then(run);
|
|
15
|
+
return {
|
|
16
|
+
getCustomer: () => withToken(() => base.getCustomer()),
|
|
17
|
+
getPrograms: () => withToken(() => base.getPrograms()),
|
|
18
|
+
getActivities: query => withToken(() => base.getActivities(query)),
|
|
19
|
+
getRewards: params => withToken(() => base.getRewards(params)),
|
|
20
|
+
getReceivedRewards: params => withToken(() => base.getReceivedRewards(params)),
|
|
21
|
+
getAddresses: () => withToken(() => base.getAddresses()),
|
|
22
|
+
saveAddress: address => withToken(() => base.saveAddress(address)),
|
|
23
|
+
deleteAddress: addressId => withToken(() => base.deleteAddress(addressId)),
|
|
24
|
+
updateProfile: options => withToken(() => base.updateProfile(options)),
|
|
25
|
+
saveBirthday: (birthday, dateOfBirth) => withToken(() => base.saveBirthday(birthday, dateOfBirth)),
|
|
26
|
+
getReferral: () => withToken(() => base.getReferral()),
|
|
27
|
+
sendReferralEmail: refereeEmail => withToken(() => base.sendReferralEmail(refereeEmail)),
|
|
28
|
+
generateReferralLink: email => base.generateReferralLink(email),
|
|
29
|
+
getTierRewards: () => withToken(() => base.getTierRewards()),
|
|
30
|
+
getPendingTierRewardClaims: () => withToken(() => base.getPendingTierRewardClaims()),
|
|
31
|
+
getMilestoneProgress: () => withToken(() => base.getMilestoneProgress()),
|
|
32
|
+
claimMilestone: input => withToken(() => base.claimMilestone(input)),
|
|
33
|
+
saveTierPerkVariantSelection: input => withToken(() => base.saveTierPerkVariantSelection(input)),
|
|
34
|
+
claimPendingReward: (pendingId, input) => withToken(() => base.claimPendingReward(pendingId, input)),
|
|
35
|
+
getImpactHistory: params => withToken(() => base.getImpactHistory(params)),
|
|
36
|
+
getReferralHistory: params => withToken(() => base.getReferralHistory(params)),
|
|
37
|
+
getOrders: () => withToken(() => base.getOrders()),
|
|
38
|
+
getOrderById: orderId => withToken(() => base.getOrderById(orderId)),
|
|
39
|
+
getOrderActivities: orderId => withToken(() => base.getOrderActivities(orderId)),
|
|
40
|
+
getStoreCreditTransactions: params => withToken(() => base.getStoreCreditTransactions(params)),
|
|
41
|
+
sendRewardToFriend: input => withToken(() => base.sendRewardToFriend(input)),
|
|
42
|
+
setBirthdayRewards: birthdayRewards => withToken(() => base.setBirthdayRewards(birthdayRewards)),
|
|
43
|
+
claimBirthdayReward: birthdayRewards => withToken(() => base.claimBirthdayReward(birthdayRewards)),
|
|
44
|
+
generateQrCode: () => withToken(() => base.generateQrCode()),
|
|
45
|
+
joinProgram: joinFrom => withToken(() => base.joinProgram(joinFrom)),
|
|
46
|
+
checkSegmentPrograms: segmentPrograms => withToken(() => base.checkSegmentPrograms(segmentPrograms)),
|
|
47
|
+
linkInstagram: instagramUsername => withToken(() => base.linkInstagram(instagramUsername)),
|
|
48
|
+
disconnectFacebook: () => withToken(() => base.disconnectFacebook()),
|
|
49
|
+
getLineAuthUrl: () => withToken(() => base.getLineAuthUrl()),
|
|
50
|
+
getAppleWalletLink: () => withToken(() => base.getAppleWalletLink()),
|
|
51
|
+
getGoogleWalletLink: () => withToken(() => base.getGoogleWalletLink()),
|
|
52
|
+
verifyApplePass: () => withToken(() => base.verifyApplePass()),
|
|
53
|
+
getFreeGiftStock: (programId, country) => withToken(() => base.getFreeGiftStock(programId, country)),
|
|
54
|
+
getInfo: params => getJoyToken({ tokenRoute }).then(token => {
|
|
55
|
+
const { allowGuest, ...rest } = params ?? {};
|
|
56
|
+
const forwarded = params && 'allowGuest' in params ? rest : params;
|
|
57
|
+
if (!token) {
|
|
58
|
+
if (!allowGuest)
|
|
59
|
+
throw new Error(GUEST_INFO_SKIP);
|
|
60
|
+
client.setToken(null);
|
|
61
|
+
return base.getInfo(forwarded);
|
|
62
|
+
}
|
|
63
|
+
client.setToken(token);
|
|
64
|
+
return base.getInfo(forwarded);
|
|
65
|
+
}),
|
|
66
|
+
redeem: (programId, opts) => withToken(() => base.redeem(programId, opts)),
|
|
67
|
+
earn: (programId, context) => withToken(() => base.earn(programId, context)),
|
|
68
|
+
earnUpload: input => withToken(() => base.earnUpload(input)),
|
|
69
|
+
earnSocial: programId => withToken(() => base.earnSocial(programId))
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export const ICON_IMAGE_SIZE = 260;
|
|
2
|
+
export function sizeShopifyImage(url, size) {
|
|
3
|
+
if (!url.includes('cdn.shopify.com'))
|
|
4
|
+
return url;
|
|
5
|
+
try {
|
|
6
|
+
const parsed = new URL(url);
|
|
7
|
+
parsed.searchParams.set('width', String(size));
|
|
8
|
+
parsed.searchParams.set('height', String(size));
|
|
9
|
+
return parsed.toString();
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return url;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface JoyStorefrontClient {
|
|
2
|
+
query(query: string, options?: unknown): Promise<unknown>;
|
|
3
|
+
CacheCustom?: (strategy: {
|
|
4
|
+
mode?: string;
|
|
5
|
+
maxAge?: number;
|
|
6
|
+
staleWhileRevalidate?: number;
|
|
7
|
+
}) => unknown;
|
|
8
|
+
i18n?: {
|
|
9
|
+
country?: string;
|
|
10
|
+
language?: string;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export type JoyMetafieldBlob = Record<string, unknown>;
|
|
14
|
+
export type JoyCustomerLoyaltyEligibility = 'customer_eligible_all' | 'exclude_b2b_customers' | 'manually_assigned_only';
|
|
15
|
+
export type JoyCustomerFreeGiftBehavior = 'manual_add_to_cart' | 'auto_add_to_cart' | 'auto_add_to_cart_drawer_hide_modal';
|
|
16
|
+
export interface JoyBlobShopConfig {
|
|
17
|
+
currency: string;
|
|
18
|
+
currencyFormat: string;
|
|
19
|
+
pointLabel: {
|
|
20
|
+
singular: string;
|
|
21
|
+
plural: string;
|
|
22
|
+
};
|
|
23
|
+
optInEnrollmentEnabled: boolean;
|
|
24
|
+
customerLoyaltyEligibility: JoyCustomerLoyaltyEligibility;
|
|
25
|
+
isNewFormatDOB: boolean;
|
|
26
|
+
customerFreeGiftBehavior: JoyCustomerFreeGiftBehavior;
|
|
27
|
+
shopId: string | null;
|
|
28
|
+
facebookPageId: string | null;
|
|
29
|
+
}
|
|
30
|
+
export declare function fetchMetafieldBlob(storefront: JoyStorefrontClient): Promise<JoyMetafieldBlob | undefined>;
|
|
31
|
+
export declare function shopConfigFromBlob(blob: JoyMetafieldBlob | undefined): JoyBlobShopConfig | undefined;
|
|
32
|
+
export declare function getJoyMetafieldBlob(storefront: JoyStorefrontClient): Promise<JoyMetafieldBlob | undefined>;
|
|
33
|
+
export declare function getJoyShopConfig(storefront: JoyStorefrontClient): Promise<JoyBlobShopConfig | undefined>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
const ELIGIBILITY_VALUES = [
|
|
2
|
+
'customer_eligible_all',
|
|
3
|
+
'exclude_b2b_customers',
|
|
4
|
+
'manually_assigned_only'
|
|
5
|
+
];
|
|
6
|
+
const FREE_GIFT_BEHAVIOR_VALUES = [
|
|
7
|
+
'manual_add_to_cart',
|
|
8
|
+
'auto_add_to_cart',
|
|
9
|
+
'auto_add_to_cart_drawer_hide_modal'
|
|
10
|
+
];
|
|
11
|
+
const METAFIELD_QUERY = `#graphql
|
|
12
|
+
query JoyMetafield {
|
|
13
|
+
shop {
|
|
14
|
+
metafield(namespace: "joy_loyalty_avada", key: "data") {
|
|
15
|
+
value
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
`;
|
|
20
|
+
export async function fetchMetafieldBlob(storefront) {
|
|
21
|
+
try {
|
|
22
|
+
const cache = storefront.CacheCustom?.({ mode: 'public', maxAge: 60, staleWhileRevalidate: 600 });
|
|
23
|
+
const data = (await storefront.query(METAFIELD_QUERY, cache ? { cache } : undefined));
|
|
24
|
+
const raw = data?.shop?.metafield?.value;
|
|
25
|
+
if (!raw)
|
|
26
|
+
return undefined;
|
|
27
|
+
const parsed = JSON.parse(raw);
|
|
28
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
29
|
+
? parsed
|
|
30
|
+
: undefined;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function shopConfigFromBlob(blob) {
|
|
37
|
+
if (!blob)
|
|
38
|
+
return undefined;
|
|
39
|
+
const shop = (blob.shop ?? {});
|
|
40
|
+
const settings = (blob.settings ?? {});
|
|
41
|
+
return {
|
|
42
|
+
currency: shop.currency || 'USD',
|
|
43
|
+
currencyFormat: shop.moneyFormat || '${{amount}}',
|
|
44
|
+
pointLabel: {
|
|
45
|
+
singular: settings.pointSingular || 'point',
|
|
46
|
+
plural: settings.pointPlural || 'points'
|
|
47
|
+
},
|
|
48
|
+
optInEnrollmentEnabled: shop.optInEnrollmentEnabled === true,
|
|
49
|
+
customerLoyaltyEligibility: ELIGIBILITY_VALUES.includes(shop.customerLoyaltyEligibility)
|
|
50
|
+
? shop.customerLoyaltyEligibility
|
|
51
|
+
: 'customer_eligible_all',
|
|
52
|
+
isNewFormatDOB: shop.isNewFormatDOB === true,
|
|
53
|
+
customerFreeGiftBehavior: FREE_GIFT_BEHAVIOR_VALUES.includes(settings.customerFreeGiftBehavior)
|
|
54
|
+
? settings.customerFreeGiftBehavior
|
|
55
|
+
: 'manual_add_to_cart',
|
|
56
|
+
shopId: typeof blob.shopId === 'string' ? blob.shopId : null,
|
|
57
|
+
facebookPageId: typeof blob.facebookPageId === 'string' && blob.facebookPageId
|
|
58
|
+
? blob.facebookPageId
|
|
59
|
+
: null
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const blobByStorefront = new WeakMap();
|
|
63
|
+
function sharedBlob(storefront) {
|
|
64
|
+
const cached = blobByStorefront.get(storefront);
|
|
65
|
+
if (cached)
|
|
66
|
+
return cached;
|
|
67
|
+
const pending = fetchMetafieldBlob(storefront);
|
|
68
|
+
blobByStorefront.set(storefront, pending);
|
|
69
|
+
return pending;
|
|
70
|
+
}
|
|
71
|
+
export function getJoyMetafieldBlob(storefront) {
|
|
72
|
+
return sharedBlob(storefront).then((blob) => (blob ? structuredClone(blob) : undefined));
|
|
73
|
+
}
|
|
74
|
+
export function getJoyShopConfig(storefront) {
|
|
75
|
+
return sharedBlob(storefront).then(shopConfigFromBlob);
|
|
76
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export function formatMoney(value, money) {
|
|
2
|
+
const plain = (money.currencyFormat || '').replace(/<[^>]*>/g, '').trim();
|
|
3
|
+
const token = plain.match(/\{\{\s*(\w+)\s*\}\}/);
|
|
4
|
+
if (!token)
|
|
5
|
+
return `${value} ${money.currency}`;
|
|
6
|
+
const amount = Number.isInteger(value) ? String(value) : value.toFixed(2);
|
|
7
|
+
return plain.replace(/\{\{\s*\w+\s*\}\}/, amount);
|
|
8
|
+
}
|
|
9
|
+
export function formatOrderMoney(value, money, locale) {
|
|
10
|
+
let amount;
|
|
11
|
+
try {
|
|
12
|
+
amount = new Intl.NumberFormat(locale || undefined, {
|
|
13
|
+
minimumFractionDigits: 2,
|
|
14
|
+
maximumFractionDigits: 2
|
|
15
|
+
}).format(value);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
amount = new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value);
|
|
19
|
+
}
|
|
20
|
+
const plain = (money.currencyFormat || '').replace(/<[^>]*>/g, '').trim();
|
|
21
|
+
const token = plain.match(/\{\{\s*(\w+)\s*\}\}/);
|
|
22
|
+
if (!token)
|
|
23
|
+
return `${amount} ${money.currency}`;
|
|
24
|
+
return plain.replace(/\{\{\s*\w+\s*\}\}/, amount);
|
|
25
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Order, OrderAddress } from '@joy-loyalty/sdk/client';
|
|
2
|
+
import { type JoyMoney } from './money.js';
|
|
3
|
+
export interface OrderLineItemView {
|
|
4
|
+
title: string;
|
|
5
|
+
quantity: number;
|
|
6
|
+
price: string;
|
|
7
|
+
image: string;
|
|
8
|
+
variantTitle: string;
|
|
9
|
+
productId: number | null;
|
|
10
|
+
productHandle: string;
|
|
11
|
+
}
|
|
12
|
+
export interface OrderItem {
|
|
13
|
+
id: string;
|
|
14
|
+
name: string;
|
|
15
|
+
date: string;
|
|
16
|
+
status: string;
|
|
17
|
+
statusKey: string;
|
|
18
|
+
statusSteps: string[];
|
|
19
|
+
currentStep: number;
|
|
20
|
+
total: string;
|
|
21
|
+
subtotal: string;
|
|
22
|
+
shipping: string;
|
|
23
|
+
tax: string;
|
|
24
|
+
discount: string;
|
|
25
|
+
discountCode: string;
|
|
26
|
+
totalSavings: string;
|
|
27
|
+
lineItems: OrderLineItemView[];
|
|
28
|
+
shippingAddress: OrderAddress | null;
|
|
29
|
+
billingAddress: OrderAddress | null;
|
|
30
|
+
contactEmail: string;
|
|
31
|
+
shippingMethod: string;
|
|
32
|
+
paymentMethod: string;
|
|
33
|
+
buyAgainUrl: string;
|
|
34
|
+
viewOrderUrl: string;
|
|
35
|
+
}
|
|
36
|
+
type TLabel = (english: string) => string;
|
|
37
|
+
export interface OrderMapperDeps {
|
|
38
|
+
tLabel: TLabel;
|
|
39
|
+
money: JoyMoney;
|
|
40
|
+
shopDomain?: string;
|
|
41
|
+
locale?: string;
|
|
42
|
+
}
|
|
43
|
+
export declare function mapOrder(order: Order, deps: OrderMapperDeps): OrderItem;
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { formatOrderMoney } from './money.js';
|
|
2
|
+
function formatOrderDate(createdAt, locale) {
|
|
3
|
+
if (!createdAt)
|
|
4
|
+
return '';
|
|
5
|
+
const date = new Date(createdAt);
|
|
6
|
+
if (Number.isNaN(date.getTime()))
|
|
7
|
+
return '';
|
|
8
|
+
try {
|
|
9
|
+
return new Intl.DateTimeFormat(locale || undefined, { year: 'numeric', month: 'short', day: 'numeric' }).format(date);
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'short', day: 'numeric' }).format(date);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function normalizeStatus(value) {
|
|
16
|
+
return `${value || ''}`.trim().toLowerCase().replace(/\s+/g, '_');
|
|
17
|
+
}
|
|
18
|
+
const STATUS_LABELS = {
|
|
19
|
+
paid: 'Paid',
|
|
20
|
+
partially_paid: 'Partially paid',
|
|
21
|
+
pending: 'Pending',
|
|
22
|
+
authorized: 'Authorized',
|
|
23
|
+
refunded: 'Refunded',
|
|
24
|
+
partially_refunded: 'Partially refunded',
|
|
25
|
+
voided: 'Voided',
|
|
26
|
+
fulfilled: 'Fulfilled',
|
|
27
|
+
partial: 'Partially fulfilled',
|
|
28
|
+
partially_fulfilled: 'Partially fulfilled',
|
|
29
|
+
unfulfilled: 'Unfulfilled',
|
|
30
|
+
in_transit: 'In transit',
|
|
31
|
+
out_for_delivery: 'Out for delivery',
|
|
32
|
+
shipped: 'Shipped',
|
|
33
|
+
processing: 'Processing',
|
|
34
|
+
payment_pending: 'Payment pending',
|
|
35
|
+
order_placed: 'Order placed'
|
|
36
|
+
};
|
|
37
|
+
function statusLabel(status, t) {
|
|
38
|
+
const value = normalizeStatus(status);
|
|
39
|
+
const english = STATUS_LABELS[value] || value.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()) || 'Unknown';
|
|
40
|
+
return t(english);
|
|
41
|
+
}
|
|
42
|
+
function resolveStatusData(order, t) {
|
|
43
|
+
const fulfillmentStatus = normalizeStatus(order.fulfillmentStatus || '');
|
|
44
|
+
const financialStatus = normalizeStatus(order.financialStatus || '');
|
|
45
|
+
const refunded = financialStatus === 'refunded' || financialStatus === 'partially_refunded';
|
|
46
|
+
if (refunded) {
|
|
47
|
+
return { key: 'cancelled', status: t('Refunded'), steps: [t('Placed'), t('Refunded')], currentStep: 2 };
|
|
48
|
+
}
|
|
49
|
+
if (fulfillmentStatus === 'fulfilled') {
|
|
50
|
+
return { key: 'delivered', status: t('Delivered'), steps: [t('Placed'), t('Paid'), t('Fulfilled')], currentStep: 3 };
|
|
51
|
+
}
|
|
52
|
+
if (fulfillmentStatus === 'partial' || fulfillmentStatus === 'partially_fulfilled') {
|
|
53
|
+
return {
|
|
54
|
+
key: 'partial',
|
|
55
|
+
status: t('Partially fulfilled'),
|
|
56
|
+
steps: [t('Placed'), statusLabel(financialStatus || 'paid', t), t('Partially fulfilled')],
|
|
57
|
+
currentStep: 2
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
if (financialStatus === 'paid' ||
|
|
61
|
+
financialStatus === 'partially_paid' ||
|
|
62
|
+
financialStatus === 'authorized' ||
|
|
63
|
+
financialStatus === 'pending') {
|
|
64
|
+
return {
|
|
65
|
+
key: 'partial',
|
|
66
|
+
status: statusLabel(financialStatus === 'pending' ? 'payment_pending' : 'processing', t),
|
|
67
|
+
steps: [t('Placed'), statusLabel(financialStatus, t), statusLabel(fulfillmentStatus || 'unfulfilled', t)],
|
|
68
|
+
currentStep: 2
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
key: 'partial',
|
|
73
|
+
status: statusLabel(financialStatus || fulfillmentStatus || 'order_placed', t),
|
|
74
|
+
steps: [t('Placed'), statusLabel(financialStatus || 'pending', t), statusLabel(fulfillmentStatus || 'unfulfilled', t)],
|
|
75
|
+
currentStep: 0
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const GENERIC_GATEWAY_LABELS = {
|
|
79
|
+
manual: 'Manual payment',
|
|
80
|
+
gift_card: 'Gift card',
|
|
81
|
+
shopify_store_credit: 'Store credit',
|
|
82
|
+
bogus: 'Test payment'
|
|
83
|
+
};
|
|
84
|
+
function formatGatewayName(name, t) {
|
|
85
|
+
const generic = GENERIC_GATEWAY_LABELS[String(name).toLowerCase()];
|
|
86
|
+
if (generic)
|
|
87
|
+
return t(generic);
|
|
88
|
+
const spaced = String(name).replace(/[-_]/g, ' ');
|
|
89
|
+
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
|
|
90
|
+
}
|
|
91
|
+
export function mapOrder(order, deps) {
|
|
92
|
+
const { tLabel, money: shopMoney, shopDomain, locale } = deps;
|
|
93
|
+
const statusData = resolveStatusData(order, tLabel);
|
|
94
|
+
const currency = order.currencyCode || shopMoney.currency;
|
|
95
|
+
const money = { currency, currencyFormat: shopMoney.currencyFormat };
|
|
96
|
+
const fmt = (cents) => formatOrderMoney((cents || 0) / 100, money, locale);
|
|
97
|
+
const totalDiscountsCents = Number(order.totalDiscounts || 0);
|
|
98
|
+
const shippingCents = typeof order.totalShipping === 'number'
|
|
99
|
+
? order.totalShipping
|
|
100
|
+
: Number(order.totalPrice || 0) - Number(order.subtotalPrice || 0) - Number(order.totalTax || 0);
|
|
101
|
+
const discountCode = order.discounts?.[0]?.code || '';
|
|
102
|
+
const buyAgainPairs = (order.lineItems || [])
|
|
103
|
+
.filter(item => item.variantId)
|
|
104
|
+
.map(item => `${item.variantId}:${item.quantity || 1}`);
|
|
105
|
+
const buyAgainUrl = shopDomain && buyAgainPairs.length ? `https://${shopDomain}/cart/${buyAgainPairs.join(',')}` : '';
|
|
106
|
+
const viewOrderUrl = order.orderStatusUrl || (order.id ? `/account/orders/${order.id}` : '');
|
|
107
|
+
return {
|
|
108
|
+
id: String(order.id),
|
|
109
|
+
name: order.name || '',
|
|
110
|
+
date: formatOrderDate(order.createdAt, locale),
|
|
111
|
+
status: statusData.status,
|
|
112
|
+
statusKey: statusData.key,
|
|
113
|
+
statusSteps: statusData.steps,
|
|
114
|
+
currentStep: statusData.currentStep,
|
|
115
|
+
total: fmt(order.totalPrice),
|
|
116
|
+
subtotal: fmt(order.subtotalPrice),
|
|
117
|
+
shipping: shippingCents > 0 ? fmt(shippingCents) : tLabel('Free'),
|
|
118
|
+
tax: fmt(order.totalTax || 0),
|
|
119
|
+
discount: totalDiscountsCents > 0 ? `-${fmt(totalDiscountsCents)}` : '',
|
|
120
|
+
discountCode,
|
|
121
|
+
totalSavings: totalDiscountsCents > 0 ? fmt(totalDiscountsCents) : '',
|
|
122
|
+
lineItems: (order.lineItems || []).map(item => ({
|
|
123
|
+
title: item.title || '',
|
|
124
|
+
quantity: item.quantity || 1,
|
|
125
|
+
price: fmt(item.price),
|
|
126
|
+
image: item.image || '',
|
|
127
|
+
variantTitle: item.variantTitle === 'Default Title' ? '' : item.variantTitle || '',
|
|
128
|
+
productId: item.productId ?? null,
|
|
129
|
+
productHandle: item.productHandle || ''
|
|
130
|
+
})),
|
|
131
|
+
shippingAddress: order.shippingAddress || null,
|
|
132
|
+
billingAddress: order.billingAddress || null,
|
|
133
|
+
contactEmail: order.customer?.email || '',
|
|
134
|
+
shippingMethod: order.shippingMethod || '',
|
|
135
|
+
paymentMethod: Array.isArray(order.paymentGatewayNames)
|
|
136
|
+
? order.paymentGatewayNames.filter(Boolean).map(name => formatGatewayName(name, tLabel)).join(', ')
|
|
137
|
+
: '',
|
|
138
|
+
buyAgainUrl,
|
|
139
|
+
viewOrderUrl
|
|
140
|
+
};
|
|
141
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { PlaceOrderScope } from '@joy-loyalty/sdk/client';
|
|
2
|
+
export declare const DEFAULT_PLACE_ORDER_SCOPE_ROUTE = "/api/joy-place-order-scope";
|
|
3
|
+
export interface GetPlaceOrderScopeOptions {
|
|
4
|
+
route?: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function getPlaceOrderScope(programId: string, options?: GetPlaceOrderScopeOptions): Promise<PlaceOrderScope | null>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const DEFAULT_PLACE_ORDER_SCOPE_ROUTE = '/api/joy-place-order-scope';
|
|
2
|
+
export async function getPlaceOrderScope(programId, options = {}) {
|
|
3
|
+
const route = options.route ?? DEFAULT_PLACE_ORDER_SCOPE_ROUTE;
|
|
4
|
+
let response;
|
|
5
|
+
try {
|
|
6
|
+
response = await fetch(`${route}?programId=${encodeURIComponent(programId)}`, {
|
|
7
|
+
headers: { Accept: 'application/json' },
|
|
8
|
+
credentials: 'same-origin'
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
if (!response.ok)
|
|
15
|
+
return null;
|
|
16
|
+
try {
|
|
17
|
+
return (await response.json());
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|