@joy-loyalty/hydrogen 0.2.0 → 0.2.1
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/README.md +3 -3
- package/dist/csp.d.ts +1 -1
- package/dist/csp.js +2 -2
- package/dist/headless-host-adapter.js +3 -2
- package/dist/host-adapter/capabilities.d.ts +1 -0
- package/dist/host-adapter/capabilities.js +3 -0
- package/dist/host-adapter/product-fetcher.d.ts +1 -1
- package/dist/host-adapter/product-fetcher.js +3 -2
- package/dist/host-adapter/promoted-collections.d.ts +1 -1
- package/dist/host-adapter/promoted-collections.js +3 -2
- package/dist/hydrogen-cart-port.js +1 -1
- package/dist/joy-widget.js +2 -2
- package/dist/lib/recommended-loader.d.ts +2 -1
- package/dist/lib/recommended-loader.js +5 -3
- package/dist/orchestrator/handlers/account.js +1 -1
- package/dist/orchestrator/handlers/earn.js +9 -0
- package/dist/routes/joy-products.js +22 -10
- package/dist/server/get-joy-initial-data.d.ts +1 -0
- package/dist/server/get-joy-initial-data.js +5 -1
- package/dist/server/get-joy-loyalty-page-data.d.ts +1 -0
- package/dist/server/get-joy-loyalty-page-data.js +1 -1
- package/dist/widget-orchestrator.d.ts +1 -0
- package/dist/widget-orchestrator.js +6 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Joy Loyalty for Hydrogen / headless Shopify storefronts. Embeds the Joy Loyalty Widget V4 (`<JoyWidget/>`) and Loyalty Page V2 (`<JoyLoyaltyPage/>`) in any Hydrogen app, plus the server helpers and resource routes they need. No Weaverse dependency (for Weaverse use [`@joy-loyalty/weaverse-hydrogen`](../weaverse-hydrogen), which builds on this package).
|
|
4
4
|
|
|
5
|
-
The widget core is a shared, host-neutral Lit bundle loaded at runtime from `https://
|
|
5
|
+
The widget core is a shared, host-neutral Lit bundle loaded at runtime from `https://api.joy.so`. It talks to the Joy Headless API; this package supplies the host side (token exchange, SSR data, cart wiring).
|
|
6
6
|
|
|
7
7
|
> ESM-only. React 18 or 19 required. `@shopify/hydrogen` (>= 2025.5) is an optional peer, needed only when you wire the cart.
|
|
8
8
|
|
|
@@ -25,7 +25,7 @@ npm install @joy-loyalty/hydrogen
|
|
|
25
25
|
| `JOY_API_URL` | server (may be passed to the browser as a prop) | e.g. `https://api.joy.so/app/api/v1/headless`. Not a credential. |
|
|
26
26
|
| `JOY_SHOP_DOMAIN` | server | The shop's `*.myshopify.com` domain. |
|
|
27
27
|
| `JOY_API_SECRET` | **server only** | The headless API secret from your Joy admin. |
|
|
28
|
-
| `JOY_WIDGET_ASSET_URL` | optional | Overrides the widget-core origin (default `https://
|
|
28
|
+
| `JOY_WIDGET_ASSET_URL` | optional | Overrides the widget-core origin (default `https://api.joy.so`). Pass it as the `assetUrl` prop. |
|
|
29
29
|
|
|
30
30
|
> **Warning: server-only secret.** `JOY_API_SECRET` must only be read on the server (Oxygen worker / loaders / resource routes). Never prefix it `PUBLIC_` or `VITE_`, never put it in a loader return value, and never import code that reads it into a client bundle. Anyone holding the secret can mint customer tokens for your shop.
|
|
31
31
|
>
|
|
@@ -123,7 +123,7 @@ Pages whose HTML includes personalized Joy data must not be shared-cached. Use `
|
|
|
123
123
|
## Security notes
|
|
124
124
|
|
|
125
125
|
- The customer JWT is kept in `sessionStorage` (about 1 hour TTL) so the widget can call the Headless API from the browser. Any script running on your storefront origin (for example via XSS) can read it. Keep a strict CSP and avoid untrusted third-party scripts.
|
|
126
|
-
- The widget core is executed code loaded from `
|
|
126
|
+
- The widget core is executed code loaded from `api.joy.so` (or your `assetUrl`). Allow-list only the origins you trust.
|
|
127
127
|
- The token route responds with `Cache-Control: private, no-store`; do not override that.
|
|
128
128
|
|
|
129
129
|
## Other exports
|
package/dist/csp.d.ts
CHANGED
package/dist/csp.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export const JOY_CDN_ORIGIN = 'https://
|
|
1
|
+
export const JOY_CDN_ORIGIN = 'https://api.joy.so';
|
|
2
2
|
export const JOY_API_ORIGIN = 'https://api.joy.so';
|
|
3
3
|
export const JOY_CSP_DIRECTIVES = {
|
|
4
4
|
scriptSrc: [JOY_CDN_ORIGIN],
|
|
5
|
-
connectSrc: [JOY_CDN_ORIGIN, JOY_API_ORIGIN],
|
|
5
|
+
connectSrc: unique([JOY_CDN_ORIGIN, JOY_API_ORIGIN]),
|
|
6
6
|
styleSrc: [JOY_CDN_ORIGIN],
|
|
7
7
|
imgSrc: [JOY_CDN_ORIGIN],
|
|
8
8
|
fontSrc: [JOY_CDN_ORIGIN]
|
|
@@ -50,8 +50,9 @@ function parsePageQuery(query) {
|
|
|
50
50
|
export function createHeadlessHostAdapter(options) {
|
|
51
51
|
const { context: contextInput, initialData = null, source, getToken, productsRoute = DEFAULT_PRODUCTS_ROUTE } = options;
|
|
52
52
|
const context = { ...contextInput, translation: contextInput.translation ?? {} };
|
|
53
|
-
const
|
|
54
|
-
const
|
|
53
|
+
const getCountry = () => context.country || undefined;
|
|
54
|
+
const getProductByHandle = createProductByHandleFetcher(productsRoute, getCountry);
|
|
55
|
+
const getPromotedCollections = createPromotedCollectionsFetcher(productsRoute, getCountry);
|
|
55
56
|
let appleWalletPassCache = {
|
|
56
57
|
createdApplePass: !!initialData?.customer?.createdApplePass,
|
|
57
58
|
qrCodeDownloadApplePass: initialData?.customer?.qrCodeDownloadApplePass || ''
|
|
@@ -10,3 +10,6 @@ export const HEADLESS_CAPABILITIES = {
|
|
|
10
10
|
googleWalletPass: true
|
|
11
11
|
};
|
|
12
12
|
export const DEFAULT_PRODUCTS_ROUTE = '/api/joy-products';
|
|
13
|
+
export function withMarketCountry(query, country) {
|
|
14
|
+
return country ? `${query}&country=${encodeURIComponent(country)}` : query;
|
|
15
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { CurrentProduct } from './types.js';
|
|
2
|
-
export declare function createProductByHandleFetcher(productsRoute: string): (handle: string) => Promise<CurrentProduct | null>;
|
|
2
|
+
export declare function createProductByHandleFetcher(productsRoute: string, getCountry?: () => string | undefined): (handle: string) => Promise<CurrentProduct | null>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import { withMarketCountry } from './capabilities.js';
|
|
2
|
+
export function createProductByHandleFetcher(productsRoute, getCountry = () => undefined) {
|
|
2
3
|
let pending = [];
|
|
3
4
|
let scheduled = false;
|
|
4
5
|
async function flush() {
|
|
@@ -11,7 +12,7 @@ export function createProductByHandleFetcher(productsRoute) {
|
|
|
11
12
|
return;
|
|
12
13
|
}
|
|
13
14
|
try {
|
|
14
|
-
const url = `${productsRoute}?handles=${handles.map(encodeURIComponent).join(',')}
|
|
15
|
+
const url = withMarketCountry(`${productsRoute}?handles=${handles.map(encodeURIComponent).join(',')}`, getCountry());
|
|
15
16
|
const response = await fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
|
|
16
17
|
if (!response.ok)
|
|
17
18
|
throw new Error(`joy-products ${response.status}`);
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { PromotedCollection, PromotedCollectionSelection } from './types.js';
|
|
2
|
-
export declare function createPromotedCollectionsFetcher(productsRoute: string): (selections: PromotedCollectionSelection[]) => Promise<PromotedCollection[]>;
|
|
2
|
+
export declare function createPromotedCollectionsFetcher(productsRoute: string, getCountry?: () => string | undefined): (selections: PromotedCollectionSelection[]) => Promise<PromotedCollection[]>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import { withMarketCountry } from './capabilities.js';
|
|
2
|
+
export function createPromotedCollectionsFetcher(productsRoute, getCountry = () => undefined) {
|
|
2
3
|
return async function getPromotedCollections(selections) {
|
|
3
4
|
const handles = Array.from(new Set((selections ?? []).map(selection => selection?.handle).filter(Boolean)));
|
|
4
5
|
if (!handles.length)
|
|
@@ -18,7 +19,7 @@ export function createPromotedCollectionsFetcher(productsRoute) {
|
|
|
18
19
|
.map(handle => snapshotByHandle.get(handle))
|
|
19
20
|
.filter(Boolean);
|
|
20
21
|
try {
|
|
21
|
-
const url = `${productsRoute}?collections=${handles.map(encodeURIComponent).join(',')}
|
|
22
|
+
const url = withMarketCountry(`${productsRoute}?collections=${handles.map(encodeURIComponent).join(',')}`, getCountry());
|
|
22
23
|
const response = await fetch(url, {
|
|
23
24
|
headers: { Accept: 'application/json' },
|
|
24
25
|
credentials: 'same-origin'
|
|
@@ -97,7 +97,7 @@ export class HydrogenCartPort {
|
|
|
97
97
|
if (cart &&
|
|
98
98
|
discountCodes.length === existingCodes.length &&
|
|
99
99
|
discountCodes.every(existingCode => existingCodes.includes(existingCode))) {
|
|
100
|
-
return { ok: true, applied: true };
|
|
100
|
+
return { ok: true, applied: cart.discountCodes.find(discount => discount.code === code)?.applicable === true };
|
|
101
101
|
}
|
|
102
102
|
try {
|
|
103
103
|
const result = await this.submit(CartForm.ACTIONS.DiscountCodesUpdate, { discountCodes });
|
package/dist/joy-widget.js
CHANGED
|
@@ -61,7 +61,7 @@ export function JoyWidget({ apiUrl = null, tokenRoute, loginUrl = '/account', lo
|
|
|
61
61
|
const [open, setOpen] = useState(false);
|
|
62
62
|
const [coreLoaded, setCoreLoaded] = useState(false);
|
|
63
63
|
const [coreFailed, setCoreFailed] = useState(false);
|
|
64
|
-
const hostConfig = useJoyConfig({ apiUrl, loginUrl, locale, shopDomain });
|
|
64
|
+
const hostConfig = useJoyConfig({ apiUrl, loginUrl, locale: locale ?? initialData?.locale, shopDomain });
|
|
65
65
|
const config = {
|
|
66
66
|
...hostConfig,
|
|
67
67
|
locale: resolveShopLocale(hostConfig.locale, initialData?.blob?.translation)
|
|
@@ -162,7 +162,7 @@ export function JoyWidget({ apiUrl = null, tokenRoute, loginUrl = '/account', lo
|
|
|
162
162
|
registerUrl: authUrls.registerUrl,
|
|
163
163
|
loyaltyPageUrl,
|
|
164
164
|
accountUrl: '/account',
|
|
165
|
-
country: country ?? 'US',
|
|
165
|
+
country: country ?? initialData?.country ?? 'US',
|
|
166
166
|
viewport: { width: window.innerWidth }
|
|
167
167
|
},
|
|
168
168
|
source
|
|
@@ -39,5 +39,6 @@ export interface LoadRecommendedOptions {
|
|
|
39
39
|
productCard?: ProductCardHelpers;
|
|
40
40
|
currency?: string;
|
|
41
41
|
productsRoute?: string;
|
|
42
|
+
country?: string;
|
|
42
43
|
}
|
|
43
|
-
export declare function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute }: LoadRecommendedOptions): Promise<void>;
|
|
44
|
+
export declare function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute, country }: LoadRecommendedOptions): Promise<void>;
|
|
@@ -2,7 +2,7 @@ import { DEFAULT_PRODUCTS_ROUTE } from '../headless-host-adapter.js';
|
|
|
2
2
|
import { PRODUCT_PATH_PATTERN, RECENTLY_VIEWED_STORAGE_KEY as STORAGE_KEY } from '@joy-loyalty/sdk/widget-contracts';
|
|
3
3
|
const AUTO_SIGNALS = ['product_page', 'recently_viewed'];
|
|
4
4
|
const CARD_IMAGE_WIDTH = 400;
|
|
5
|
-
export async function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute = DEFAULT_PRODUCTS_ROUTE }) {
|
|
5
|
+
export async function loadRecommendedProducts({ widgetEl, sections, productCard, currency, productsRoute = DEFAULT_PRODUCTS_ROUTE, country }) {
|
|
6
6
|
try {
|
|
7
7
|
if (!productCard) {
|
|
8
8
|
console.warn('[joy] recommendations skipped: the loaded widget core has no `productCard` export ' +
|
|
@@ -10,7 +10,7 @@ export async function loadRecommendedProducts({ widgetEl, sections, productCard,
|
|
|
10
10
|
return;
|
|
11
11
|
}
|
|
12
12
|
const section = (sections.find(entry => entry?.id === 'PRODUCTS') ?? {});
|
|
13
|
-
const { products, currencyCode } = await fetchRecommended(productsRoute, section);
|
|
13
|
+
const { products, currencyCode } = await fetchRecommended(productsRoute, section, country);
|
|
14
14
|
if (!products.length)
|
|
15
15
|
return;
|
|
16
16
|
const subConfig = productCard.resolveSubscriptionConfig(sections, 'PRODUCTS');
|
|
@@ -31,13 +31,15 @@ export async function loadRecommendedProducts({ widgetEl, sections, productCard,
|
|
|
31
31
|
widgetEl.recentProductsLoading = false;
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
|
-
async function fetchRecommended(route, section) {
|
|
34
|
+
async function fetchRecommended(route, section, country) {
|
|
35
35
|
const empty = { products: [], currencyCode: null };
|
|
36
36
|
const params = new URLSearchParams({ recommend: resolveSeedHandle(section.personalizeFrom) });
|
|
37
37
|
if (section.fallbackCollectionHandle)
|
|
38
38
|
params.set('fallbackCollection', section.fallbackCollectionHandle);
|
|
39
39
|
if (section.fallbackSort)
|
|
40
40
|
params.set('fallbackSort', section.fallbackSort);
|
|
41
|
+
if (country)
|
|
42
|
+
params.set('country', country);
|
|
41
43
|
const response = await fetch(`${route}?${params}`, {
|
|
42
44
|
headers: { Accept: 'application/json' },
|
|
43
45
|
credentials: 'same-origin'
|
|
@@ -35,7 +35,7 @@ export function mapActivityRows(activities, ctx, countryCode) {
|
|
|
35
35
|
return activities.map(activity => toActivityViewModel(activity, locale));
|
|
36
36
|
}
|
|
37
37
|
const blob = (ctx.activeBlob ?? {});
|
|
38
|
-
const mapped = mapActivities(activities.map(activity => ({ ...activity, type: activity.rawType })), {
|
|
38
|
+
const mapped = mapActivities(activities.map(({ title: _composedTitle, ...activity }) => ({ ...activity, type: activity.rawType })), {
|
|
39
39
|
translation: resolveActiveTranslation(blob.translation, locale),
|
|
40
40
|
settings: blob.settings ?? {},
|
|
41
41
|
shop: blob.shop ?? {},
|
|
@@ -38,6 +38,12 @@ export function registerEarnHandlers(ctx) {
|
|
|
38
38
|
element
|
|
39
39
|
.setEarnActionResult?.(success, extra);
|
|
40
40
|
}
|
|
41
|
+
function settleSocialEarn(option, success, response) {
|
|
42
|
+
const widget = element;
|
|
43
|
+
widget.socialPending = { option, pending: false };
|
|
44
|
+
widget.handleEarnResult?.(option, success);
|
|
45
|
+
element.dispatchEvent(new CustomEvent('joy-earn-result', { bubbles: true, composed: true, detail: { option, success, response } }));
|
|
46
|
+
}
|
|
41
47
|
function resetEarnAction() {
|
|
42
48
|
element.resetEarnActionState?.();
|
|
43
49
|
}
|
|
@@ -117,10 +123,13 @@ export function registerEarnHandlers(ctx) {
|
|
|
117
123
|
if (typeof totalPoints === 'number')
|
|
118
124
|
writeProps(element, { points: totalPoints });
|
|
119
125
|
setEarnResult(true);
|
|
126
|
+
settleSocialEarn(d.option, true, result);
|
|
120
127
|
ctx.loadActivities();
|
|
121
128
|
}
|
|
122
129
|
catch (error) {
|
|
123
130
|
setEarnResult(false);
|
|
131
|
+
if (isSocial && !hasForm && !hasReceipt)
|
|
132
|
+
settleSocialEarn(d.option, false);
|
|
124
133
|
surface(Promise.reject(error));
|
|
125
134
|
}
|
|
126
135
|
}
|
|
@@ -116,24 +116,29 @@ const COLLECTION_SORT_KEYS = new Set([
|
|
|
116
116
|
const DEFAULT_SORT = { sortKey: 'BEST_SELLING', reverse: false };
|
|
117
117
|
export async function loader({ context, request }) {
|
|
118
118
|
const params = new URL(request.url).searchParams;
|
|
119
|
+
const market = marketVariables(params);
|
|
119
120
|
if (params.has('recommend')) {
|
|
120
|
-
return loadRecommendations(context.storefront, params);
|
|
121
|
+
return loadRecommendations(context.storefront, params, market);
|
|
121
122
|
}
|
|
122
123
|
const collectionsParam = params.get('collections');
|
|
123
124
|
if (collectionsParam !== null) {
|
|
124
|
-
return loadCollections(context.storefront, collectionsParam);
|
|
125
|
+
return loadCollections(context.storefront, collectionsParam, market);
|
|
125
126
|
}
|
|
126
127
|
const handlesParam = params.get('handles');
|
|
127
128
|
if (handlesParam !== null) {
|
|
128
|
-
return loadByHandles(context.storefront, handlesParam);
|
|
129
|
+
return loadByHandles(context.storefront, handlesParam, market);
|
|
129
130
|
}
|
|
130
131
|
return json({ products: [], currencyCode: null }, 400);
|
|
131
132
|
}
|
|
132
|
-
|
|
133
|
+
function marketVariables(params) {
|
|
134
|
+
const country = params.get('country');
|
|
135
|
+
return country && /^[A-Z]{2}$/.test(country) ? { country } : {};
|
|
136
|
+
}
|
|
137
|
+
async function loadByHandles(storefront, raw, market) {
|
|
133
138
|
const handles = parseHandles(raw);
|
|
134
139
|
if (!handles.length)
|
|
135
140
|
return json({ products: [], currencyCode: null, handles }, 200);
|
|
136
|
-
const variables = {};
|
|
141
|
+
const variables = { ...market };
|
|
137
142
|
handles.forEach((handle, index) => {
|
|
138
143
|
variables[`h${index}`] = handle;
|
|
139
144
|
});
|
|
@@ -150,7 +155,7 @@ async function loadByHandles(storefront, raw) {
|
|
|
150
155
|
}
|
|
151
156
|
return json({ products: nodes.map(toAjaxProduct), currencyCode: pickCurrencyCode(nodes), handles }, 200);
|
|
152
157
|
}
|
|
153
|
-
async function loadRecommendations(storefront, params) {
|
|
158
|
+
async function loadRecommendations(storefront, params, market) {
|
|
154
159
|
const seed = sanitizeHandle(params.get('recommend'));
|
|
155
160
|
const collectionHandle = sanitizeHandle(params.get('fallbackCollection'));
|
|
156
161
|
const { sortKey, reverse } = resolveSort(params.get('fallbackSort'));
|
|
@@ -158,6 +163,7 @@ async function loadRecommendations(storefront, params) {
|
|
|
158
163
|
try {
|
|
159
164
|
const data = (await storefront.query(RECOMMENDATIONS_QUERY, {
|
|
160
165
|
variables: {
|
|
166
|
+
...market,
|
|
161
167
|
handle: seed,
|
|
162
168
|
useRecommended: !!seed,
|
|
163
169
|
collectionHandle,
|
|
@@ -180,11 +186,11 @@ async function loadRecommendations(storefront, params) {
|
|
|
180
186
|
.filter((product) => !!product && product.handle !== seed);
|
|
181
187
|
return json({ products, currencyCode: pickCurrencyCode(nodes) }, 200);
|
|
182
188
|
}
|
|
183
|
-
async function loadCollections(storefront, raw) {
|
|
189
|
+
async function loadCollections(storefront, raw, market) {
|
|
184
190
|
const handles = parseHandles(raw, MAX_COLLECTIONS);
|
|
185
191
|
if (!handles.length)
|
|
186
192
|
return json({ collections: [] }, 200);
|
|
187
|
-
const variables = {};
|
|
193
|
+
const variables = { ...market };
|
|
188
194
|
handles.forEach((handle, index) => {
|
|
189
195
|
variables[`h${index}`] = handle;
|
|
190
196
|
});
|
|
@@ -274,7 +280,7 @@ function toAjaxProduct(node) {
|
|
|
274
280
|
handle: node.handle,
|
|
275
281
|
title: node.title ?? '',
|
|
276
282
|
url: `/products/${node.handle}`,
|
|
277
|
-
price:
|
|
283
|
+
price: toPriceCents(node.priceRange?.minVariantPrice),
|
|
278
284
|
compare_at_price: toCents(node.compareAtPriceRange?.maxVariantPrice),
|
|
279
285
|
featured_image: featuredImage,
|
|
280
286
|
images,
|
|
@@ -290,11 +296,17 @@ function toAjaxVariant(variant) {
|
|
|
290
296
|
.map(perDeliveryPrice => ({ perDeliveryPrice })));
|
|
291
297
|
return {
|
|
292
298
|
id: numericId(variant.id),
|
|
293
|
-
price:
|
|
299
|
+
price: toPriceCents(variant.price),
|
|
294
300
|
compare_at_price: toCents(variant.compareAtPrice),
|
|
295
301
|
sellingPlanAllocations: allocations
|
|
296
302
|
};
|
|
297
303
|
}
|
|
304
|
+
function toPriceCents(money) {
|
|
305
|
+
const amount = Number(money?.amount);
|
|
306
|
+
if (money?.amount == null || !Number.isFinite(amount) || amount < 0)
|
|
307
|
+
return null;
|
|
308
|
+
return Math.round(amount * 100);
|
|
309
|
+
}
|
|
298
310
|
function toCents(money) {
|
|
299
311
|
const amount = Number(money?.amount);
|
|
300
312
|
if (!Number.isFinite(amount) || amount <= 0)
|
|
@@ -2,12 +2,15 @@ import { createJoyClient } from '@joy-loyalty/sdk/client';
|
|
|
2
2
|
import { getJoyMetafieldBlob } from '../lib/metafield-blob.js';
|
|
3
3
|
import { mintJoyToken } from '../lib/server-token.js';
|
|
4
4
|
import { resolveShopLocale } from '../lib/shop-locale.js';
|
|
5
|
+
import { toShopifyLocale } from './get-joy-loyalty-page-data.js';
|
|
5
6
|
import { getWidgetCoreManifest } from '../lib/core-manifest.js';
|
|
6
7
|
const DEFAULT_LOGIN_URL = '/account/login';
|
|
7
8
|
const DEFAULT_REGISTER_URL = '/account/register';
|
|
8
9
|
const DEFAULT_ACCOUNT_URL = '/account';
|
|
9
10
|
export async function getJoyInitialData(options) {
|
|
10
|
-
const { storefront, customerAccount, apiUrl, shopDomain, secret,
|
|
11
|
+
const { storefront, customerAccount, apiUrl, shopDomain, secret, loginUrl = DEFAULT_LOGIN_URL, registerUrl = DEFAULT_REGISTER_URL, accountUrl = DEFAULT_ACCOUNT_URL, request, exposeToken = false, assetUrl, deferCustomerBalance = false } = options;
|
|
12
|
+
const i18n = storefront.i18n;
|
|
13
|
+
const locale = options.locale ?? (i18n?.language ? toShopifyLocale(i18n.language) : undefined);
|
|
11
14
|
const [blob, customerHalf, core] = await Promise.all([
|
|
12
15
|
getJoyMetafieldBlob(storefront),
|
|
13
16
|
fetchCustomerHalf({ customerAccount, apiUrl, shopDomain, secret, locale, deferCustomerBalance }),
|
|
@@ -20,6 +23,7 @@ export async function getJoyInitialData(options) {
|
|
|
20
23
|
...(customerHalf.shopifyCustomer !== undefined ? { shopifyCustomer: customerHalf.shopifyCustomer } : {}),
|
|
21
24
|
...(exposeToken && customerHalf.token !== undefined ? { token: customerHalf.token } : {}),
|
|
22
25
|
...(locale !== undefined ? { locale: resolveShopLocale(locale, blob?.translation) } : {}),
|
|
26
|
+
...(i18n?.country ? { country: i18n.country } : {}),
|
|
23
27
|
login_url: loginUrl,
|
|
24
28
|
register_url: registerUrl,
|
|
25
29
|
account_url: accountUrl,
|
|
@@ -25,3 +25,4 @@ export interface GetJoyLoyaltyPageDataOptions {
|
|
|
25
25
|
}
|
|
26
26
|
export declare function getJoyLoyaltyPageData(options: GetJoyLoyaltyPageDataOptions): Promise<JoyLoyaltyPageData>;
|
|
27
27
|
export declare function projectTranslations(translations: Record<string, unknown>, locale: string): Record<string, unknown>;
|
|
28
|
+
export declare function toShopifyLocale(language: string): string;
|
|
@@ -93,7 +93,7 @@ function blobWithoutHostFields(blob) {
|
|
|
93
93
|
const { translation: _translation, shop: _shop, ...rest } = blob;
|
|
94
94
|
return rest;
|
|
95
95
|
}
|
|
96
|
-
function toShopifyLocale(language) {
|
|
96
|
+
export function toShopifyLocale(language) {
|
|
97
97
|
const [lang, region] = language.split('_');
|
|
98
98
|
return region ? `${lang.toLowerCase()}-${region.toUpperCase()}` : lang.toLowerCase();
|
|
99
99
|
}
|
|
@@ -109,6 +109,10 @@ export function writeProps(element, props) {
|
|
|
109
109
|
if (value === undefined || value === null)
|
|
110
110
|
continue;
|
|
111
111
|
const property = key.replace(/-([a-z])/g, (_, character) => character.toUpperCase());
|
|
112
|
+
if (/[A-Z]/.test(key)) {
|
|
113
|
+
element[property] = value;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
112
116
|
if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
|
|
113
117
|
element[property] = value;
|
|
114
118
|
}
|
|
@@ -414,7 +418,8 @@ export function createWidgetOrchestrator(container, hostAdapter, initialData, ap
|
|
|
414
418
|
widgetEl: element,
|
|
415
419
|
sections: Array.isArray(settings?.sections) ? settings.sections : [],
|
|
416
420
|
productCard: coreExports?.productCard,
|
|
417
|
-
currency: renderContext?.currency
|
|
421
|
+
currency: renderContext?.currency,
|
|
422
|
+
country: hostAdapter.context().country || undefined
|
|
418
423
|
});
|
|
419
424
|
}
|
|
420
425
|
return {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@joy-loyalty/hydrogen",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Joy Loyalty Widget V4 for any Hydrogen / headless Shopify storefront — host-neutral core embedded through HeadlessHostAdapter. No Weaverse dependency.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "module",
|
|
@@ -95,7 +95,7 @@
|
|
|
95
95
|
}
|
|
96
96
|
},
|
|
97
97
|
"dependencies": {
|
|
98
|
-
"@joy-loyalty/sdk": "^0.2.
|
|
98
|
+
"@joy-loyalty/sdk": "^0.2.1",
|
|
99
99
|
"dompurify": "^3.1.7"
|
|
100
100
|
},
|
|
101
101
|
"devDependencies": {
|