@shopify/hydrogen-react 2023.10.0 → 2023.10.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/dist/browser-dev/ShopPayButton.mjs +22 -1
- package/dist/browser-dev/ShopPayButton.mjs.map +1 -1
- package/dist/browser-dev/storefront-client.mjs +2 -2
- package/dist/browser-dev/storefront-client.mjs.map +1 -1
- package/dist/browser-prod/ShopPayButton.mjs +22 -1
- package/dist/browser-prod/ShopPayButton.mjs.map +1 -1
- package/dist/browser-prod/storefront-client.mjs +1 -1
- package/dist/browser-prod/storefront-client.mjs.map +1 -1
- package/dist/node-dev/ShopPayButton.js +22 -1
- package/dist/node-dev/ShopPayButton.js.map +1 -1
- package/dist/node-dev/ShopPayButton.mjs +22 -1
- package/dist/node-dev/ShopPayButton.mjs.map +1 -1
- package/dist/node-dev/storefront-client.js +2 -2
- package/dist/node-dev/storefront-client.js.map +1 -1
- package/dist/node-dev/storefront-client.mjs +2 -2
- package/dist/node-dev/storefront-client.mjs.map +1 -1
- package/dist/node-prod/ShopPayButton.js +22 -1
- package/dist/node-prod/ShopPayButton.js.map +1 -1
- package/dist/node-prod/ShopPayButton.mjs +22 -1
- package/dist/node-prod/ShopPayButton.mjs.map +1 -1
- package/dist/node-prod/storefront-client.js +1 -1
- package/dist/node-prod/storefront-client.js.map +1 -1
- package/dist/node-prod/storefront-client.mjs +1 -1
- package/dist/node-prod/storefront-client.mjs.map +1 -1
- package/dist/types/ShopPayButton.d.ts +8 -2
- package/dist/umd/hydrogen-react.dev.js +23 -3
- package/dist/umd/hydrogen-react.dev.js.map +1 -1
- package/dist/umd/hydrogen-react.prod.js +18 -18
- package/dist/umd/hydrogen-react.prod.js.map +1 -1
- package/package.json +3 -3
|
@@ -3,7 +3,11 @@ import { useShop, defaultShopifyContext } from "./ShopifyProvider.mjs";
|
|
|
3
3
|
import { useLoadScript } from "./load-script.mjs";
|
|
4
4
|
import { parseGid } from "./analytics-utils.mjs";
|
|
5
5
|
const SHOPJS_URL = "https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js";
|
|
6
|
+
function isChannel(channel) {
|
|
7
|
+
return channel === "headless" || channel === "hydrogen";
|
|
8
|
+
}
|
|
6
9
|
function ShopPayButton({
|
|
10
|
+
channel,
|
|
7
11
|
variantIds,
|
|
8
12
|
className,
|
|
9
13
|
variantIdsAndQuantities,
|
|
@@ -14,6 +18,7 @@ function ShopPayButton({
|
|
|
14
18
|
const storeDomain = _storeDomain || (shop == null ? void 0 : shop.storeDomain);
|
|
15
19
|
const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);
|
|
16
20
|
let ids = [];
|
|
21
|
+
let channelAttribution;
|
|
17
22
|
if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {
|
|
18
23
|
throw new Error(MissingStoreDomainErrorMessage);
|
|
19
24
|
}
|
|
@@ -23,6 +28,13 @@ function ShopPayButton({
|
|
|
23
28
|
if (!variantIds && !variantIdsAndQuantities) {
|
|
24
29
|
throw new Error(MissingPropsErrorMessage);
|
|
25
30
|
}
|
|
31
|
+
if (channel) {
|
|
32
|
+
if (isChannel(channel)) {
|
|
33
|
+
channelAttribution = channel;
|
|
34
|
+
} else {
|
|
35
|
+
throw new Error(InvalidChannelErrorMessage);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
26
38
|
if (variantIds) {
|
|
27
39
|
ids = variantIds.reduce((prev, curr) => {
|
|
28
40
|
const bareId = parseGid(curr).id;
|
|
@@ -48,14 +60,23 @@ function ShopPayButton({
|
|
|
48
60
|
const style = width ? {
|
|
49
61
|
"--shop-pay-button-width": width
|
|
50
62
|
} : void 0;
|
|
51
|
-
return /* @__PURE__ */ jsx("div", { className, style, children: shopPayLoadedStatus === "done" && /* @__PURE__ */ jsx(
|
|
63
|
+
return /* @__PURE__ */ jsx("div", { className, style, children: shopPayLoadedStatus === "done" && /* @__PURE__ */ jsx(
|
|
64
|
+
"shop-pay-button",
|
|
65
|
+
{
|
|
66
|
+
...channelAttribution ? { channel: channelAttribution } : {},
|
|
67
|
+
"store-url": storeDomain,
|
|
68
|
+
variants: ids.join(",")
|
|
69
|
+
}
|
|
70
|
+
) });
|
|
52
71
|
}
|
|
53
72
|
const MissingStoreDomainErrorMessage = 'You must pass a "storeDomain" prop to the "ShopPayButton" component, or wrap it in a "ShopifyProvider" component.';
|
|
54
73
|
const InvalidPropsErrorMessage = `You must pass in "variantIds" in the form of ["gid://shopify/ProductVariant/1"]`;
|
|
55
74
|
const MissingPropsErrorMessage = `You must pass in either "variantIds" or "variantIdsAndQuantities" to ShopPayButton`;
|
|
56
75
|
const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;
|
|
76
|
+
const InvalidChannelErrorMessage = `Invalid channel attribution value. Must be either "headless" or "hydrogen"`;
|
|
57
77
|
export {
|
|
58
78
|
DoublePropsErrorMessage,
|
|
79
|
+
InvalidChannelErrorMessage,
|
|
59
80
|
InvalidPropsErrorMessage,
|
|
60
81
|
MissingPropsErrorMessage,
|
|
61
82
|
MissingStoreDomainErrorMessage,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShopPayButton.mjs","sources":["../../src/ShopPayButton.tsx"],"sourcesContent":["import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button store-url={storeDomain}
|
|
1
|
+
{"version":3,"file":"ShopPayButton.mjs","sources":["../../src/ShopPayButton.tsx"],"sourcesContent":["import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n ShopPayChannelAttribution &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ntype ShopPayChannelAttribution = {\n /** A string that adds channel attribution to the order. Can be either `headless` or `hydrogen` */\n channel?: 'headless' | 'hydrogen';\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n channel?: string;\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\nfunction isChannel(\n channel: string,\n): channel is Exclude<ShopPayChannelAttribution['channel'], undefined> {\n return channel === 'headless' || channel === 'hydrogen';\n}\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n channel,\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n let channelAttribution: string | undefined;\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (channel) {\n if (isChannel(channel)) {\n channelAttribution = channel;\n } else {\n throw new Error(InvalidChannelErrorMessage);\n }\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button\n {...(channelAttribution ? {channel: channelAttribution} : {})}\n store-url={storeDomain}\n variants={ids.join(',')}\n />\n )}\n </div>\n );\n}\n\nexport const MissingStoreDomainErrorMessage =\n 'You must pass a \"storeDomain\" prop to the \"ShopPayButton\" component, or wrap it in a \"ShopifyProvider\" component.';\nexport const InvalidPropsErrorMessage = `You must pass in \"variantIds\" in the form of [\"gid://shopify/ProductVariant/1\"]`;\nexport const MissingPropsErrorMessage = `You must pass in either \"variantIds\" or \"variantIdsAndQuantities\" to ShopPayButton`;\nexport const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;\nexport const InvalidChannelErrorMessage = `Invalid channel attribution value. Must be either \"headless\" or \"hydrogen\"`;\n"],"names":[],"mappings":";;;;AAyDA,MAAM,aACJ;AAEF,SAAS,UACP,SACqE;AAC9D,SAAA,YAAY,cAAc,YAAY;AAC/C;AAOO,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AACf,GAAoC;AAClC,QAAM,OAAO;AACP,QAAA,cAAc,iBAA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AAA,MAC3D,aAAW;AAAA,MACX,UAAU,IAAI,KAAK,GAAG;AAAA,IAAA;AAAA,EAG5B,EAAA,CAAA;AAEJ;AAEO,MAAM,iCACX;AACK,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;AAChC,MAAM,6BAA6B;"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SFAPI_VERSION } from "./storefront-api-constants.mjs";
|
|
2
|
+
const isMockShop = (domain) => domain.includes("mock.shop");
|
|
2
3
|
function createStorefrontClient(props) {
|
|
3
4
|
const {
|
|
4
5
|
storeDomain,
|
|
@@ -19,7 +20,7 @@ Received "${storeDomain}".`
|
|
|
19
20
|
You may run into unexpected errors if these versions don't match. Received verion: "${storefrontApiVersion}"; expected version "${SFAPI_VERSION}"`
|
|
20
21
|
);
|
|
21
22
|
}
|
|
22
|
-
if (!privateStorefrontToken && !globalThis.document) {
|
|
23
|
+
if (!privateStorefrontToken && !globalThis.document && !isMockShop(storeDomain)) {
|
|
23
24
|
warnOnce(
|
|
24
25
|
`Using a private storefront token is recommended for server environments.
|
|
25
26
|
Refer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`
|
|
@@ -30,7 +31,6 @@ Refer to the authentication https://shopify.dev/api/storefront#authentication do
|
|
|
30
31
|
"You are attempting to use a private token in an environment where it can be easily accessed by anyone.\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop"
|
|
31
32
|
);
|
|
32
33
|
}
|
|
33
|
-
const isMockShop = (domain) => domain.includes("mock.shop");
|
|
34
34
|
const getShopifyDomain = (overrideProps) => {
|
|
35
35
|
const domain = (overrideProps == null ? void 0 : overrideProps.storeDomain) ?? storeDomain;
|
|
36
36
|
return domain.includes("://") ? domain : `https://${domain}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion = SFAPI_VERSION,\n contentType,\n } = props;\n\n if (!storeDomain) {\n throw new Error(\n H2_PREFIX_ERROR +\n `\\`storeDomain\\` is required when creating a new Storefront client.\\nReceived \"${storeDomain}\".`,\n );\n }\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.` +\n `\\nYou may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (__HYDROGEN_DEV__ && !privateStorefrontToken && !globalThis.document) {\n warnOnce(\n `Using a private storefront token is recommended for server environments.` +\n `\\nRefer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n 'You are attempting to use a private token in an environment where it can be easily accessed by anyone.' +\n '\\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop',\n );\n }\n\n const isMockShop = (domain: string): boolean => domain.includes('mock.shop');\n const getShopifyDomain: StorefrontClientReturn['getShopifyDomain'] = (\n overrideProps,\n ) => {\n const domain = overrideProps?.storeDomain ?? storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n };\n\n return {\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const domain = getShopifyDomain(overrideProps);\n const apiUrl = domain + (domain.endsWith('/') ? 'api' : '/api');\n\n if (isMockShop(domain)) return apiUrl;\n\n return `${apiUrl}/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (\n !privateStorefrontToken &&\n !overrideProps?.privateStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`',\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n 'It is recommended to pass in the `buyerIp` property which improves analytics and data in the admin.',\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (\n !publicStorefrontToken &&\n !overrideProps?.publicStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`',\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst H2_PREFIX_ERROR = '[h2:error:createStorefrontClient] ';\nconst H2_PREFIX_WARN = '[h2:warn:createStorefrontClient] ';\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(H2_PREFIX_WARN + string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n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oBAAmB,+CAAe,gBAAe;AAEhD,aAAA;AAAA;AAAA,QAEL,gBACE,qBAAqB,YACjB,wBACA;AAAA,QACN,iBAAiB;AAAA,QACjB,wBAAwB;AAAA,QACxB,iBAAiB;AAAA,QACjB,qCACE,+CAAe,2BAA0B,0BAA0B;AAAA,QACrE,IAAI,+CAAe,WACf,EAAC,+BAA+B,cAAc,QAAA,IAC9C,CAAC;AAAA,MAAA;AAAA,IAET;AAAA,IACA,sBAAsB,eAAuC;AAEzD,UAAA,CAAC,yBACD,EAAC,+CAAe,0BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAEM,YAAA,oBACJ,+CAAe,gBAAe,eAAe;AAExC,aAAA;AAAA,QACL;AAAA,QACA;AAAA,SACA,+CAAe,0BAAyB,yBAAyB;AAAA,MAAA;AAAA,IAErE;AAAA,EAAA;AAEJ;AAEgB,SAAA,yBACd,aACA,sBACA,aAOA;AACO,SAAA;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AACvB,MAAM,WAAW,CAAC,WAAyB;AACzC,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACjB,YAAA,KAAK,iBAAiB,MAAM;AACpC,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
1
|
+
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\nconst isMockShop = (domain: string): boolean => domain.includes('mock.shop');\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion = SFAPI_VERSION,\n contentType,\n } = props;\n\n if (!storeDomain) {\n throw new Error(\n H2_PREFIX_ERROR +\n `\\`storeDomain\\` is required when creating a new Storefront client.\\nReceived \"${storeDomain}\".`,\n );\n }\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.` +\n `\\nYou may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (\n __HYDROGEN_DEV__ &&\n !privateStorefrontToken &&\n !globalThis.document &&\n !isMockShop(storeDomain)\n ) {\n warnOnce(\n `Using a private storefront token is recommended for server environments.` +\n `\\nRefer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n 'You are attempting to use a private token in an environment where it can be easily accessed by anyone.' +\n '\\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop',\n );\n }\n\n const getShopifyDomain: StorefrontClientReturn['getShopifyDomain'] = (\n overrideProps,\n ) => {\n const domain = overrideProps?.storeDomain ?? storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n };\n\n return {\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const domain = getShopifyDomain(overrideProps);\n const apiUrl = domain + (domain.endsWith('/') ? 'api' : '/api');\n\n if (isMockShop(domain)) return apiUrl;\n\n return `${apiUrl}/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (\n !privateStorefrontToken &&\n !overrideProps?.privateStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`',\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n 'It is recommended to pass in the `buyerIp` property which improves analytics and data in the admin.',\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (\n !publicStorefrontToken &&\n !overrideProps?.publicStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`',\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst H2_PREFIX_ERROR = '[h2:error:createStorefrontClient] ';\nconst H2_PREFIX_WARN = '[h2:warn:createStorefrontClient] ';\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(H2_PREFIX_WARN + string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAmBA,MAAM,aAAa,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jB,wBACA;AAAA,QACN,iBAAiB;AAAA,QACjB,wBAAwB;AAAA,QACxB,iBAAiB;AAAA,QACjB,qCACE,+CAAe,2BAA0B,0BAA0B;AAAA,QACrE,IAAI,+CAAe,WACf,EAAC,+BAA+B,cAAc,QAAA,IAC9C,CAAC;AAAA,MAAA;AAAA,IAET;AAAA,IACA,sBAAsB,eAAuC;AAEzD,UAAA,CAAC,yBACD,EAAC,+CAAe,0BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAEM,YAAA,oBACJ,+CAAe,gBAAe,eAAe;AAExC,aAAA;AAAA,QACL;AAAA,QACA;AAAA,SACA,+CAAe,0BAAyB,yBAAyB;AAAA,MAAA;AAAA,IAErE;AAAA,EAAA;AAEJ;AAEgB,SAAA,yBACd,aACA,sBACA,aAOA;AACO,SAAA;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AACvB,MAAM,WAAW,CAAC,WAAyB;AACzC,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACjB,YAAA,KAAK,iBAAiB,MAAM;AACpC,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
@@ -3,7 +3,11 @@ import { useShop, defaultShopifyContext } from "./ShopifyProvider.mjs";
|
|
|
3
3
|
import { useLoadScript } from "./load-script.mjs";
|
|
4
4
|
import { parseGid } from "./analytics-utils.mjs";
|
|
5
5
|
const SHOPJS_URL = "https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js";
|
|
6
|
+
function isChannel(channel) {
|
|
7
|
+
return channel === "headless" || channel === "hydrogen";
|
|
8
|
+
}
|
|
6
9
|
function ShopPayButton({
|
|
10
|
+
channel,
|
|
7
11
|
variantIds,
|
|
8
12
|
className,
|
|
9
13
|
variantIdsAndQuantities,
|
|
@@ -14,6 +18,7 @@ function ShopPayButton({
|
|
|
14
18
|
const storeDomain = _storeDomain || (shop == null ? void 0 : shop.storeDomain);
|
|
15
19
|
const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);
|
|
16
20
|
let ids = [];
|
|
21
|
+
let channelAttribution;
|
|
17
22
|
if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {
|
|
18
23
|
throw new Error(MissingStoreDomainErrorMessage);
|
|
19
24
|
}
|
|
@@ -23,6 +28,13 @@ function ShopPayButton({
|
|
|
23
28
|
if (!variantIds && !variantIdsAndQuantities) {
|
|
24
29
|
throw new Error(MissingPropsErrorMessage);
|
|
25
30
|
}
|
|
31
|
+
if (channel) {
|
|
32
|
+
if (isChannel(channel)) {
|
|
33
|
+
channelAttribution = channel;
|
|
34
|
+
} else {
|
|
35
|
+
throw new Error(InvalidChannelErrorMessage);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
26
38
|
if (variantIds) {
|
|
27
39
|
ids = variantIds.reduce((prev, curr) => {
|
|
28
40
|
const bareId = parseGid(curr).id;
|
|
@@ -48,14 +60,23 @@ function ShopPayButton({
|
|
|
48
60
|
const style = width ? {
|
|
49
61
|
"--shop-pay-button-width": width
|
|
50
62
|
} : void 0;
|
|
51
|
-
return /* @__PURE__ */ jsx("div", { className, style, children: shopPayLoadedStatus === "done" && /* @__PURE__ */ jsx(
|
|
63
|
+
return /* @__PURE__ */ jsx("div", { className, style, children: shopPayLoadedStatus === "done" && /* @__PURE__ */ jsx(
|
|
64
|
+
"shop-pay-button",
|
|
65
|
+
{
|
|
66
|
+
...channelAttribution ? { channel: channelAttribution } : {},
|
|
67
|
+
"store-url": storeDomain,
|
|
68
|
+
variants: ids.join(",")
|
|
69
|
+
}
|
|
70
|
+
) });
|
|
52
71
|
}
|
|
53
72
|
const MissingStoreDomainErrorMessage = 'You must pass a "storeDomain" prop to the "ShopPayButton" component, or wrap it in a "ShopifyProvider" component.';
|
|
54
73
|
const InvalidPropsErrorMessage = `You must pass in "variantIds" in the form of ["gid://shopify/ProductVariant/1"]`;
|
|
55
74
|
const MissingPropsErrorMessage = `You must pass in either "variantIds" or "variantIdsAndQuantities" to ShopPayButton`;
|
|
56
75
|
const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;
|
|
76
|
+
const InvalidChannelErrorMessage = `Invalid channel attribution value. Must be either "headless" or "hydrogen"`;
|
|
57
77
|
export {
|
|
58
78
|
DoublePropsErrorMessage,
|
|
79
|
+
InvalidChannelErrorMessage,
|
|
59
80
|
InvalidPropsErrorMessage,
|
|
60
81
|
MissingPropsErrorMessage,
|
|
61
82
|
MissingStoreDomainErrorMessage,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShopPayButton.mjs","sources":["../../src/ShopPayButton.tsx"],"sourcesContent":["import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button store-url={storeDomain}
|
|
1
|
+
{"version":3,"file":"ShopPayButton.mjs","sources":["../../src/ShopPayButton.tsx"],"sourcesContent":["import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n ShopPayChannelAttribution &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ntype ShopPayChannelAttribution = {\n /** A string that adds channel attribution to the order. Can be either `headless` or `hydrogen` */\n channel?: 'headless' | 'hydrogen';\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n channel?: string;\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\nfunction isChannel(\n channel: string,\n): channel is Exclude<ShopPayChannelAttribution['channel'], undefined> {\n return channel === 'headless' || channel === 'hydrogen';\n}\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n channel,\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n let channelAttribution: string | undefined;\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (channel) {\n if (isChannel(channel)) {\n channelAttribution = channel;\n } else {\n throw new Error(InvalidChannelErrorMessage);\n }\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button\n {...(channelAttribution ? {channel: channelAttribution} : {})}\n store-url={storeDomain}\n variants={ids.join(',')}\n />\n )}\n </div>\n );\n}\n\nexport const MissingStoreDomainErrorMessage =\n 'You must pass a \"storeDomain\" prop to the \"ShopPayButton\" component, or wrap it in a \"ShopifyProvider\" component.';\nexport const InvalidPropsErrorMessage = `You must pass in \"variantIds\" in the form of [\"gid://shopify/ProductVariant/1\"]`;\nexport const MissingPropsErrorMessage = `You must pass in either \"variantIds\" or \"variantIdsAndQuantities\" to ShopPayButton`;\nexport const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;\nexport const InvalidChannelErrorMessage = `Invalid channel attribution value. Must be either \"headless\" or \"hydrogen\"`;\n"],"names":[],"mappings":";;;;AAyDA,MAAM,aACJ;AAEF,SAAS,UACP,SACqE;AAC9D,SAAA,YAAY,cAAc,YAAY;AAC/C;AAOO,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AACf,GAAoC;AAClC,QAAM,OAAO;AACP,QAAA,cAAc,iBAAgB,6BAAM;AACpC,QAAA,sBAAsB,cAAc,UAAU;AAEpD,MAAI,MAAgB,CAAA;AAChB,MAAA;AAEJ,MAAI,CAAC,eAAe,gBAAgB,sBAAsB,aAAa;AAC/D,UAAA,IAAI,MAAM,8BAA8B;AAAA,EAChD;AAE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C,MAAM,6BAA6B;"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SFAPI_VERSION } from "./storefront-api-constants.mjs";
|
|
2
|
+
const isMockShop = (domain) => domain.includes("mock.shop");
|
|
2
3
|
function createStorefrontClient(props) {
|
|
3
4
|
const {
|
|
4
5
|
storeDomain,
|
|
@@ -19,7 +20,6 @@ Received "${storeDomain}".`
|
|
|
19
20
|
You may run into unexpected errors if these versions don't match. Received verion: "${storefrontApiVersion}"; expected version "${SFAPI_VERSION}"`
|
|
20
21
|
);
|
|
21
22
|
}
|
|
22
|
-
const isMockShop = (domain) => domain.includes("mock.shop");
|
|
23
23
|
const getShopifyDomain = (overrideProps) => {
|
|
24
24
|
const domain = (overrideProps == null ? void 0 : overrideProps.storeDomain) ?? storeDomain;
|
|
25
25
|
return domain.includes("://") ? domain : `https://${domain}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion = SFAPI_VERSION,\n contentType,\n } = props;\n\n if (!storeDomain) {\n throw new Error(\n H2_PREFIX_ERROR +\n `\\`storeDomain\\` is required when creating a new Storefront client.\\nReceived \"${storeDomain}\".`,\n );\n }\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.` +\n `\\nYou may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (__HYDROGEN_DEV__ && !privateStorefrontToken && !globalThis.document) {\n warnOnce(\n `Using a private storefront token is recommended for server environments.` +\n `\\nRefer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n 'You are attempting to use a private token in an environment where it can be easily accessed by anyone.' +\n '\\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop',\n );\n }\n\n const isMockShop = (domain: string): boolean => domain.includes('mock.shop');\n const getShopifyDomain: StorefrontClientReturn['getShopifyDomain'] = (\n overrideProps,\n ) => {\n const domain = overrideProps?.storeDomain ?? storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n };\n\n return {\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const domain = getShopifyDomain(overrideProps);\n const apiUrl = domain + (domain.endsWith('/') ? 'api' : '/api');\n\n if (isMockShop(domain)) return apiUrl;\n\n return `${apiUrl}/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (\n !privateStorefrontToken &&\n !overrideProps?.privateStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`',\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n 'It is recommended to pass in the `buyerIp` property which improves analytics and data in the admin.',\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (\n !publicStorefrontToken &&\n !overrideProps?.publicStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`',\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst H2_PREFIX_ERROR = '[h2:error:createStorefrontClient] ';\nconst H2_PREFIX_WARN = '[h2:warn:createStorefrontClient] ';\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(H2_PREFIX_WARN + string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAwBO,SAAS,uBACd,OACwB;AAClB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA,uBAAuB;AAAA,IACvB;AAAA,EACE,IAAA;AAEJ,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI;AAAA,MACR,kBACE;AAAA,YAAiF,WAAW;AAAA,IAAA;AAAA,EAElG;AAEA,MAAI,yBAAyB,eAAe;AAC1C;AAAA,MACE;AAAA,sFAC2F,oBAAoB,wBAAwB,aAAa;AAAA,IAAA;AAAA,EAExJ;AAkBA,QAAM,aAAa,CAAC,WAA4B,OAAO,SAAS,WAAW;AACrE,QAAA,mBAA+D,CACnE,kBACG;AACG,UAAA,UAAS,+CAAe,gBAAe;AAC7C,WAAO,OAAO,SAAS,KAAK,IAAI,SAAS,W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AM,kBAAkB;AACxB,MAAM,iBAAiB;AACvB,MAAM,WAAW,CAAC,WAAyB;AACzC,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACjB,YAAA,KAAK,iBAAiB,MAAM;AACpC,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
1
|
+
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\nconst isMockShop = (domain: string): boolean => domain.includes('mock.shop');\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion = SFAPI_VERSION,\n contentType,\n } = props;\n\n if (!storeDomain) {\n throw new Error(\n H2_PREFIX_ERROR +\n `\\`storeDomain\\` is required when creating a new Storefront client.\\nReceived \"${storeDomain}\".`,\n );\n }\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.` +\n `\\nYou may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (\n __HYDROGEN_DEV__ &&\n !privateStorefrontToken &&\n !globalThis.document &&\n !isMockShop(storeDomain)\n ) {\n warnOnce(\n `Using a private storefront token is recommended for server environments.` +\n `\\nRefer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n 'You are attempting to use a private token in an environment where it can be easily accessed by anyone.' +\n '\\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop',\n );\n }\n\n const getShopifyDomain: StorefrontClientReturn['getShopifyDomain'] = (\n overrideProps,\n ) => {\n const domain = overrideProps?.storeDomain ?? storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n };\n\n return {\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const domain = getShopifyDomain(overrideProps);\n const apiUrl = domain + (domain.endsWith('/') ? 'api' : '/api');\n\n if (isMockShop(domain)) return apiUrl;\n\n return `${apiUrl}/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (\n !privateStorefrontToken &&\n !overrideProps?.privateStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`',\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n 'It is recommended to pass in the `buyerIp` property which improves analytics and data in the admin.',\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (\n !publicStorefrontToken &&\n !overrideProps?.publicStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`',\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst H2_PREFIX_ERROR = '[h2:error:createStorefrontClient] ';\nconst H2_PREFIX_WARN = '[h2:warn:createStorefrontClient] ';\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(H2_PREFIX_WARN + string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAmBA,MAAM,aAAa,CAAC,WAA4B,OAAO,SAAS,WAAW;AAOpE,SAAS,uBACd,OACwB;AAClB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA,uBAAuB;AAAA,IACvB;AAAA,EACE,IAAA;AAEJ,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI;AAAA,MACR,kBACE;AAAA,YAAiF,WAAW;AAAA,IAAA;AAAA,EAElG;AAEA,MAAI,yBAAyB,eAAe;AAC1C;AAAA,MACE;AAAA,sFAC2F,oBAAoB,wBAAwB,aAAa;AAAA,IAAA;AAAA,EAExJ;AAuBM,QAAA,mBAA+D,CACnE,kBACG;AACG,UAAA,UAAS,+CAAe,gBAAe;AAC7C,WAAO,OAAO,SAAS,KAAK,IAAI,SAAS,WAAW,MAAM;AAAA,EAAA;AAGrD,SAAA;AAAA,IACL;AAAA,IACA,oBAAoB,eAAuB;AACnC,YAAA,SAAS,iBAAiB,aAAa;AAC7C,YAAM,SAAS,UAAU,OAAO,SAAS,GAAG,IAAI,QAAQ;AAExD,UAAI,WAAW,MAAM;AAAU,eAAA;AAE/B,aAAO,GAAG,MAAM,KACd,+CAAe,yBAAwB,oBACzC;AAAA,IACF;AAAA,IACA,uBAAuB,eAAuC;AAE1D,UAAA,CAAC,0BACD,EAAC,+CAAe,2BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAQM,YAAA,oBAAmB,+CAAe,gBAAe;AAEhD,aAAA;AAAA;AAAA,QAEL,gBACE,qBAAqB,YACjB,wBACA;AAAA,QACN,iBAAiB;AAAA,QACjB,wBAAwB;AAAA,QACxB,iBAAiB;AAAA,QACjB,qCACE,+CAAe,2BAA0B,0BAA0B;AAAA,QACrE,IAAI,+CAAe,WACf,EAAC,+BAA+B,cAAc,QAAA,IAC9C,CAAC;AAAA,MAAA;AAAA,IAET;AAAA,IACA,sBAAsB,eAAuC;AAEzD,UAAA,CAAC,yBACD,EAAC,+CAAe,0BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAEM,YAAA,oBACJ,+CAAe,gBAAe,eAAe;AAExC,aAAA;AAAA,QACL;AAAA,QACA;AAAA,SACA,+CAAe,0BAAyB,yBAAyB;AAAA,MAAA;AAAA,IAErE;AAAA,EAAA;AAEJ;AAEgB,SAAA,yBACd,aACA,sBACA,aAOA;AACO,SAAA;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AACvB,MAAM,WAAW,CAAC,WAAyB;AACzC,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACjB,YAAA,KAAK,iBAAiB,MAAM;AACpC,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
@@ -5,7 +5,11 @@ const ShopifyProvider = require("./ShopifyProvider.js");
|
|
|
5
5
|
const loadScript = require("./load-script.js");
|
|
6
6
|
const analyticsUtils = require("./analytics-utils.js");
|
|
7
7
|
const SHOPJS_URL = "https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js";
|
|
8
|
+
function isChannel(channel) {
|
|
9
|
+
return channel === "headless" || channel === "hydrogen";
|
|
10
|
+
}
|
|
8
11
|
function ShopPayButton({
|
|
12
|
+
channel,
|
|
9
13
|
variantIds,
|
|
10
14
|
className,
|
|
11
15
|
variantIdsAndQuantities,
|
|
@@ -16,6 +20,7 @@ function ShopPayButton({
|
|
|
16
20
|
const storeDomain = _storeDomain || (shop == null ? void 0 : shop.storeDomain);
|
|
17
21
|
const shopPayLoadedStatus = loadScript.useLoadScript(SHOPJS_URL);
|
|
18
22
|
let ids = [];
|
|
23
|
+
let channelAttribution;
|
|
19
24
|
if (!storeDomain || storeDomain === ShopifyProvider.defaultShopifyContext.storeDomain) {
|
|
20
25
|
throw new Error(MissingStoreDomainErrorMessage);
|
|
21
26
|
}
|
|
@@ -25,6 +30,13 @@ function ShopPayButton({
|
|
|
25
30
|
if (!variantIds && !variantIdsAndQuantities) {
|
|
26
31
|
throw new Error(MissingPropsErrorMessage);
|
|
27
32
|
}
|
|
33
|
+
if (channel) {
|
|
34
|
+
if (isChannel(channel)) {
|
|
35
|
+
channelAttribution = channel;
|
|
36
|
+
} else {
|
|
37
|
+
throw new Error(InvalidChannelErrorMessage);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
28
40
|
if (variantIds) {
|
|
29
41
|
ids = variantIds.reduce((prev, curr) => {
|
|
30
42
|
const bareId = analyticsUtils.parseGid(curr).id;
|
|
@@ -50,13 +62,22 @@ function ShopPayButton({
|
|
|
50
62
|
const style = width ? {
|
|
51
63
|
"--shop-pay-button-width": width
|
|
52
64
|
} : void 0;
|
|
53
|
-
return /* @__PURE__ */ jsxRuntime.jsx("div", { className, style, children: shopPayLoadedStatus === "done" && /* @__PURE__ */ jsxRuntime.jsx(
|
|
65
|
+
return /* @__PURE__ */ jsxRuntime.jsx("div", { className, style, children: shopPayLoadedStatus === "done" && /* @__PURE__ */ jsxRuntime.jsx(
|
|
66
|
+
"shop-pay-button",
|
|
67
|
+
{
|
|
68
|
+
...channelAttribution ? { channel: channelAttribution } : {},
|
|
69
|
+
"store-url": storeDomain,
|
|
70
|
+
variants: ids.join(",")
|
|
71
|
+
}
|
|
72
|
+
) });
|
|
54
73
|
}
|
|
55
74
|
const MissingStoreDomainErrorMessage = 'You must pass a "storeDomain" prop to the "ShopPayButton" component, or wrap it in a "ShopifyProvider" component.';
|
|
56
75
|
const InvalidPropsErrorMessage = `You must pass in "variantIds" in the form of ["gid://shopify/ProductVariant/1"]`;
|
|
57
76
|
const MissingPropsErrorMessage = `You must pass in either "variantIds" or "variantIdsAndQuantities" to ShopPayButton`;
|
|
58
77
|
const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;
|
|
78
|
+
const InvalidChannelErrorMessage = `Invalid channel attribution value. Must be either "headless" or "hydrogen"`;
|
|
59
79
|
exports.DoublePropsErrorMessage = DoublePropsErrorMessage;
|
|
80
|
+
exports.InvalidChannelErrorMessage = InvalidChannelErrorMessage;
|
|
60
81
|
exports.InvalidPropsErrorMessage = InvalidPropsErrorMessage;
|
|
61
82
|
exports.MissingPropsErrorMessage = MissingPropsErrorMessage;
|
|
62
83
|
exports.MissingStoreDomainErrorMessage = MissingStoreDomainErrorMessage;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShopPayButton.js","sources":["../../src/ShopPayButton.tsx"],"sourcesContent":["import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button store-url={storeDomain}
|
|
1
|
+
{"version":3,"file":"ShopPayButton.js","sources":["../../src/ShopPayButton.tsx"],"sourcesContent":["import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n ShopPayChannelAttribution &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ntype ShopPayChannelAttribution = {\n /** A string that adds channel attribution to the order. Can be either `headless` or `hydrogen` */\n channel?: 'headless' | 'hydrogen';\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n channel?: string;\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\nfunction isChannel(\n channel: string,\n): channel is Exclude<ShopPayChannelAttribution['channel'], undefined> {\n return channel === 'headless' || channel === 'hydrogen';\n}\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n channel,\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n let channelAttribution: string | undefined;\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (channel) {\n if (isChannel(channel)) {\n channelAttribution = channel;\n } else {\n throw new Error(InvalidChannelErrorMessage);\n }\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button\n {...(channelAttribution ? {channel: channelAttribution} : {})}\n store-url={storeDomain}\n variants={ids.join(',')}\n />\n )}\n </div>\n );\n}\n\nexport const MissingStoreDomainErrorMessage =\n 'You must pass a \"storeDomain\" prop to the \"ShopPayButton\" component, or wrap it in a \"ShopifyProvider\" component.';\nexport const InvalidPropsErrorMessage = `You must pass in \"variantIds\" in the form of [\"gid://shopify/ProductVariant/1\"]`;\nexport const MissingPropsErrorMessage = `You must pass in either \"variantIds\" or \"variantIdsAndQuantities\" to ShopPayButton`;\nexport const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;\nexport const InvalidChannelErrorMessage = `Invalid channel attribution value. Must be either \"headless\" or \"hydrogen\"`;\n"],"names":["useShop","useLoadScript","defaultShopifyContext","parseGid","jsx"],"mappings":";;;;;;AAyDA,MAAM,aACJ;AAEF,SAAS,UACP,SACqE;AAC9D,SAAA,YAAY,cAAc,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AAM,QAAQ,QACT;AAAA,IACC,2BAA2B;AAAA,EAE7B,IAAA;AAEJ,SACGC,2BAAA,IAAA,OAAA,EAAI,WAAsB,OACxB,kCAAwB,UACvBA,2BAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACE,GAAI,qBAAqB,EAAC,SAAS,uBAAsB,CAAC;AAAA,MAC3D,aAAW;AAAA,MACX,UAAU,IAAI,KAAK,GAAG;AAAA,IAAA;AAAA,EAG5B,EAAA,CAAA;AAEJ;AAEO,MAAM,iCACX;AACK,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;AAChC,MAAM,6BAA6B;;;;;;;"}
|
|
@@ -3,7 +3,11 @@ import { useShop, defaultShopifyContext } from "./ShopifyProvider.mjs";
|
|
|
3
3
|
import { useLoadScript } from "./load-script.mjs";
|
|
4
4
|
import { parseGid } from "./analytics-utils.mjs";
|
|
5
5
|
const SHOPJS_URL = "https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js";
|
|
6
|
+
function isChannel(channel) {
|
|
7
|
+
return channel === "headless" || channel === "hydrogen";
|
|
8
|
+
}
|
|
6
9
|
function ShopPayButton({
|
|
10
|
+
channel,
|
|
7
11
|
variantIds,
|
|
8
12
|
className,
|
|
9
13
|
variantIdsAndQuantities,
|
|
@@ -14,6 +18,7 @@ function ShopPayButton({
|
|
|
14
18
|
const storeDomain = _storeDomain || (shop == null ? void 0 : shop.storeDomain);
|
|
15
19
|
const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);
|
|
16
20
|
let ids = [];
|
|
21
|
+
let channelAttribution;
|
|
17
22
|
if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {
|
|
18
23
|
throw new Error(MissingStoreDomainErrorMessage);
|
|
19
24
|
}
|
|
@@ -23,6 +28,13 @@ function ShopPayButton({
|
|
|
23
28
|
if (!variantIds && !variantIdsAndQuantities) {
|
|
24
29
|
throw new Error(MissingPropsErrorMessage);
|
|
25
30
|
}
|
|
31
|
+
if (channel) {
|
|
32
|
+
if (isChannel(channel)) {
|
|
33
|
+
channelAttribution = channel;
|
|
34
|
+
} else {
|
|
35
|
+
throw new Error(InvalidChannelErrorMessage);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
26
38
|
if (variantIds) {
|
|
27
39
|
ids = variantIds.reduce((prev, curr) => {
|
|
28
40
|
const bareId = parseGid(curr).id;
|
|
@@ -48,14 +60,23 @@ function ShopPayButton({
|
|
|
48
60
|
const style = width ? {
|
|
49
61
|
"--shop-pay-button-width": width
|
|
50
62
|
} : void 0;
|
|
51
|
-
return /* @__PURE__ */ jsx("div", { className, style, children: shopPayLoadedStatus === "done" && /* @__PURE__ */ jsx(
|
|
63
|
+
return /* @__PURE__ */ jsx("div", { className, style, children: shopPayLoadedStatus === "done" && /* @__PURE__ */ jsx(
|
|
64
|
+
"shop-pay-button",
|
|
65
|
+
{
|
|
66
|
+
...channelAttribution ? { channel: channelAttribution } : {},
|
|
67
|
+
"store-url": storeDomain,
|
|
68
|
+
variants: ids.join(",")
|
|
69
|
+
}
|
|
70
|
+
) });
|
|
52
71
|
}
|
|
53
72
|
const MissingStoreDomainErrorMessage = 'You must pass a "storeDomain" prop to the "ShopPayButton" component, or wrap it in a "ShopifyProvider" component.';
|
|
54
73
|
const InvalidPropsErrorMessage = `You must pass in "variantIds" in the form of ["gid://shopify/ProductVariant/1"]`;
|
|
55
74
|
const MissingPropsErrorMessage = `You must pass in either "variantIds" or "variantIdsAndQuantities" to ShopPayButton`;
|
|
56
75
|
const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;
|
|
76
|
+
const InvalidChannelErrorMessage = `Invalid channel attribution value. Must be either "headless" or "hydrogen"`;
|
|
57
77
|
export {
|
|
58
78
|
DoublePropsErrorMessage,
|
|
79
|
+
InvalidChannelErrorMessage,
|
|
59
80
|
InvalidPropsErrorMessage,
|
|
60
81
|
MissingPropsErrorMessage,
|
|
61
82
|
MissingStoreDomainErrorMessage,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShopPayButton.mjs","sources":["../../src/ShopPayButton.tsx"],"sourcesContent":["import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button store-url={storeDomain}
|
|
1
|
+
{"version":3,"file":"ShopPayButton.mjs","sources":["../../src/ShopPayButton.tsx"],"sourcesContent":["import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n ShopPayChannelAttribution &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ntype ShopPayChannelAttribution = {\n /** A string that adds channel attribution to the order. Can be either `headless` or `hydrogen` */\n channel?: 'headless' | 'hydrogen';\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n channel?: string;\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\nfunction isChannel(\n channel: string,\n): channel is Exclude<ShopPayChannelAttribution['channel'], undefined> {\n return channel === 'headless' || channel === 'hydrogen';\n}\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n channel,\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n let channelAttribution: string | undefined;\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (channel) {\n if (isChannel(channel)) {\n channelAttribution = channel;\n } else {\n throw new Error(InvalidChannelErrorMessage);\n }\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button\n {...(channelAttribution ? {channel: channelAttribution} : {})}\n store-url={storeDomain}\n variants={ids.join(',')}\n />\n )}\n </div>\n );\n}\n\nexport const MissingStoreDomainErrorMessage =\n 'You must pass a \"storeDomain\" prop to the \"ShopPayButton\" component, or wrap it in a \"ShopifyProvider\" component.';\nexport const InvalidPropsErrorMessage = `You must pass in \"variantIds\" in the form of [\"gid://shopify/ProductVariant/1\"]`;\nexport const MissingPropsErrorMessage = `You must pass in either \"variantIds\" or \"variantIdsAndQuantities\" to ShopPayButton`;\nexport const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;\nexport const InvalidChannelErrorMessage = `Invalid channel attribution value. Must be either \"headless\" or \"hydrogen\"`;\n"],"names":[],"mappings":";;;;AAyDA,MAAM,aACJ;AAEF,SAAS,UACP,SACqE;AAC9D,SAAA,YAAY,cAAc,YAAY;AAC/C;AAOO,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AACf,GAAoC;AAClC,QAAM,OAAO;AACP,QAAA,cAAc,iBAAgB,6BAAM;AACpC,QAAA,sBAAsB,cAAc,UAAU;AAEpD,MAAI,MAAgB,CAAA;AAChB,MAAA;AAEJ,MAAI,CAAC,eAAe,gBAAgB,sBAAsB,aAAa;AAC/D,UAAA,IAAI,MAAM,8BAA8B;AAAA,EAChD;AAEA,MAAI,cAAc,yBAAyB;AACnC,UAAA,IAAI,MAAM,uBAAuB;AAAA,EACzC;AAEI,MAAA,CAAC,cAAc,CAAC,yBAAyB;AACrC,UAAA,IAAI,MAAM,wBAAwB;AAAA,EAC1C;AAEA,MAAI,SAAS;AACP,QAAA,UAAU,OAAO,GAAG;AACD,2BAAA;AAAA,IAAA,OAChB;AACC,YAAA,IAAI,MAAM,0BAA0B;AAAA,IAC5C;AAAA,EACF;AAEA,MAAI,YAAY;AACd,UAAM,WAAW,OAAiB,CAAC,MAAM,SAAS;AAC1C,YAAA,SAAS,SAAS,IAAI,EAAE;AAC9B,UAAI,QAAQ;AACV,aAAK,KAAK,MAAM;AAAA,MAClB;AACO,aAAA;AAAA,IACT,GAAG,CAAE,CAAA;AAAA,aACI,yBAAyB;AAClC,UAAM,wBAAwB,OAAiB,CAAC,MAAM,SAAS;AAC7D,YAAM,SAAS,SAAS,6BAAM,EAAE,EAAE;AAClC,UAAI,QAAQ;AACV,aAAK,KAAK,GAAG,MAAM,KAAI,6BAAM,aAAY,CAAC,EAAE;AAAA,MAC9C;AACO,aAAA;AAAA,IACT,GAAG,CAAE,CAAA;AAAA,EAAA,OACA;AACC,UAAA,IAAI,MAAM,wBAAwB;AAAA,EAC1C;AAEI,MAAA,IAAI,WAAW,GAAG;AACd,UAAA,IAAI,MAAM,wBAAwB;AAAA,EAC1C;AAEA,QAAM,QAAQ,QACT;AAAA,IACC,2BAA2B;AAAA,EAE7B,IAAA;AAEJ,SACG,oBAAA,OAAA,EAAI,WAAsB,OACxB,kCAAwB,UACvB;AAAA,IAAC;AAAA,IAAA;AAAA,MACE,GAAI,qBAAqB,EAAC,SAAS,uBAAsB,CAAC;AAAA,MAC3D,aAAW;AAAA,MACX,UAAU,IAAI,KAAK,GAAG;AAAA,IAAA;AAAA,EAG5B,EAAA,CAAA;AAEJ;AAEO,MAAM,iCACX;AACK,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;AAChC,MAAM,6BAA6B;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const storefrontApiConstants = require("./storefront-api-constants.js");
|
|
4
|
+
const isMockShop = (domain) => domain.includes("mock.shop");
|
|
4
5
|
function createStorefrontClient(props) {
|
|
5
6
|
const {
|
|
6
7
|
storeDomain,
|
|
@@ -21,7 +22,7 @@ Received "${storeDomain}".`
|
|
|
21
22
|
You may run into unexpected errors if these versions don't match. Received verion: "${storefrontApiVersion}"; expected version "${storefrontApiConstants.SFAPI_VERSION}"`
|
|
22
23
|
);
|
|
23
24
|
}
|
|
24
|
-
if (!privateStorefrontToken && !globalThis.document) {
|
|
25
|
+
if (!privateStorefrontToken && !globalThis.document && !isMockShop(storeDomain)) {
|
|
25
26
|
warnOnce(
|
|
26
27
|
`Using a private storefront token is recommended for server environments.
|
|
27
28
|
Refer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`
|
|
@@ -32,7 +33,6 @@ Refer to the authentication https://shopify.dev/api/storefront#authentication do
|
|
|
32
33
|
"You are attempting to use a private token in an environment where it can be easily accessed by anyone.\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop"
|
|
33
34
|
);
|
|
34
35
|
}
|
|
35
|
-
const isMockShop = (domain) => domain.includes("mock.shop");
|
|
36
36
|
const getShopifyDomain = (overrideProps) => {
|
|
37
37
|
const domain = (overrideProps == null ? void 0 : overrideProps.storeDomain) ?? storeDomain;
|
|
38
38
|
return domain.includes("://") ? domain : `https://${domain}`;
|