@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
package/LICENSE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,135 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @joy-loyalty/hydrogen
|
|
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
|
+
|
|
5
|
+
The widget core is a shared, host-neutral Lit bundle loaded at runtime from `https://static.joy.so`. It talks to the Joy Headless API; this package supplies the host side (token exchange, SSR data, cart wiring).
|
|
6
|
+
|
|
7
|
+
> ESM-only. React 18 or 19 required. `@shopify/hydrogen` (>= 2025.5) is an optional peer, needed only when you wire the cart.
|
|
8
|
+
|
|
9
|
+
## Prerequisites
|
|
10
|
+
|
|
11
|
+
- A Joy Loyalty store on the **Ultimate** plan (the Headless API is plan-gated).
|
|
12
|
+
- A Hydrogen storefront with Customer Account API login (the token route reads the logged-in customer).
|
|
13
|
+
- The headless API secret from your Joy admin.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install @joy-loyalty/hydrogen
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Environment variables
|
|
22
|
+
|
|
23
|
+
| Variable | Where | Notes |
|
|
24
|
+
|---|---|---|
|
|
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
|
+
| `JOY_SHOP_DOMAIN` | server | The shop's `*.myshopify.com` domain. |
|
|
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://static.joy.so`). Pass it as the `assetUrl` prop. |
|
|
29
|
+
|
|
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
|
+
>
|
|
32
|
+
> Note: the secret will be rotated to a dedicated headless secret before general availability. Plan for the value to change; the variable name stays `JOY_API_SECRET`.
|
|
33
|
+
|
|
34
|
+
## Setup
|
|
35
|
+
|
|
36
|
+
**1. Token route** — mints a short-lived customer JWT; returns 401 for guests.
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
// app/routes/api.joy-token.ts
|
|
40
|
+
export {loader} from '@joy-loyalty/hydrogen/routes/joy-token';
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**2. Root loader** — server-side initial data (never throws).
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
// app/root.tsx
|
|
47
|
+
import {getJoyInitialData} from '@joy-loyalty/hydrogen/server';
|
|
48
|
+
|
|
49
|
+
export async function loader({context, request}: LoaderFunctionArgs) {
|
|
50
|
+
const {env, storefront, customerAccount} = context;
|
|
51
|
+
const joy = await getJoyInitialData({
|
|
52
|
+
storefront,
|
|
53
|
+
customerAccount,
|
|
54
|
+
apiUrl: env.JOY_API_URL ?? '',
|
|
55
|
+
shopDomain: env.JOY_SHOP_DOMAIN ?? '',
|
|
56
|
+
secret: env.JOY_API_SECRET ?? '',
|
|
57
|
+
locale: storefront.i18n.language.toLowerCase(),
|
|
58
|
+
request
|
|
59
|
+
});
|
|
60
|
+
return {joy, joyApiUrl: env.JOY_API_URL ?? null, joyShopDomain: env.JOY_SHOP_DOMAIN ?? null};
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**3. Widget** — once, in `root.tsx`.
|
|
65
|
+
|
|
66
|
+
```tsx
|
|
67
|
+
import {JoyWidget} from '@joy-loyalty/hydrogen';
|
|
68
|
+
|
|
69
|
+
<JoyWidget
|
|
70
|
+
apiUrl={data.joyApiUrl}
|
|
71
|
+
shopDomain={data.joyShopDomain ?? undefined}
|
|
72
|
+
initialData={data.joy}
|
|
73
|
+
/>
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`JoyWidget` also accepts `tokenRoute`, `loginUrl`, `loyaltyPageUrl`, `locale`, `pathname`, `assetUrl` and cart props; see `JoyWidgetProps`.
|
|
77
|
+
|
|
78
|
+
**4. CSP** — see below.
|
|
79
|
+
|
|
80
|
+
### Loyalty page
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
// route loader
|
|
84
|
+
import {getJoyLoyaltyPageData} from '@joy-loyalty/hydrogen/server';
|
|
85
|
+
const data = await getJoyLoyaltyPageData({storefront, apiUrl, shopDomain});
|
|
86
|
+
```
|
|
87
|
+
```tsx
|
|
88
|
+
import {JoyLoyaltyPage} from '@joy-loyalty/hydrogen';
|
|
89
|
+
<JoyLoyaltyPage apiUrl={apiUrl} shopDomain={shopDomain} data={data} />
|
|
90
|
+
```
|
|
91
|
+
The server-rendered data carries no customer information by design; customer data loads client-side with the JWT. Set `sectionId` to render a single section.
|
|
92
|
+
|
|
93
|
+
## Optional resource routes
|
|
94
|
+
|
|
95
|
+
Each is a one-line re-export; the widget degrades gracefully without them.
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
// app/routes/api.joy-place-order-scope.ts (place_order programs restricted to products/collections)
|
|
99
|
+
export {loader} from '@joy-loyalty/hydrogen/routes/joy-place-order-scope';
|
|
100
|
+
|
|
101
|
+
// app/routes/api.joy-products.ts ("Recently viewed" / "Recommended for you" sections)
|
|
102
|
+
export {loader} from '@joy-loyalty/hydrogen/routes/joy-products';
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Content Security Policy
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import {JOY_CSP_DIRECTIVES} from '@joy-loyalty/hydrogen/csp';
|
|
109
|
+
|
|
110
|
+
createContentSecurityPolicy({
|
|
111
|
+
scriptSrc: ['self', ...JOY_CSP_DIRECTIVES.scriptSrc],
|
|
112
|
+
connectSrc: ['self', ...JOY_CSP_DIRECTIVES.connectSrc],
|
|
113
|
+
styleSrc: ['self', ...JOY_CSP_DIRECTIVES.styleSrc],
|
|
114
|
+
imgSrc: ['self', ...JOY_CSP_DIRECTIVES.imgSrc]
|
|
115
|
+
});
|
|
116
|
+
```
|
|
117
|
+
`JOY_CSP_DIRECTIVES` also has `fontSrc`. If you override `JOY_WIDGET_ASSET_URL` or use a non-default API host, derive the directives with `joyCspDirectives({apiUrl, assetUrl})`.
|
|
118
|
+
|
|
119
|
+
## Caching
|
|
120
|
+
|
|
121
|
+
Pages whose HTML includes personalized Joy data must not be shared-cached. Use `isJoyInitialDataPersonalized(joy)` and `JOY_PERSONALIZED_CACHE_CONTROL` (exported from the root and from `/server`) when setting `Cache-Control` in `entry.server.tsx`.
|
|
122
|
+
|
|
123
|
+
## Security notes
|
|
124
|
+
|
|
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 `static.joy.so` (or your `assetUrl`). Allow-list only the origins you trust.
|
|
127
|
+
- The token route responds with `Cache-Control: private, no-store`; do not override that.
|
|
128
|
+
|
|
129
|
+
## Other exports
|
|
130
|
+
|
|
131
|
+
Subpaths: `/csp`, `/provider`, `/token`, `/points`, `/money`, `/image`, `/social-earn`, `/facebook-ref-link`, `/metafield-blob`, `/place-order-scope`, `/server`, `/routes/*`. The root also exports `JoyProvider`, `useJoyConfig`, `useJoyCustomer`, `getJoyToken`, `clearJoyToken`, `createHeadlessHostAdapter`, `loadWidgetCore` and related types.
|
|
132
|
+
|
|
133
|
+
## License
|
|
134
|
+
|
|
135
|
+
Proprietary. Copyright (c) 2026 Avada Group. All rights reserved. Licensed only for use with the Joy Loyalty service under the Joy Loyalty Terms of Service. See `LICENSE`.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
interface PersonalizedJoyData {
|
|
2
|
+
customer?: unknown;
|
|
3
|
+
shopifyCustomer?: unknown;
|
|
4
|
+
token?: unknown;
|
|
5
|
+
}
|
|
6
|
+
export declare const JOY_PERSONALIZED_CACHE_CONTROL = "private, no-store";
|
|
7
|
+
export declare function isJoyInitialDataPersonalized(joy: PersonalizedJoyData | undefined | null): boolean;
|
|
8
|
+
export {};
|
package/dist/csp.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare const JOY_CDN_ORIGIN = "https://static.joy.so";
|
|
2
|
+
export declare const JOY_API_ORIGIN = "https://api.joy.so";
|
|
3
|
+
export interface JoyCspDirectives {
|
|
4
|
+
scriptSrc: string[];
|
|
5
|
+
connectSrc: string[];
|
|
6
|
+
styleSrc: string[];
|
|
7
|
+
imgSrc: string[];
|
|
8
|
+
fontSrc: string[];
|
|
9
|
+
}
|
|
10
|
+
export declare const JOY_CSP_DIRECTIVES: JoyCspDirectives;
|
|
11
|
+
export declare function joyCspDirectives(opts?: {
|
|
12
|
+
apiUrl?: string;
|
|
13
|
+
assetUrl?: string;
|
|
14
|
+
}): JoyCspDirectives;
|
package/dist/csp.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export const JOY_CDN_ORIGIN = 'https://static.joy.so';
|
|
2
|
+
export const JOY_API_ORIGIN = 'https://api.joy.so';
|
|
3
|
+
export const JOY_CSP_DIRECTIVES = {
|
|
4
|
+
scriptSrc: [JOY_CDN_ORIGIN],
|
|
5
|
+
connectSrc: [JOY_CDN_ORIGIN, JOY_API_ORIGIN],
|
|
6
|
+
styleSrc: [JOY_CDN_ORIGIN],
|
|
7
|
+
imgSrc: [JOY_CDN_ORIGIN],
|
|
8
|
+
fontSrc: [JOY_CDN_ORIGIN]
|
|
9
|
+
};
|
|
10
|
+
export function joyCspDirectives(opts = {}) {
|
|
11
|
+
const cdn = originOf(opts.assetUrl) ?? JOY_CDN_ORIGIN;
|
|
12
|
+
const api = originOf(opts.apiUrl) ?? JOY_API_ORIGIN;
|
|
13
|
+
return {
|
|
14
|
+
scriptSrc: [cdn],
|
|
15
|
+
connectSrc: unique([cdn, api]),
|
|
16
|
+
styleSrc: [cdn],
|
|
17
|
+
imgSrc: [cdn],
|
|
18
|
+
fontSrc: [cdn]
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function originOf(url) {
|
|
22
|
+
if (!url)
|
|
23
|
+
return null;
|
|
24
|
+
try {
|
|
25
|
+
return new URL(url).origin;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function unique(values) {
|
|
32
|
+
return [...new Set(values)];
|
|
33
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { HeadlessHostAdapter, HeadlessHostAdapterOptions } from './host-adapter/types.js';
|
|
2
|
+
export * from './host-adapter/types.js';
|
|
3
|
+
export { DEFAULT_PRODUCTS_ROUTE } from './host-adapter/capabilities.js';
|
|
4
|
+
export { createJoyDataSource } from './host-adapter/data-source.js';
|
|
5
|
+
export declare function createHeadlessHostAdapter(options: HeadlessHostAdapterOptions): HeadlessHostAdapter;
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { RECENTLY_VIEWED_STORAGE_KEY } from '@joy-loyalty/sdk/widget-contracts';
|
|
2
|
+
import { hasCachedJoyToken } from './lib/token.js';
|
|
3
|
+
import { safeNavigationUrl } from './lib/safe-navigation-url.js';
|
|
4
|
+
import { DEFAULT_PRODUCTS_ROUTE, HEADLESS_CAPABILITIES } from './host-adapter/capabilities.js';
|
|
5
|
+
import { createProductByHandleFetcher } from './host-adapter/product-fetcher.js';
|
|
6
|
+
import { createPromotedCollectionsFetcher } from './host-adapter/promoted-collections.js';
|
|
7
|
+
export * from './host-adapter/types.js';
|
|
8
|
+
export { DEFAULT_PRODUCTS_ROUTE } from './host-adapter/capabilities.js';
|
|
9
|
+
export { createJoyDataSource } from './host-adapter/data-source.js';
|
|
10
|
+
function getLocalStorage() {
|
|
11
|
+
try {
|
|
12
|
+
return typeof localStorage === 'undefined' ? null : localStorage;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
async function readRecentlyViewedProducts() {
|
|
19
|
+
const store = getLocalStorage();
|
|
20
|
+
if (!store)
|
|
21
|
+
return [];
|
|
22
|
+
try {
|
|
23
|
+
const parsed = JSON.parse(store.getItem(RECENTLY_VIEWED_STORAGE_KEY) || '[]');
|
|
24
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function writeRecentlyViewedProducts(items) {
|
|
31
|
+
const store = getLocalStorage();
|
|
32
|
+
if (!store)
|
|
33
|
+
return;
|
|
34
|
+
try {
|
|
35
|
+
store.setItem(RECENTLY_VIEWED_STORAGE_KEY, JSON.stringify(items));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function parsePageQuery(query) {
|
|
41
|
+
const params = new URLSearchParams(query);
|
|
42
|
+
const limit = params.get('limit');
|
|
43
|
+
const parsedLimit = limit === null ? undefined : Number.parseInt(limit, 10);
|
|
44
|
+
return {
|
|
45
|
+
before: params.get('before') || undefined,
|
|
46
|
+
after: params.get('after') || undefined,
|
|
47
|
+
...(Number.isFinite(parsedLimit) ? { limit: parsedLimit } : {})
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export function createHeadlessHostAdapter(options) {
|
|
51
|
+
const { context: contextInput, initialData = null, source, getToken, productsRoute = DEFAULT_PRODUCTS_ROUTE } = options;
|
|
52
|
+
const context = { ...contextInput, translation: contextInput.translation ?? {} };
|
|
53
|
+
const getProductByHandle = createProductByHandleFetcher(productsRoute);
|
|
54
|
+
const getPromotedCollections = createPromotedCollectionsFetcher(productsRoute);
|
|
55
|
+
let appleWalletPassCache = {
|
|
56
|
+
createdApplePass: !!initialData?.customer?.createdApplePass,
|
|
57
|
+
qrCodeDownloadApplePass: initialData?.customer?.qrCodeDownloadApplePass || ''
|
|
58
|
+
};
|
|
59
|
+
const authListeners = new Set();
|
|
60
|
+
function getAuthState() {
|
|
61
|
+
if (initialData?.customer)
|
|
62
|
+
return { status: 'authenticated' };
|
|
63
|
+
if (hasCachedJoyToken())
|
|
64
|
+
return { status: 'authenticated' };
|
|
65
|
+
return { status: 'guest' };
|
|
66
|
+
}
|
|
67
|
+
const auth = {
|
|
68
|
+
getState: getAuthState,
|
|
69
|
+
subscribe(listener) {
|
|
70
|
+
authListeners.add(listener);
|
|
71
|
+
return () => {
|
|
72
|
+
authListeners.delete(listener);
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
function notifyAuth(state) {
|
|
77
|
+
authListeners.forEach(listener => listener(state));
|
|
78
|
+
}
|
|
79
|
+
function navigate(target) {
|
|
80
|
+
if (typeof window === 'undefined')
|
|
81
|
+
return;
|
|
82
|
+
if (target.type === 'hash') {
|
|
83
|
+
window.location.hash = target.hash;
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (target.type === 'login') {
|
|
87
|
+
assignSafe(context.loginUrl);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (target.type === 'register') {
|
|
91
|
+
assignSafe(context.registerUrl);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (target.type === 'loyaltyPage') {
|
|
95
|
+
assignSafe(context.loyaltyPageUrl);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (target.type === 'view') {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (target.url)
|
|
102
|
+
assignSafe(target.url);
|
|
103
|
+
}
|
|
104
|
+
function assignSafe(url) {
|
|
105
|
+
const safe = safeNavigationUrl(url);
|
|
106
|
+
if (safe)
|
|
107
|
+
window.location.href = url;
|
|
108
|
+
}
|
|
109
|
+
function requireSourceMethod(method) {
|
|
110
|
+
const sourceMethod = source?.[method];
|
|
111
|
+
if (typeof sourceMethod === 'function') {
|
|
112
|
+
return sourceMethod.bind(source);
|
|
113
|
+
}
|
|
114
|
+
return (() => Promise.reject(new Error(`[joy] live source does not support ${String(method)}`)));
|
|
115
|
+
}
|
|
116
|
+
function preferInjected(key, live) {
|
|
117
|
+
const injected = initialData?.[key];
|
|
118
|
+
if (injected !== undefined) {
|
|
119
|
+
return Promise.resolve(injected);
|
|
120
|
+
}
|
|
121
|
+
return live();
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
context: () => context,
|
|
125
|
+
initialData,
|
|
126
|
+
getToken: getToken ?? (async () => null),
|
|
127
|
+
auth,
|
|
128
|
+
navigate,
|
|
129
|
+
notifyAuth,
|
|
130
|
+
data: {
|
|
131
|
+
getShopConfig: () => preferInjected('shopConfig', () => requireSourceMethod('getShopConfig')()),
|
|
132
|
+
getPrograms: () => preferInjected('programs', () => requireSourceMethod('getPrograms')()),
|
|
133
|
+
getTiers: () => preferInjected('tiers', () => requireSourceMethod('getTiers')()),
|
|
134
|
+
getCustomer: () => preferInjected('customer', () => requireSourceMethod('getCustomer')()),
|
|
135
|
+
getActivities: query => requireSourceMethod('getActivities')(parsePageQuery(query)),
|
|
136
|
+
getRewards: async (params) => {
|
|
137
|
+
if (params?.received) {
|
|
138
|
+
const page = await requireSourceMethod('getReceivedRewards')(parsePageQuery(params.query));
|
|
139
|
+
return { available: [], redeemed: [], customerPoints: 0, received: page.received, pagination: page.pagination };
|
|
140
|
+
}
|
|
141
|
+
const { available, redeemed, customerPoints, pagination } = await requireSourceMethod('getRewards')({
|
|
142
|
+
...parsePageQuery(params?.query),
|
|
143
|
+
couponStatus: params?.couponStatus
|
|
144
|
+
});
|
|
145
|
+
return { available, redeemed, customerPoints, pagination };
|
|
146
|
+
},
|
|
147
|
+
getReceivedRewards: params => requireSourceMethod('getReceivedRewards')(params),
|
|
148
|
+
getAddresses: () => requireSourceMethod('getAddresses')(),
|
|
149
|
+
saveAddress: address => requireSourceMethod('saveAddress')(address),
|
|
150
|
+
deleteAddress: addressId => requireSourceMethod('deleteAddress')(addressId),
|
|
151
|
+
updateProfile: options => requireSourceMethod('updateProfile')(options),
|
|
152
|
+
saveBirthday: (birthday, dateOfBirth) => requireSourceMethod('saveBirthday')(birthday, dateOfBirth),
|
|
153
|
+
getReferral: () => requireSourceMethod('getReferral')(),
|
|
154
|
+
getReferralHistory: params => requireSourceMethod('getReferralHistory')(params),
|
|
155
|
+
sendReferralEmail: refereeEmail => requireSourceMethod('sendReferralEmail')(refereeEmail),
|
|
156
|
+
generateReferralLink: email => requireSourceMethod('generateReferralLink')(email),
|
|
157
|
+
getTierRewards: () => requireSourceMethod('getTierRewards')(),
|
|
158
|
+
getPendingTierRewardClaims: () => requireSourceMethod('getPendingTierRewardClaims')(),
|
|
159
|
+
getMilestoneProgress: () => requireSourceMethod('getMilestoneProgress')(),
|
|
160
|
+
claimMilestone: input => requireSourceMethod('claimMilestone')(input),
|
|
161
|
+
saveTierPerkVariantSelection: input => requireSourceMethod('saveTierPerkVariantSelection')(input),
|
|
162
|
+
claimPendingReward: (pendingId, input) => requireSourceMethod('claimPendingReward')(pendingId, input),
|
|
163
|
+
getImpactHistory: params => requireSourceMethod('getImpactHistory')(params),
|
|
164
|
+
getOrders: () => requireSourceMethod('getOrders')(),
|
|
165
|
+
getOrderById: orderId => requireSourceMethod('getOrderById')(orderId),
|
|
166
|
+
getOrderActivities: orderId => requireSourceMethod('getOrderActivities')(orderId),
|
|
167
|
+
getStoreCreditTransactions: params => requireSourceMethod('getStoreCreditTransactions')(params),
|
|
168
|
+
sendRewardToFriend: input => requireSourceMethod('sendRewardToFriend')(input),
|
|
169
|
+
setBirthdayRewards: birthdayRewards => requireSourceMethod('setBirthdayRewards')(birthdayRewards),
|
|
170
|
+
claimBirthdayReward: birthdayRewards => requireSourceMethod('claimBirthdayReward')(birthdayRewards),
|
|
171
|
+
generateQrCode: () => requireSourceMethod('generateQrCode')(),
|
|
172
|
+
joinProgram: joinFrom => requireSourceMethod('joinProgram')(joinFrom),
|
|
173
|
+
checkSegmentPrograms: segmentPrograms => requireSourceMethod('checkSegmentPrograms')(segmentPrograms),
|
|
174
|
+
linkInstagram: instagramUsername => requireSourceMethod('linkInstagram')(instagramUsername),
|
|
175
|
+
disconnectFacebook: () => requireSourceMethod('disconnectFacebook')(),
|
|
176
|
+
getLineAuthUrl: () => requireSourceMethod('getLineAuthUrl')(),
|
|
177
|
+
getAppleWalletLink: () => requireSourceMethod('getAppleWalletLink')(),
|
|
178
|
+
getGoogleWalletLink: () => requireSourceMethod('getGoogleWalletLink')(),
|
|
179
|
+
verifyApplePass: () => requireSourceMethod('verifyApplePass')(),
|
|
180
|
+
getAppleWalletPassCache: () => appleWalletPassCache,
|
|
181
|
+
setAppleWalletPassCache: qrUrl => {
|
|
182
|
+
appleWalletPassCache = { createdApplePass: true, qrCodeDownloadApplePass: qrUrl };
|
|
183
|
+
},
|
|
184
|
+
getFreeGiftStock: programId => requireSourceMethod('getFreeGiftStock')(programId, context.country),
|
|
185
|
+
getInfo: params => requireSourceMethod('getInfo')(params),
|
|
186
|
+
redeem: (programId, opts) => requireSourceMethod('redeem')(programId, opts),
|
|
187
|
+
earn: ({ programId, context }) => requireSourceMethod('earn')(programId, context),
|
|
188
|
+
earnUpload: input => requireSourceMethod('earnUpload')(input),
|
|
189
|
+
earnSocial: programId => requireSourceMethod('earnSocial')(programId),
|
|
190
|
+
getProductByHandle,
|
|
191
|
+
getPromotedCollections,
|
|
192
|
+
getRecentlyViewedProducts: readRecentlyViewedProducts,
|
|
193
|
+
saveRecentlyViewedProducts: writeRecentlyViewedProducts,
|
|
194
|
+
capabilities: HEADLESS_CAPABILITIES
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const HEADLESS_CAPABILITIES = {
|
|
2
|
+
freeGiftStock: true,
|
|
3
|
+
receivedRewards: true,
|
|
4
|
+
referralInvite: true,
|
|
5
|
+
referralHistory: true,
|
|
6
|
+
joinProgram: true,
|
|
7
|
+
socialConnect: true,
|
|
8
|
+
profileEdit: true,
|
|
9
|
+
appleWalletPass: true,
|
|
10
|
+
googleWalletPass: true
|
|
11
|
+
};
|
|
12
|
+
export const DEFAULT_PRODUCTS_ROUTE = '/api/joy-products';
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export function createJoyDataSource(client) {
|
|
2
|
+
return {
|
|
3
|
+
getCustomer: () => client.getCustomer(),
|
|
4
|
+
getPrograms: () => client.getPrograms(),
|
|
5
|
+
getActivities: query => client.getActivities(query),
|
|
6
|
+
getRewards: query => client.getRewards(query),
|
|
7
|
+
getReceivedRewards: params => client.getReceivedRewards(params),
|
|
8
|
+
getAddresses: () => client.getAddresses(),
|
|
9
|
+
saveAddress: address => client.saveAddress(address),
|
|
10
|
+
deleteAddress: addressId => client.deleteAddress(addressId),
|
|
11
|
+
updateProfile: options => client.updateProfile(options),
|
|
12
|
+
saveBirthday: (birthday, dateOfBirth) => client.saveBirthday(birthday, dateOfBirth),
|
|
13
|
+
getReferral: () => client.getReferral(),
|
|
14
|
+
sendReferralEmail: refereeEmail => client.sendReferralEmail(refereeEmail),
|
|
15
|
+
generateReferralLink: email => client.generateReferralLink({ email }),
|
|
16
|
+
getTierRewards: () => client.getTierRewards(),
|
|
17
|
+
getPendingTierRewardClaims: () => client.getPendingTierRewardClaims(),
|
|
18
|
+
getMilestoneProgress: () => client.getMilestoneProgress(),
|
|
19
|
+
claimMilestone: input => client.claimMilestone(input),
|
|
20
|
+
saveTierPerkVariantSelection: input => client.saveTierPerkVariantSelection(input),
|
|
21
|
+
claimPendingReward: (pendingId, input) => client.claimPendingReward(pendingId, input),
|
|
22
|
+
getImpactHistory: params => client.getImpactHistory(params),
|
|
23
|
+
getReferralHistory: params => client.getReferralHistory(params),
|
|
24
|
+
getOrders: () => client.getOrders(),
|
|
25
|
+
getOrderById: orderId => client.getOrderById(orderId),
|
|
26
|
+
getOrderActivities: orderId => client.getOrderActivities(orderId),
|
|
27
|
+
getStoreCreditTransactions: params => client.getStoreCreditTransactions(params),
|
|
28
|
+
sendRewardToFriend: input => client.sendRewardToFriend(input),
|
|
29
|
+
setBirthdayRewards: birthdayRewards => client.setBirthdayRewards(birthdayRewards),
|
|
30
|
+
claimBirthdayReward: birthdayRewards => client.claimBirthdayReward(birthdayRewards),
|
|
31
|
+
generateQrCode: () => client.generateQrCode(),
|
|
32
|
+
joinProgram: joinFrom => client.joinProgram(joinFrom),
|
|
33
|
+
checkSegmentPrograms: segmentPrograms => client.checkSegmentPrograms(segmentPrograms),
|
|
34
|
+
linkInstagram: instagramUsername => client.linkInstagram(instagramUsername),
|
|
35
|
+
disconnectFacebook: () => client.disconnectFacebook(),
|
|
36
|
+
getLineAuthUrl: () => client.getLineAuthUrl(),
|
|
37
|
+
getAppleWalletLink: async () => (await client.createApplePass()).qrUrl,
|
|
38
|
+
getGoogleWalletLink: async () => (await client.getGoogleWalletPass()).link,
|
|
39
|
+
verifyApplePass: async () => (await client.verifyApplePass()).exists,
|
|
40
|
+
getFreeGiftStock: (programId, country) => client.getFreeGiftStock(programId, { country }),
|
|
41
|
+
getInfo: params => client.getInfo(params),
|
|
42
|
+
async redeem(programId, opts) {
|
|
43
|
+
return client.redeem(programId, opts ? { ...opts, recipient: opts.recipient ?? undefined } : opts);
|
|
44
|
+
},
|
|
45
|
+
earn: (programId, context) => client.earn(programId, context),
|
|
46
|
+
earnUpload: ({ images }) => client.uploadEarnImages(images),
|
|
47
|
+
earnSocial: programId => client.earnSocial(programId)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export function createProductByHandleFetcher(productsRoute) {
|
|
2
|
+
let pending = [];
|
|
3
|
+
let scheduled = false;
|
|
4
|
+
async function flush() {
|
|
5
|
+
const batch = pending;
|
|
6
|
+
pending = [];
|
|
7
|
+
scheduled = false;
|
|
8
|
+
const handles = Array.from(new Set(batch.map(entry => entry.handle).filter(Boolean)));
|
|
9
|
+
if (!handles.length) {
|
|
10
|
+
batch.forEach(entry => entry.resolve(null));
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
const url = `${productsRoute}?handles=${handles.map(encodeURIComponent).join(',')}`;
|
|
15
|
+
const response = await fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
|
|
16
|
+
if (!response.ok)
|
|
17
|
+
throw new Error(`joy-products ${response.status}`);
|
|
18
|
+
const body = (await response.json());
|
|
19
|
+
const products = Array.isArray(body.products) ? body.products : [];
|
|
20
|
+
const resolvedHandles = Array.isArray(body.handles) ? body.handles : [];
|
|
21
|
+
const byHandle = new Map(resolvedHandles.map((handle, index) => [handle, products[index] ?? null]));
|
|
22
|
+
batch.forEach(entry => entry.resolve(byHandle.get(entry.handle) ?? null));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
batch.forEach(entry => entry.resolve(null));
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return function getProductByHandle(handle) {
|
|
29
|
+
return new Promise(resolve => {
|
|
30
|
+
pending.push({ handle, resolve });
|
|
31
|
+
if (!scheduled) {
|
|
32
|
+
scheduled = true;
|
|
33
|
+
queueMicrotask(flush);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export function createPromotedCollectionsFetcher(productsRoute) {
|
|
2
|
+
return async function getPromotedCollections(selections) {
|
|
3
|
+
const handles = Array.from(new Set((selections ?? []).map(selection => selection?.handle).filter(Boolean)));
|
|
4
|
+
if (!handles.length)
|
|
5
|
+
return [];
|
|
6
|
+
const snapshotByHandle = new Map();
|
|
7
|
+
for (const selection of selections ?? []) {
|
|
8
|
+
if (!selection?.handle || snapshotByHandle.has(selection.handle))
|
|
9
|
+
continue;
|
|
10
|
+
snapshotByHandle.set(selection.handle, {
|
|
11
|
+
id: String(selection.id || selection.handle),
|
|
12
|
+
title: selection.title || '',
|
|
13
|
+
handle: selection.handle,
|
|
14
|
+
url: `/collections/${selection.handle}`
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
const snapshots = handles
|
|
18
|
+
.map(handle => snapshotByHandle.get(handle))
|
|
19
|
+
.filter(Boolean);
|
|
20
|
+
try {
|
|
21
|
+
const url = `${productsRoute}?collections=${handles.map(encodeURIComponent).join(',')}`;
|
|
22
|
+
const response = await fetch(url, {
|
|
23
|
+
headers: { Accept: 'application/json' },
|
|
24
|
+
credentials: 'same-origin'
|
|
25
|
+
});
|
|
26
|
+
if (!response.ok)
|
|
27
|
+
throw new Error(`joy-products collections ${response.status}`);
|
|
28
|
+
const body = (await response.json());
|
|
29
|
+
const resolved = Array.isArray(body.collections)
|
|
30
|
+
? body.collections
|
|
31
|
+
: [];
|
|
32
|
+
if (!resolved.length)
|
|
33
|
+
return snapshots;
|
|
34
|
+
const resolvedByHandle = new Map(resolved.map(collection => [collection.handle, collection]));
|
|
35
|
+
return handles
|
|
36
|
+
.map(handle => resolvedByHandle.get(handle) ?? snapshotByHandle.get(handle))
|
|
37
|
+
.filter(Boolean);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return snapshots;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|