@rechargeapps/storefront-client 2.9.0 → 2.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/api/auth.js +1 -1
- package/dist/cjs/api/auth.js.map +1 -1
- package/dist/cjs/api/bundleData.js +1 -1
- package/dist/cjs/api/bundleData.js.map +1 -1
- package/dist/cjs/utils/request.js +1 -1
- package/dist/cjs/utils/request.js.map +1 -1
- package/dist/esm/api/auth.js +1 -1
- package/dist/esm/api/auth.js.map +1 -1
- package/dist/esm/api/bundleData.js +1 -1
- package/dist/esm/api/bundleData.js.map +1 -1
- package/dist/esm/utils/request.js +1 -1
- package/dist/esm/utils/request.js.map +1 -1
- package/dist/index.d.ts +31 -2
- package/dist/umd/recharge-client.min.js +2 -2
- package/package.json +1 -1
package/dist/cjs/api/auth.js
CHANGED
|
@@ -199,7 +199,7 @@ async function rechargeAdminRequest(method, url, { id, query, data, headers } =
|
|
|
199
199
|
...storefrontAccessToken ? { "X-Recharge-Storefront-Access-Token": storefrontAccessToken } : {},
|
|
200
200
|
...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
|
|
201
201
|
...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
|
|
202
|
-
"X-Recharge-Sdk-Version": "2.
|
|
202
|
+
"X-Recharge-Sdk-Version": "2.10.0",
|
|
203
203
|
...headers ? headers : {}
|
|
204
204
|
};
|
|
205
205
|
return request.request(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });
|
package/dist/cjs/api/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\nimport {\n LoginResponse,\n Method,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n RequestOptions,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n if (!shopifyStorefrontToken) {\n throw new Error('Shopify storefront token is required');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_storefront_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_customer_account_api_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n // Only forward documented option keys. Spreading raw `options` after the\n // trusted `shop`/`email` fields would let a runtime caller override them or\n // inject undocumented authority fields (H1-3884986 / SEC-4002).\n const { send_email, send_sms } = options;\n const response = await rechargeAdminRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\n ...(send_email !== undefined ? { send_email } : {}),\n ...(send_sms !== undefined ? { send_sms } : {}),\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n // Only forward documented option keys (see sendPasswordlessCode above) so a\n // caller can't override `email` or inject undocumented fields (SEC-4002).\n const { send_email, send_sms } = options;\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...(send_email !== undefined ? { send_email } : {}),\n ...(send_sms !== undefined ? { send_sms } : {}),\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const response = await rechargeAdminRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getScrubbedPortalToken(customerHash: string | undefined): string | null {\n if (window.ReCharge?.token) return window.ReCharge.token;\n if (!customerHash) return null;\n try {\n return window.sessionStorage.getItem(`rc_cp_token:${customerHash}`);\n } catch {\n return null;\n }\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n // The portal can move the token out of the URL so third-party scripts reading `location` never see it\n const token = urlParams.get('token') || getScrubbedPortalToken(customerHash);\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<LoginResponse>(\n 'post',\n `/customers/${encodePathSegment(customerHash)}/access`,\n {\n data: {\n token,\n shop: storeIdentifier,\n },\n }\n );\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nasync function rechargeAdminRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const { environment, environmentUri, storefrontAccessToken, appName, appVersion } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n ...(storefrontAccessToken ? { 'X-Recharge-Storefront-Access-Token': storefrontAccessToken } : {}),\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(headers ? headers : {}),\n };\n\n return baseRequest<T>(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });\n}\n"],"names":["getOptions","shopifyAppProxyRequest","options","encodePathSegment","RECHARGE_ADMIN_URL","baseRequest"],"mappings":";;;;;;;AAeA,eAAsB,oBAAA,GAAyC;AAC7D,EAAA,MAAM,EAAE,qBAAA,EAAsB,GAAIA,kBAAA,EAAW;AAC7C,EAAA,MAAM,UAA0B,EAAC;AACjC,EAAA,IAAI,qBAAA,EAAuB;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAA,GAAI,qBAAA;AAAA,EAClD;AACA,EAAA,MAAM,WAAW,MAAMC,8BAAA,CAAsC,OAAO,SAAA,EAAW,EAAE,SAAS,CAAA;AAE1F,EAAA,OAAO,EAAE,UAAU,QAAA,CAAS,SAAA,EAAW,YAAY,QAAA,CAAS,WAAA,EAAa,OAAA,EAAS,QAAA,CAAS,OAAA,EAAQ;AACrG;AAGA,eAAsB,eAAA,CACpB,wBACA,0BAAA,EACyB;AACzB,EAAA,OAAO,0BAAA,CAA2B,wBAAwB,0BAA0B,CAAA;AACtF;AAEA,eAAsB,0BAAA,CACpB,wBACA,0BAAA,EACyB;AACzB,EAAA,IAAI,CAAC,sBAAA,EAAwB;AAC3B,IAAA,MAAM,IAAI,MAAM,sCAAsC,CAAA;AAAA,EACxD;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EAAI,OAAO,IAAA,EAAM,OAAA,EAAQ,GAAoB,EAAC,EACpC;AACZ,EAAA,MAAM,EAAE,WAAA,EAAa,cAAA,EAAgB,uBAAuB,OAAA,EAAS,UAAA,KAAeH,kBAAA,EAAW;AAC/F,EAAA,MAAM,eAAA,GAAkBI,sBAAA,CAAmB,WAAA,EAAa,cAAc,CAAA;AACtE,EAAA,MAAM,UAAA,GAA6B;AAAA,IACjC,GAAI,qBAAA,GAAwB,EAAE,oCAAA,EAAsC,qBAAA,KAA0B,EAAC;AAAA,IAC/F,GAAI,OAAA,GAAU,EAAE,yBAAA,EAA2B,OAAA,KAAY,EAAC;AAAA,IACxD,GAAI,UAAA,GAAa,EAAE,4BAAA,EAA8B,UAAA,KAAe,EAAC;AAAA,IACjE,wBAAA,EAA0B,OAAA;AAAA,IAC1B,GAAI,OAAA,GAAU,OAAA,GAAU;AAAC,GAC3B;AAEA,EAAA,OAAOC,eAAA,CAAe,MAAA,EAAQ,CAAA,EAAG,eAAe,CAAA,EAAG,GAAG,CAAA,CAAA,EAAI,EAAE,EAAA,EAAI,KAAA,EAAO,IAAA,EAAM,OAAA,EAAS,YAAY,CAAA;AACpG;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\nimport {\n LoginResponse,\n Method,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n RequestOptions,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n if (!shopifyStorefrontToken) {\n throw new Error('Shopify storefront token is required');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_storefront_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_customer_account_api_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n // Only forward documented option keys. Spreading raw `options` after the\n // trusted `shop`/`email` fields would let a runtime caller override them or\n // inject undocumented authority fields (H1-3884986 / SEC-4002).\n const { send_email, send_sms } = options;\n const response = await rechargeAdminRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\n ...(send_email !== undefined ? { send_email } : {}),\n ...(send_sms !== undefined ? { send_sms } : {}),\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n // Only forward documented option keys (see sendPasswordlessCode above) so a\n // caller can't override `email` or inject undocumented fields (SEC-4002).\n const { send_email, send_sms } = options;\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...(send_email !== undefined ? { send_email } : {}),\n ...(send_sms !== undefined ? { send_sms } : {}),\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const response = await rechargeAdminRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getScrubbedPortalToken(customerHash: string | undefined): string | null {\n if (window.ReCharge?.token) return window.ReCharge.token;\n if (!customerHash) return null;\n try {\n return window.sessionStorage.getItem(`rc_cp_token:${customerHash}`);\n } catch {\n return null;\n }\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n // The portal can move the token out of the URL so third-party scripts reading `location` never see it\n const token = urlParams.get('token') || getScrubbedPortalToken(customerHash);\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<LoginResponse>(\n 'post',\n `/customers/${encodePathSegment(customerHash)}/access`,\n {\n data: {\n token,\n shop: storeIdentifier,\n },\n }\n );\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nasync function rechargeAdminRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const { environment, environmentUri, storefrontAccessToken, appName, appVersion } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n ...(storefrontAccessToken ? { 'X-Recharge-Storefront-Access-Token': storefrontAccessToken } : {}),\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(headers ? headers : {}),\n };\n\n return baseRequest<T>(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });\n}\n"],"names":["getOptions","shopifyAppProxyRequest","options","encodePathSegment","RECHARGE_ADMIN_URL","baseRequest"],"mappings":";;;;;;;AAeA,eAAsB,oBAAA,GAAyC;AAC7D,EAAA,MAAM,EAAE,qBAAA,EAAsB,GAAIA,kBAAA,EAAW;AAC7C,EAAA,MAAM,UAA0B,EAAC;AACjC,EAAA,IAAI,qBAAA,EAAuB;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAA,GAAI,qBAAA;AAAA,EAClD;AACA,EAAA,MAAM,WAAW,MAAMC,8BAAA,CAAsC,OAAO,SAAA,EAAW,EAAE,SAAS,CAAA;AAE1F,EAAA,OAAO,EAAE,UAAU,QAAA,CAAS,SAAA,EAAW,YAAY,QAAA,CAAS,WAAA,EAAa,OAAA,EAAS,QAAA,CAAS,OAAA,EAAQ;AACrG;AAGA,eAAsB,eAAA,CACpB,wBACA,0BAAA,EACyB;AACzB,EAAA,OAAO,0BAAA,CAA2B,wBAAwB,0BAA0B,CAAA;AACtF;AAEA,eAAsB,0BAAA,CACpB,wBACA,0BAAA,EACyB;AACzB,EAAA,IAAI,CAAC,sBAAA,EAAwB;AAC3B,IAAA,MAAM,IAAI,MAAM,sCAAsC,CAAA;AAAA,EACxD;AACA,EAAA,MAAM,EAAE,eAAA,EAAgB,GAAID,kBAAA,EAAW;AACvC,EAAA,IAAI,CAAC,eAAA,EAAiB;AACpB,IAAA,MAAM,IAAI,MAAM,+EAA+E,CAAA;AAAA,EACjG;AACA,EAAA,MAAM;AAAA,IACJ,SAAA,EAAW,QAAA;AAAA,IACX,WAAA,EAAa,UAAA;AAAA,IACb;AAAA,GACF,GAAI,MAAM,oB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,IACjC,GAAI,qBAAA,GAAwB,EAAE,oCAAA,EAAsC,qBAAA,KAA0B,EAAC;AAAA,IAC/F,GAAI,OAAA,GAAU,EAAE,yBAAA,EAA2B,OAAA,KAAY,EAAC;AAAA,IACxD,GAAI,UAAA,GAAa,EAAE,4BAAA,EAA8B,UAAA,KAAe,EAAC;AAAA,IACjE,wBAAA,EAA0B,QAAA;AAAA,IAC1B,GAAI,OAAA,GAAU,OAAA,GAAU;AAAC,GAC3B;AAEA,EAAA,OAAOC,eAAA,CAAe,MAAA,EAAQ,CAAA,EAAG,eAAe,CAAA,EAAG,GAAG,CAAA,CAAA,EAAI,EAAE,EAAA,EAAI,KAAA,EAAO,IAAA,EAAM,OAAA,EAAS,YAAY,CAAA;AACpG;;;;;;;;;;"}
|
|
@@ -16,7 +16,7 @@ async function loadFromOnlineStore(id, country_code) {
|
|
|
16
16
|
const { appName, appVersion } = options.getOptions();
|
|
17
17
|
const headers = {
|
|
18
18
|
"X-Recharge-Sdk-Fn": "loadFromOnlineStore",
|
|
19
|
-
"X-Recharge-Sdk-Version": "2.
|
|
19
|
+
"X-Recharge-Sdk-Version": "2.10.0",
|
|
20
20
|
...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
|
|
21
21
|
...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {}
|
|
22
22
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleData.js","sources":["../../../src/api/bundleData.ts"],"sourcesContent":["import { Options, PublicBundleData, ShopifyStorefrontOptions } from '../types/bundleData';\nimport { getOptions } from '../utils/options';\nimport { SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { BundleData as StorefrontBundleData } from '../types/bundle';\nimport { request, shopifyAppProxyRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\nimport { mapOnlineStoreToPublicBundleData } from '../utils/bundleData';\n\n/**\n * Load bundle data from the specified source\n *\n * @param id - The external product ID (Shopify product ID)\n * @param options - Configuration for data source and parameters\n * @param options.source - The source of the data (online_store or shopify_storefront)\n * @param options.country_code - The country code for the online store\n * @param options.storefront_access_token - The storefront access token for the Shopify Storefront API\n * @returns Promise resolving to bundle data result with success/error handling\n *\n * @example\n * ```typescript\n * // Load from online store\n * const result = await loadBundleData({\n * source: 'online_store',\n * external_product_id: '123456789',\n * country_code: 'US'\n * });\n *\n * if (result.success) {\n * console.log('Bundle data:', result.data);\n * } else {\n * console.error('Error:', result.error.message);\n * }\n *\n * // Load from Shopify Storefront API\n * const result2 = await loadBundleData({\n * source: 'shopify_storefront',\n * external_product_id: '123456789',\n * country_code: 'US',\n * shopify_storefront_access_token: 'your-token-here'\n * });\n * ```\n */\nexport async function loadBundleData(id: string, options?: Options): Promise<PublicBundleData> {\n if (options?.source === 'shopify_storefront') {\n return loadFromShopifyStorefrontApi(id, options);\n }\n\n return loadFromOnlineStore(id, options?.country_code);\n}\n\n/**\n * Load bundle data from the online store endpoint\n */\nasync function loadFromOnlineStore(id: string, country_code?: string): Promise<PublicBundleData> {\n const { appName, appVersion } = getOptions();\n const headers = {\n 'X-Recharge-Sdk-Fn': 'loadFromOnlineStore',\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n };\n\n if (!country_code) {\n const data = await shopifyAppProxyRequest<StorefrontBundleData>('get', `/bundle-data/${encodePathSegment(id)}`, {\n headers,\n });\n return mapOnlineStoreToPublicBundleData(data);\n }\n\n const payload = new FormData();\n payload.append('form_type', 'localization');\n payload.append('_method', 'put');\n payload.append('return_to', `${SHOPIFY_APP_PROXY_URL}/bundle-data/${id}`);\n payload.append('country_code', country_code);\n\n try {\n const data = await request<StorefrontBundleData>('post', '/localization', {\n headers: { 'Content-Type': 'multipart/form-data', ...headers },\n data: payload,\n });\n return mapOnlineStoreToPublicBundleData(data);\n } catch (error) {\n const data = await shopifyAppProxyRequest<StorefrontBundleData>('get', `/bundle-data/${encodePathSegment(id)}`, {\n headers,\n });\n return mapOnlineStoreToPublicBundleData(data);\n }\n}\n\n/**\n * Load bundle data from Shopify Storefront API\n */\nasync function loadFromShopifyStorefrontApi(id: string, options: ShopifyStorefrontOptions): Promise<PublicBundleData> {\n const opts = getOptions();\n\n if (!opts.storeIdentifier) {\n throw new Error('Store identifier is required for Shopify Storefront API requests');\n }\n\n // Request data from Shopify Storefront API\n return {} as PublicBundleData;\n}\n"],"names":["getOptions","shopifyAppProxyRequest","encodePathSegment","mapOnlineStoreToPublicBundleData","SHOPIFY_APP_PROXY_URL","request","options"],"mappings":";;;;;;;;AA0CA,eAAsB,cAAA,CAAe,IAAY,OAAA,EAA8C;AAC7F,EAAA,IAAI,OAAA,EAAS,WAAW,oBAAA,EAAsB;AAC5C,IAAA,OAAO,4BAAA,CAAwC,CAAA;AAAA,EACjD;AAEA,EAAA,OAAO,mBAAA,CAAoB,EAAA,EAAI,OAAA,EAAS,YAAY,CAAA;AACtD;AAKA,eAAe,mBAAA,CAAoB,IAAY,YAAA,EAAkD;AAC/F,EAAA,MAAM,EAAE,OAAA,EAAS,UAAA,EAAW,GAAIA,kBAAA,EAAW;AAC3C,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,mBAAA,EAAqB,qBAAA;AAAA,IACrB,wBAAA,EAA0B,
|
|
1
|
+
{"version":3,"file":"bundleData.js","sources":["../../../src/api/bundleData.ts"],"sourcesContent":["import { Options, PublicBundleData, ShopifyStorefrontOptions } from '../types/bundleData';\nimport { getOptions } from '../utils/options';\nimport { SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { BundleData as StorefrontBundleData } from '../types/bundle';\nimport { request, shopifyAppProxyRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\nimport { mapOnlineStoreToPublicBundleData } from '../utils/bundleData';\n\n/**\n * Load bundle data from the specified source\n *\n * @param id - The external product ID (Shopify product ID)\n * @param options - Configuration for data source and parameters\n * @param options.source - The source of the data (online_store or shopify_storefront)\n * @param options.country_code - The country code for the online store\n * @param options.storefront_access_token - The storefront access token for the Shopify Storefront API\n * @returns Promise resolving to bundle data result with success/error handling\n *\n * @example\n * ```typescript\n * // Load from online store\n * const result = await loadBundleData({\n * source: 'online_store',\n * external_product_id: '123456789',\n * country_code: 'US'\n * });\n *\n * if (result.success) {\n * console.log('Bundle data:', result.data);\n * } else {\n * console.error('Error:', result.error.message);\n * }\n *\n * // Load from Shopify Storefront API\n * const result2 = await loadBundleData({\n * source: 'shopify_storefront',\n * external_product_id: '123456789',\n * country_code: 'US',\n * shopify_storefront_access_token: 'your-token-here'\n * });\n * ```\n */\nexport async function loadBundleData(id: string, options?: Options): Promise<PublicBundleData> {\n if (options?.source === 'shopify_storefront') {\n return loadFromShopifyStorefrontApi(id, options);\n }\n\n return loadFromOnlineStore(id, options?.country_code);\n}\n\n/**\n * Load bundle data from the online store endpoint\n */\nasync function loadFromOnlineStore(id: string, country_code?: string): Promise<PublicBundleData> {\n const { appName, appVersion } = getOptions();\n const headers = {\n 'X-Recharge-Sdk-Fn': 'loadFromOnlineStore',\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n };\n\n if (!country_code) {\n const data = await shopifyAppProxyRequest<StorefrontBundleData>('get', `/bundle-data/${encodePathSegment(id)}`, {\n headers,\n });\n return mapOnlineStoreToPublicBundleData(data);\n }\n\n const payload = new FormData();\n payload.append('form_type', 'localization');\n payload.append('_method', 'put');\n payload.append('return_to', `${SHOPIFY_APP_PROXY_URL}/bundle-data/${id}`);\n payload.append('country_code', country_code);\n\n try {\n const data = await request<StorefrontBundleData>('post', '/localization', {\n headers: { 'Content-Type': 'multipart/form-data', ...headers },\n data: payload,\n });\n return mapOnlineStoreToPublicBundleData(data);\n } catch (error) {\n const data = await shopifyAppProxyRequest<StorefrontBundleData>('get', `/bundle-data/${encodePathSegment(id)}`, {\n headers,\n });\n return mapOnlineStoreToPublicBundleData(data);\n }\n}\n\n/**\n * Load bundle data from Shopify Storefront API\n */\nasync function loadFromShopifyStorefrontApi(id: string, options: ShopifyStorefrontOptions): Promise<PublicBundleData> {\n const opts = getOptions();\n\n if (!opts.storeIdentifier) {\n throw new Error('Store identifier is required for Shopify Storefront API requests');\n }\n\n // Request data from Shopify Storefront API\n return {} as PublicBundleData;\n}\n"],"names":["getOptions","shopifyAppProxyRequest","encodePathSegment","mapOnlineStoreToPublicBundleData","SHOPIFY_APP_PROXY_URL","request","options"],"mappings":";;;;;;;;AA0CA,eAAsB,cAAA,CAAe,IAAY,OAAA,EAA8C;AAC7F,EAAA,IAAI,OAAA,EAAS,WAAW,oBAAA,EAAsB;AAC5C,IAAA,OAAO,4BAAA,CAAwC,CAAA;AAAA,EACjD;AAEA,EAAA,OAAO,mBAAA,CAAoB,EAAA,EAAI,OAAA,EAAS,YAAY,CAAA;AACtD;AAKA,eAAe,mBAAA,CAAoB,IAAY,YAAA,EAAkD;AAC/F,EAAA,MAAM,EAAE,OAAA,EAAS,UAAA,EAAW,GAAIA,kBAAA,EAAW;AAC3C,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,mBAAA,EAAqB,qBAAA;AAAA,IACrB,wBAAA,EAA0B,QAAA;AAAA,IAC1B,GAAI,OAAA,GAAU,EAAE,yBAAA,EAA2B,OAAA,KAAY,EAAC;AAAA,IACxD,GAAI,UAAA,GAAa,EAAE,4BAAA,EAA8B,UAAA,KAAe;AAAC,GACnE;AAEA,EAAA,IAAI,CAAC,YAAA,EAAc;AACjB,IAAA,MAAM,IAAA,GAAO,MAAMC,8BAAA,CAA6C,KAAA,EAAO,gBAAgBC,qBAAA,CAAkB,EAAE,CAAC,CAAA,CAAA,EAAI;AAAA,MAC9G;AAAA,KACD,CAAA;AACD,IAAA,OAAOC,4CAAiC,IAAI,CAAA;AAAA,EAC9C;AAEA,EAAA,MAAM,OAAA,GAAU,IAAI,QAAA,EAAS;AAC7B,EAAA,OAAA,CAAQ,MAAA,CAAO,aAAa,cAAc,CAAA;AAC1C,EAAA,OAAA,CAAQ,MAAA,CAAO,WAAW,KAAK,CAAA;AAC/B,EAAA,OAAA,CAAQ,OAAO,WAAA,EAAa,CAAA,EAAGC,yBAAqB,CAAA,aAAA,EAAgB,EAAE,CAAA,CAAE,CAAA;AACxE,EAAA,OAAA,CAAQ,MAAA,CAAO,gBAAgB,YAAY,CAAA;AAE3C,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,MAAMC,eAAA,CAA8B,MAAA,EAAQ,eAAA,EAAiB;AAAA,MACxE,OAAA,EAAS,EAAE,cAAA,EAAgB,qBAAA,EAAuB,GAAG,OAAA,EAAQ;AAAA,MAC7D,IAAA,EAAM;AAAA,KACP,CAAA;AACD,IAAA,OAAOF,4CAAiC,IAAI,CAAA;AAAA,EAC9C,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAA,GAAO,MAAMF,8BAAA,CAA6C,KAAA,EAAO,gBAAgBC,qBAAA,CAAkB,EAAE,CAAC,CAAA,CAAA,EAAI;AAAA,MAC9G;AAAA,KACD,CAAA;AACD,IAAA,OAAOC,4CAAiC,IAAI,CAAA;AAAA,EAC9C;AACF;AAKA,eAAe,4BAAA,CAA6B,IAAYG,SAAA,EAA8D;AACpH,EAAA,MAAM,OAAON,kBAAA,EAAW;AAExB,EAAA,IAAI,CAAC,KAAK,eAAA,EAAiB;AACzB,IAAA,MAAM,IAAI,MAAM,kEAAkE,CAAA;AAAA,EACpF;AAGA,EAAA,OAAO,EAAC;AACV;;"}
|
|
@@ -72,7 +72,7 @@ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}
|
|
|
72
72
|
"X-Recharge-Sdk-Fn": session.internalFnCall,
|
|
73
73
|
...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
|
|
74
74
|
...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
|
|
75
|
-
"X-Recharge-Sdk-Version": "2.
|
|
75
|
+
"X-Recharge-Sdk-Version": "2.10.0",
|
|
76
76
|
"X-Request-Id": session.internalRequestId,
|
|
77
77
|
...session.tmp_fn_identifier ? { "X-Recharge-Sdk-Fn-Identifier": session.tmp_fn_identifier } : {},
|
|
78
78
|
...headers ? headers : {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import { nanoid } from './id';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\nimport { encodePathSegment } from './url';\n\n/**\n * Converts a query object into a URL-encoded query string using the following rules:\n * - Arrays are serialized as comma-separated values: `a=1,2` (not `a[0]=1&a[1]=2`)\n * - Only the values are URL-encoded; keys are not encoded\n * - Properties with `undefined` values or empty arrays are omitted from the result\n *\n * Reference: qs\n */\nfunction stringifyQuery(obj: Record<string, unknown>): string {\n const encode = (value: unknown) => encodeURIComponent(value === null ? '' : String(value));\n return Object.entries(obj)\n .filter(([, value]) => value !== undefined && !(Array.isArray(value) && value.length === 0))\n .map(([key, value]) => `${key}=${Array.isArray(value) ? value.map(encode).join(',') : encode(value)}`)\n .join('&');\n}\n\nconst RESERVED_QUERY_KEYS = new Set(['shop_url']);\n\ntype SessionRetryFn = () => Promise<Session | undefined>;\n\ninterface SessionRetryState {\n inFlight?: Promise<Session | undefined>;\n latest?: { session: Session; generation: number };\n}\n\nconst sessionRetryStates = new WeakMap<SessionRetryFn, SessionRetryState>();\nlet sessionRetryGeneration = 0;\n\nfunction getSessionRetryState(retryFn: SessionRetryFn): SessionRetryState {\n let state = sessionRetryStates.get(retryFn);\n if (!state) {\n state = {};\n sessionRetryStates.set(retryFn, state);\n }\n return state;\n}\n\n/**\n * Gets a fresh session for a failed request. Concurrent failures share one `retryFn` call. A request sent before an\n * earlier call returned a new session retries with that session instead of calling `retryFn` again; a request sent\n * after it always calls `retryFn`, so the app still decides (for example, after the customer logs out).\n */\nfunction getRetrySession(\n retryFn: SessionRetryFn,\n failedToken: string,\n sentAtGeneration: number\n): Promise<Session | undefined> {\n const state = getSessionRetryState(retryFn);\n if (state.inFlight) return state.inFlight;\n if (state.latest && state.latest.generation > sentAtGeneration) return Promise.resolve(state.latest.session);\n\n state.inFlight = retryFn()\n .then(session => {\n if (session && session.apiToken !== failedToken) {\n sessionRetryGeneration += 1;\n state.latest = { session, generation: sessionRetryGeneration };\n }\n return session;\n })\n .finally(() => {\n state.inFlight = undefined;\n });\n return state.inFlight;\n}\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const {\n environment,\n environmentUri,\n storeIdentifier,\n loginRetryFn,\n __unstable_twoFactorRetryFn,\n appName,\n appVersion,\n } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const token = session.apiToken;\n if (!token) {\n throw new Error('No API token defined on session.');\n }\n const sentAtGeneration = sessionRetryGeneration;\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Sdk-Fn': session.internalFnCall,\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n 'X-Request-Id': session.internalRequestId,\n ...(session.tmp_fn_identifier ? { 'X-Recharge-Sdk-Fn-Identifier': session.tmp_fn_identifier } : {}),\n ...(headers ? headers : {}),\n };\n\n const callerQuery = query as Record<string, unknown> | undefined;\n const sanitizedCallerQuery = callerQuery\n ? Object.fromEntries(Object.entries(callerQuery).filter(([k]) => !RESERVED_QUERY_KEYS.has(k)))\n : undefined;\n\n const localQuery = {\n ...sanitizedCallerQuery,\n shop_url: storeIdentifier,\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n const retryFnsByStatus: Partial<Record<number, SessionRetryFn>> = {\n 401: loginRetryFn,\n 423: __unstable_twoFactorRetryFn,\n };\n const retryFn = error instanceof RechargeRequestError && error.status ? retryFnsByStatus[error.status] : undefined;\n if (!retryFn) throw error;\n\n const retrySession = await getRetrySession(retryFn, token, sentAtGeneration);\n if (!retrySession) throw error;\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': retrySession.apiToken,\n },\n });\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n // Encode the id as a single opaque path segment. Without this, an id\n // containing `../` or `?` could traverse to a different API route or\n // smuggle query params (H1-3884884 / SEC-4002).\n reqUrl = [reqUrl, encodePathSegment(id)].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query as Record<string, unknown>)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (response.status === 502 || response.status === 504) {\n throw new RechargeRequestError('A gateway error occurred while making the request', response.status);\n } else if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":["nanoid","getOptions","RECHARGE_CDN_URL","RECHARGE_API_URL","error","RechargeRequestError","SHOPIFY_APP_PROXY_URL","url","encodePathSegment"],"mappings":";;;;;;;;AAgBA,SAAS,eAAe,GAAA,EAAsC;AAC5D,EAAA,MAAM,MAAA,GAAS,CAAC,KAAA,KAAmB,kBAAA,CAAmB,UAAU,IAAA,GAAO,EAAA,GAAK,MAAA,CAAO,KAAK,CAAC,CAAA;AACzF,EAAA,OAAO,MAAA,CAAO,QAAQ,GAAG,CAAA,CACtB,OAAO,CAAC,GAAG,KAAK,CAAA,KAAM,UAAU,MAAA,IAAa,EAAE,MAAM,OAAA,CAAQ,KAAK,KAAK,KAAA,CAAM,MAAA,KAAW,CAAA,CAAE,CAAA,CAC1F,GAAA,CAAI,CAAC,CAAC,GAAA,EAAK,KAAK,MAAM,CAAA,EAAG,GAAG,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,GAAI,KAAA,CAAM,GAAA,CAAI,MAAM,CAAA,CAAE,IAAA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CAAA;AAAA,IAC/E,CAAA,MAAO;AACL,MAAA,MAAM,IAAIA,2BAAqB,sDAAsD,CAAA;AAAA,IACvF;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;;;;;;"}
|
|
1
|
+
{"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import { nanoid } from './id';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\nimport { encodePathSegment } from './url';\n\n/**\n * Converts a query object into a URL-encoded query string using the following rules:\n * - Arrays are serialized as comma-separated values: `a=1,2` (not `a[0]=1&a[1]=2`)\n * - Only the values are URL-encoded; keys are not encoded\n * - Properties with `undefined` values or empty arrays are omitted from the result\n *\n * Reference: qs\n */\nfunction stringifyQuery(obj: Record<string, unknown>): string {\n const encode = (value: unknown) => encodeURIComponent(value === null ? '' : String(value));\n return Object.entries(obj)\n .filter(([, value]) => value !== undefined && !(Array.isArray(value) && value.length === 0))\n .map(([key, value]) => `${key}=${Array.isArray(value) ? value.map(encode).join(',') : encode(value)}`)\n .join('&');\n}\n\nconst RESERVED_QUERY_KEYS = new Set(['shop_url']);\n\ntype SessionRetryFn = () => Promise<Session | undefined>;\n\ninterface SessionRetryState {\n inFlight?: Promise<Session | undefined>;\n latest?: { session: Session; generation: number };\n}\n\nconst sessionRetryStates = new WeakMap<SessionRetryFn, SessionRetryState>();\nlet sessionRetryGeneration = 0;\n\nfunction getSessionRetryState(retryFn: SessionRetryFn): SessionRetryState {\n let state = sessionRetryStates.get(retryFn);\n if (!state) {\n state = {};\n sessionRetryStates.set(retryFn, state);\n }\n return state;\n}\n\n/**\n * Gets a fresh session for a failed request. Concurrent failures share one `retryFn` call. A request sent before an\n * earlier call returned a new session retries with that session instead of calling `retryFn` again; a request sent\n * after it always calls `retryFn`, so the app still decides (for example, after the customer logs out).\n */\nfunction getRetrySession(\n retryFn: SessionRetryFn,\n failedToken: string,\n sentAtGeneration: number\n): Promise<Session | undefined> {\n const state = getSessionRetryState(retryFn);\n if (state.inFlight) return state.inFlight;\n if (state.latest && state.latest.generation > sentAtGeneration) return Promise.resolve(state.latest.session);\n\n state.inFlight = retryFn()\n .then(session => {\n if (session && session.apiToken !== failedToken) {\n sessionRetryGeneration += 1;\n state.latest = { session, generation: sessionRetryGeneration };\n }\n return session;\n })\n .finally(() => {\n state.inFlight = undefined;\n });\n return state.inFlight;\n}\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const {\n environment,\n environmentUri,\n storeIdentifier,\n loginRetryFn,\n __unstable_twoFactorRetryFn,\n appName,\n appVersion,\n } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const token = session.apiToken;\n if (!token) {\n throw new Error('No API token defined on session.');\n }\n const sentAtGeneration = sessionRetryGeneration;\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Sdk-Fn': session.internalFnCall,\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n 'X-Request-Id': session.internalRequestId,\n ...(session.tmp_fn_identifier ? { 'X-Recharge-Sdk-Fn-Identifier': session.tmp_fn_identifier } : {}),\n ...(headers ? headers : {}),\n };\n\n const callerQuery = query as Record<string, unknown> | undefined;\n const sanitizedCallerQuery = callerQuery\n ? Object.fromEntries(Object.entries(callerQuery).filter(([k]) => !RESERVED_QUERY_KEYS.has(k)))\n : undefined;\n\n const localQuery = {\n ...sanitizedCallerQuery,\n shop_url: storeIdentifier,\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n const retryFnsByStatus: Partial<Record<number, SessionRetryFn>> = {\n 401: loginRetryFn,\n 423: __unstable_twoFactorRetryFn,\n };\n const retryFn = error instanceof RechargeRequestError && error.status ? retryFnsByStatus[error.status] : undefined;\n if (!retryFn) throw error;\n\n const retrySession = await getRetrySession(retryFn, token, sentAtGeneration);\n if (!retrySession) throw error;\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': retrySession.apiToken,\n },\n });\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n // Encode the id as a single opaque path segment. Without this, an id\n // containing `../` or `?` could traverse to a different API route or\n // smuggle query params (H1-3884884 / SEC-4002).\n reqUrl = [reqUrl, encodePathSegment(id)].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query as Record<string, unknown>)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (response.status === 502 || response.status === 504) {\n throw new RechargeRequestError('A gateway error occurred while making the request', response.status);\n } else if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":["nanoid","getOptions","RECHARGE_CDN_URL","RECHARGE_API_URL","error","RechargeRequestError","SHOPIFY_APP_PROXY_URL","url","encodePathSegment"],"mappings":";;;;;;;;AAgBA,SAAS,eAAe,GAAA,EAAsC;AAC5D,EAAA,MAAM,MAAA,GAAS,CAAC,KAAA,KAAmB,kBAAA,CAAmB,UAAU,IAAA,GAAO,EAAA,GAAK,MAAA,CAAO,KAAK,CAAC,CAAA;AACzF,EAAA,OAAO,MAAA,CAAO,QAAQ,GAAG,CAAA,CACtB,OAAO,CAAC,GAAG,KAAK,CAAA,KAAM,UAAU,MAAA,IAAa,EAAE,MAAM,OAAA,CAAQ,KAAK,KAAK,KAAA,CAAM,MAAA,KAAW,CAAA,CAAE,CAAA,CAC1F,GAAA,CAAI,CAAC,CAAC,GAAA,EAAK,KAAK,MAAM,CAAA,EAAG,GAAG,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,GAAI,KAAA,CAAM,GAAA,CAAI,MAAM,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA,GAAI,MAAA,CAAO,KAAK,CAAC,CAAA,CAAE,CAAA,CACpG,IAAA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AAAA,IACvF;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;;;;;;"}
|
package/dist/esm/api/auth.js
CHANGED
|
@@ -197,7 +197,7 @@ async function rechargeAdminRequest(method, url, { id, query, data, headers } =
|
|
|
197
197
|
...storefrontAccessToken ? { "X-Recharge-Storefront-Access-Token": storefrontAccessToken } : {},
|
|
198
198
|
...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
|
|
199
199
|
...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
|
|
200
|
-
"X-Recharge-Sdk-Version": "2.
|
|
200
|
+
"X-Recharge-Sdk-Version": "2.10.0",
|
|
201
201
|
...headers ? headers : {}
|
|
202
202
|
};
|
|
203
203
|
return request(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });
|
package/dist/esm/api/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\nimport {\n LoginResponse,\n Method,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n RequestOptions,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n if (!shopifyStorefrontToken) {\n throw new Error('Shopify storefront token is required');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_storefront_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_customer_account_api_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n // Only forward documented option keys. Spreading raw `options` after the\n // trusted `shop`/`email` fields would let a runtime caller override them or\n // inject undocumented authority fields (H1-3884986 / SEC-4002).\n const { send_email, send_sms } = options;\n const response = await rechargeAdminRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\n ...(send_email !== undefined ? { send_email } : {}),\n ...(send_sms !== undefined ? { send_sms } : {}),\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n // Only forward documented option keys (see sendPasswordlessCode above) so a\n // caller can't override `email` or inject undocumented fields (SEC-4002).\n const { send_email, send_sms } = options;\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...(send_email !== undefined ? { send_email } : {}),\n ...(send_sms !== undefined ? { send_sms } : {}),\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const response = await rechargeAdminRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getScrubbedPortalToken(customerHash: string | undefined): string | null {\n if (window.ReCharge?.token) return window.ReCharge.token;\n if (!customerHash) return null;\n try {\n return window.sessionStorage.getItem(`rc_cp_token:${customerHash}`);\n } catch {\n return null;\n }\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n // The portal can move the token out of the URL so third-party scripts reading `location` never see it\n const token = urlParams.get('token') || getScrubbedPortalToken(customerHash);\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<LoginResponse>(\n 'post',\n `/customers/${encodePathSegment(customerHash)}/access`,\n {\n data: {\n token,\n shop: storeIdentifier,\n },\n }\n );\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nasync function rechargeAdminRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const { environment, environmentUri, storefrontAccessToken, appName, appVersion } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n ...(storefrontAccessToken ? { 'X-Recharge-Storefront-Access-Token': storefrontAccessToken } : {}),\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(headers ? headers : {}),\n };\n\n return baseRequest<T>(method, `${rechargeBaseUrl}${url}`, { id, query, data, head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AAAC,GAC3B;AAEA,EAAA,OAAOA,OAAA,CAAe,MAAA,EAAQ,CAAA,EAAG,eAAe,CAAA,EAAG,GAAG,CAAA,CAAA,EAAI,EAAE,EAAA,EAAI,KAAA,EAAO,IAAA,EAAM,OAAA,EAAS,YAAY,CAAA;AACpG;;"}
|
|
1
|
+
{"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\nimport {\n LoginResponse,\n Method,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n RequestOptions,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n if (!shopifyStorefrontToken) {\n throw new Error('Shopify storefront token is required');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_storefront_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_customer_account_api_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n // Only forward documented option keys. Spreading raw `options` after the\n // trusted `shop`/`email` fields would let a runtime caller override them or\n // inject undocumented authority fields (H1-3884986 / SEC-4002).\n const { send_email, send_sms } = options;\n const response = await rechargeAdminRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\n ...(send_email !== undefined ? { send_email } : {}),\n ...(send_sms !== undefined ? { send_sms } : {}),\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n // Only forward documented option keys (see sendPasswordlessCode above) so a\n // caller can't override `email` or inject undocumented fields (SEC-4002).\n const { send_email, send_sms } = options;\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...(send_email !== undefined ? { send_email } : {}),\n ...(send_sms !== undefined ? { send_sms } : {}),\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const response = await rechargeAdminRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getScrubbedPortalToken(customerHash: string | undefined): string | null {\n if (window.ReCharge?.token) return window.ReCharge.token;\n if (!customerHash) return null;\n try {\n return window.sessionStorage.getItem(`rc_cp_token:${customerHash}`);\n } catch {\n return null;\n }\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n // The portal can move the token out of the URL so third-party scripts reading `location` never see it\n const token = urlParams.get('token') || getScrubbedPortalToken(customerHash);\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<LoginResponse>(\n 'post',\n `/customers/${encodePathSegment(customerHash)}/access`,\n {\n data: {\n token,\n shop: storeIdentifier,\n },\n }\n );\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nasync function rechargeAdminRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const { environment, environmentUri, storefrontAccessToken, appName, appVersion } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n ...(storefrontAccessToken ? { 'X-Recharge-Storefront-Access-Token': storefrontAccessToken } : {}),\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(headers ? headers : {}),\n };\n\n return baseRequest<T>(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });\n}\n"],"names":["baseRequest"],"mappings":";;;;;AAeA,eAAsB,oBAAA,GAAyC;AAC7D,EAAA,MAAM,EAAE,qBAAA,EAAsB,GAAI,UAAA,EAAW;AAC7C,EAAA,MAAM,UAA0B,EAAC;AACjC,EAAA,IAAI,qBAAA,EAAuB;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAA,GAAI,qBAAA;AAAA,EAClD;AACA,EAAA,MAAM,WAAW,MAAM,sBAAA,CAAsC,OAAO,SAAA,EAAW,EAAE,SAAS,CAAA;AAE1F,EAAA,OAAO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B,MAAA;AAAA,IACA,CAAA,WAAA,EAAc,iBAAA,CAAkB,YAAY,CAAC,CAAA,OAAA,CAAA;AAAA,IAC7C;AAAA,MACE,IAAA,EAAM;AAAA,QACJ,KAAA;AAAA,QACA,IAAA,EAAM;AAAA;AACR;AACF,GACF;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,QAAA,CAAS,SAAA,EAAW,UAAA,EAAY,SAAS,WAAA,EAAY;AAC1E;AAEA,eAAe,oBAAA,CACb,MAAA,EACA,GAAA,EACA,EAAE,EAAA,EAAI,OAAO,IAAA,EAAM,OAAA,EAAQ,GAAoB,EAAC,EACpC;AACZ,EAAA,MAAM,EAAE,WAAA,EAAa,cAAA,EAAgB,uBAAuB,OAAA,EAAS,UAAA,KAAe,UAAA,EAAW;AAC/F,EAAA,MAAM,eAAA,GAAkB,kBAAA,CAAmB,WAAA,EAAa,cAAc,CAAA;AACtE,EAAA,MAAM,UAAA,GAA6B;AAAA,IACjC,GAAI,qBAAA,GAAwB,EAAE,oCAAA,EAAsC,qBAAA,KAA0B,EAAC;AAAA,IAC/F,GAAI,OAAA,GAAU,EAAE,yBAAA,EAA2B,OAAA,KAAY,EAAC;AAAA,IACxD,GAAI,UAAA,GAAa,EAAE,4BAAA,EAA8B,UAAA,KAAe,EAAC;AAAA,IACjE,wBAAA,EAA0B,QAAA;AAAA,IAC1B,GAAI,OAAA,GAAU,OAAA,GAAU;AAAC,GAC3B;AAEA,EAAA,OAAOA,OAAA,CAAe,MAAA,EAAQ,CAAA,EAAG,eAAe,CAAA,EAAG,GAAG,CAAA,CAAA,EAAI,EAAE,EAAA,EAAI,KAAA,EAAO,IAAA,EAAM,OAAA,EAAS,YAAY,CAAA;AACpG;;"}
|
|
@@ -14,7 +14,7 @@ async function loadFromOnlineStore(id, country_code) {
|
|
|
14
14
|
const { appName, appVersion } = getOptions();
|
|
15
15
|
const headers = {
|
|
16
16
|
"X-Recharge-Sdk-Fn": "loadFromOnlineStore",
|
|
17
|
-
"X-Recharge-Sdk-Version": "2.
|
|
17
|
+
"X-Recharge-Sdk-Version": "2.10.0",
|
|
18
18
|
...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
|
|
19
19
|
...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {}
|
|
20
20
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleData.js","sources":["../../../src/api/bundleData.ts"],"sourcesContent":["import { Options, PublicBundleData, ShopifyStorefrontOptions } from '../types/bundleData';\nimport { getOptions } from '../utils/options';\nimport { SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { BundleData as StorefrontBundleData } from '../types/bundle';\nimport { request, shopifyAppProxyRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\nimport { mapOnlineStoreToPublicBundleData } from '../utils/bundleData';\n\n/**\n * Load bundle data from the specified source\n *\n * @param id - The external product ID (Shopify product ID)\n * @param options - Configuration for data source and parameters\n * @param options.source - The source of the data (online_store or shopify_storefront)\n * @param options.country_code - The country code for the online store\n * @param options.storefront_access_token - The storefront access token for the Shopify Storefront API\n * @returns Promise resolving to bundle data result with success/error handling\n *\n * @example\n * ```typescript\n * // Load from online store\n * const result = await loadBundleData({\n * source: 'online_store',\n * external_product_id: '123456789',\n * country_code: 'US'\n * });\n *\n * if (result.success) {\n * console.log('Bundle data:', result.data);\n * } else {\n * console.error('Error:', result.error.message);\n * }\n *\n * // Load from Shopify Storefront API\n * const result2 = await loadBundleData({\n * source: 'shopify_storefront',\n * external_product_id: '123456789',\n * country_code: 'US',\n * shopify_storefront_access_token: 'your-token-here'\n * });\n * ```\n */\nexport async function loadBundleData(id: string, options?: Options): Promise<PublicBundleData> {\n if (options?.source === 'shopify_storefront') {\n return loadFromShopifyStorefrontApi(id, options);\n }\n\n return loadFromOnlineStore(id, options?.country_code);\n}\n\n/**\n * Load bundle data from the online store endpoint\n */\nasync function loadFromOnlineStore(id: string, country_code?: string): Promise<PublicBundleData> {\n const { appName, appVersion } = getOptions();\n const headers = {\n 'X-Recharge-Sdk-Fn': 'loadFromOnlineStore',\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n };\n\n if (!country_code) {\n const data = await shopifyAppProxyRequest<StorefrontBundleData>('get', `/bundle-data/${encodePathSegment(id)}`, {\n headers,\n });\n return mapOnlineStoreToPublicBundleData(data);\n }\n\n const payload = new FormData();\n payload.append('form_type', 'localization');\n payload.append('_method', 'put');\n payload.append('return_to', `${SHOPIFY_APP_PROXY_URL}/bundle-data/${id}`);\n payload.append('country_code', country_code);\n\n try {\n const data = await request<StorefrontBundleData>('post', '/localization', {\n headers: { 'Content-Type': 'multipart/form-data', ...headers },\n data: payload,\n });\n return mapOnlineStoreToPublicBundleData(data);\n } catch (error) {\n const data = await shopifyAppProxyRequest<StorefrontBundleData>('get', `/bundle-data/${encodePathSegment(id)}`, {\n headers,\n });\n return mapOnlineStoreToPublicBundleData(data);\n }\n}\n\n/**\n * Load bundle data from Shopify Storefront API\n */\nasync function loadFromShopifyStorefrontApi(id: string, options: ShopifyStorefrontOptions): Promise<PublicBundleData> {\n const opts = getOptions();\n\n if (!opts.storeIdentifier) {\n throw new Error('Store identifier is required for Shopify Storefront API requests');\n }\n\n // Request data from Shopify Storefront API\n return {} as PublicBundleData;\n}\n"],"names":[],"mappings":";;;;;;AA0CA,eAAsB,cAAA,CAAe,IAAY,OAAA,EAA8C;AAC7F,EAAA,IAAI,OAAA,EAAS,WAAW,oBAAA,EAAsB;AAC5C,IAAA,OAAO,4BAAA,CAAwC,CAAA;AAAA,EACjD;AAEA,EAAA,OAAO,mBAAA,CAAoB,EAAA,EAAI,OAAA,EAAS,YAAY,CAAA;AACtD;AAKA,eAAe,mBAAA,CAAoB,IAAY,YAAA,EAAkD;AAC/F,EAAA,MAAM,EAAE,OAAA,EAAS,UAAA,EAAW,GAAI,UAAA,EAAW;AAC3C,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,mBAAA,EAAqB,qBAAA;AAAA,IACrB,wBAAA,EAA0B,
|
|
1
|
+
{"version":3,"file":"bundleData.js","sources":["../../../src/api/bundleData.ts"],"sourcesContent":["import { Options, PublicBundleData, ShopifyStorefrontOptions } from '../types/bundleData';\nimport { getOptions } from '../utils/options';\nimport { SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { BundleData as StorefrontBundleData } from '../types/bundle';\nimport { request, shopifyAppProxyRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\nimport { mapOnlineStoreToPublicBundleData } from '../utils/bundleData';\n\n/**\n * Load bundle data from the specified source\n *\n * @param id - The external product ID (Shopify product ID)\n * @param options - Configuration for data source and parameters\n * @param options.source - The source of the data (online_store or shopify_storefront)\n * @param options.country_code - The country code for the online store\n * @param options.storefront_access_token - The storefront access token for the Shopify Storefront API\n * @returns Promise resolving to bundle data result with success/error handling\n *\n * @example\n * ```typescript\n * // Load from online store\n * const result = await loadBundleData({\n * source: 'online_store',\n * external_product_id: '123456789',\n * country_code: 'US'\n * });\n *\n * if (result.success) {\n * console.log('Bundle data:', result.data);\n * } else {\n * console.error('Error:', result.error.message);\n * }\n *\n * // Load from Shopify Storefront API\n * const result2 = await loadBundleData({\n * source: 'shopify_storefront',\n * external_product_id: '123456789',\n * country_code: 'US',\n * shopify_storefront_access_token: 'your-token-here'\n * });\n * ```\n */\nexport async function loadBundleData(id: string, options?: Options): Promise<PublicBundleData> {\n if (options?.source === 'shopify_storefront') {\n return loadFromShopifyStorefrontApi(id, options);\n }\n\n return loadFromOnlineStore(id, options?.country_code);\n}\n\n/**\n * Load bundle data from the online store endpoint\n */\nasync function loadFromOnlineStore(id: string, country_code?: string): Promise<PublicBundleData> {\n const { appName, appVersion } = getOptions();\n const headers = {\n 'X-Recharge-Sdk-Fn': 'loadFromOnlineStore',\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n };\n\n if (!country_code) {\n const data = await shopifyAppProxyRequest<StorefrontBundleData>('get', `/bundle-data/${encodePathSegment(id)}`, {\n headers,\n });\n return mapOnlineStoreToPublicBundleData(data);\n }\n\n const payload = new FormData();\n payload.append('form_type', 'localization');\n payload.append('_method', 'put');\n payload.append('return_to', `${SHOPIFY_APP_PROXY_URL}/bundle-data/${id}`);\n payload.append('country_code', country_code);\n\n try {\n const data = await request<StorefrontBundleData>('post', '/localization', {\n headers: { 'Content-Type': 'multipart/form-data', ...headers },\n data: payload,\n });\n return mapOnlineStoreToPublicBundleData(data);\n } catch (error) {\n const data = await shopifyAppProxyRequest<StorefrontBundleData>('get', `/bundle-data/${encodePathSegment(id)}`, {\n headers,\n });\n return mapOnlineStoreToPublicBundleData(data);\n }\n}\n\n/**\n * Load bundle data from Shopify Storefront API\n */\nasync function loadFromShopifyStorefrontApi(id: string, options: ShopifyStorefrontOptions): Promise<PublicBundleData> {\n const opts = getOptions();\n\n if (!opts.storeIdentifier) {\n throw new Error('Store identifier is required for Shopify Storefront API requests');\n }\n\n // Request data from Shopify Storefront API\n return {} as PublicBundleData;\n}\n"],"names":[],"mappings":";;;;;;AA0CA,eAAsB,cAAA,CAAe,IAAY,OAAA,EAA8C;AAC7F,EAAA,IAAI,OAAA,EAAS,WAAW,oBAAA,EAAsB;AAC5C,IAAA,OAAO,4BAAA,CAAwC,CAAA;AAAA,EACjD;AAEA,EAAA,OAAO,mBAAA,CAAoB,EAAA,EAAI,OAAA,EAAS,YAAY,CAAA;AACtD;AAKA,eAAe,mBAAA,CAAoB,IAAY,YAAA,EAAkD;AAC/F,EAAA,MAAM,EAAE,OAAA,EAAS,UAAA,EAAW,GAAI,UAAA,EAAW;AAC3C,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,mBAAA,EAAqB,qBAAA;AAAA,IACrB,wBAAA,EAA0B,QAAA;AA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H,EAAA,MAAM,OAAO,UAAA,EAAW;AAExB,EAAA,IAAI,CAAC,KAAK,eAAA,EAAiB;AACzB,IAAA,MAAM,IAAI,MAAM,kEAAkE,CAAA;AAAA,EACpF;AAGA,EAAA,OAAO,EAAC;AACV;;"}
|
|
@@ -70,7 +70,7 @@ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}
|
|
|
70
70
|
"X-Recharge-Sdk-Fn": session.internalFnCall,
|
|
71
71
|
...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
|
|
72
72
|
...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
|
|
73
|
-
"X-Recharge-Sdk-Version": "2.
|
|
73
|
+
"X-Recharge-Sdk-Version": "2.10.0",
|
|
74
74
|
"X-Request-Id": session.internalRequestId,
|
|
75
75
|
...session.tmp_fn_identifier ? { "X-Recharge-Sdk-Fn-Identifier": session.tmp_fn_identifier } : {},
|
|
76
76
|
...headers ? headers : {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import { nanoid } from './id';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\nimport { encodePathSegment } from './url';\n\n/**\n * Converts a query object into a URL-encoded query string using the following rules:\n * - Arrays are serialized as comma-separated values: `a=1,2` (not `a[0]=1&a[1]=2`)\n * - Only the values are URL-encoded; keys are not encoded\n * - Properties with `undefined` values or empty arrays are omitted from the result\n *\n * Reference: qs\n */\nfunction stringifyQuery(obj: Record<string, unknown>): string {\n const encode = (value: unknown) => encodeURIComponent(value === null ? '' : String(value));\n return Object.entries(obj)\n .filter(([, value]) => value !== undefined && !(Array.isArray(value) && value.length === 0))\n .map(([key, value]) => `${key}=${Array.isArray(value) ? value.map(encode).join(',') : encode(value)}`)\n .join('&');\n}\n\nconst RESERVED_QUERY_KEYS = new Set(['shop_url']);\n\ntype SessionRetryFn = () => Promise<Session | undefined>;\n\ninterface SessionRetryState {\n inFlight?: Promise<Session | undefined>;\n latest?: { session: Session; generation: number };\n}\n\nconst sessionRetryStates = new WeakMap<SessionRetryFn, SessionRetryState>();\nlet sessionRetryGeneration = 0;\n\nfunction getSessionRetryState(retryFn: SessionRetryFn): SessionRetryState {\n let state = sessionRetryStates.get(retryFn);\n if (!state) {\n state = {};\n sessionRetryStates.set(retryFn, state);\n }\n return state;\n}\n\n/**\n * Gets a fresh session for a failed request. Concurrent failures share one `retryFn` call. A request sent before an\n * earlier call returned a new session retries with that session instead of calling `retryFn` again; a request sent\n * after it always calls `retryFn`, so the app still decides (for example, after the customer logs out).\n */\nfunction getRetrySession(\n retryFn: SessionRetryFn,\n failedToken: string,\n sentAtGeneration: number\n): Promise<Session | undefined> {\n const state = getSessionRetryState(retryFn);\n if (state.inFlight) return state.inFlight;\n if (state.latest && state.latest.generation > sentAtGeneration) return Promise.resolve(state.latest.session);\n\n state.inFlight = retryFn()\n .then(session => {\n if (session && session.apiToken !== failedToken) {\n sessionRetryGeneration += 1;\n state.latest = { session, generation: sessionRetryGeneration };\n }\n return session;\n })\n .finally(() => {\n state.inFlight = undefined;\n });\n return state.inFlight;\n}\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const {\n environment,\n environmentUri,\n storeIdentifier,\n loginRetryFn,\n __unstable_twoFactorRetryFn,\n appName,\n appVersion,\n } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const token = session.apiToken;\n if (!token) {\n throw new Error('No API token defined on session.');\n }\n const sentAtGeneration = sessionRetryGeneration;\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Sdk-Fn': session.internalFnCall,\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n 'X-Request-Id': session.internalRequestId,\n ...(session.tmp_fn_identifier ? { 'X-Recharge-Sdk-Fn-Identifier': session.tmp_fn_identifier } : {}),\n ...(headers ? headers : {}),\n };\n\n const callerQuery = query as Record<string, unknown> | undefined;\n const sanitizedCallerQuery = callerQuery\n ? Object.fromEntries(Object.entries(callerQuery).filter(([k]) => !RESERVED_QUERY_KEYS.has(k)))\n : undefined;\n\n const localQuery = {\n ...sanitizedCallerQuery,\n shop_url: storeIdentifier,\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n const retryFnsByStatus: Partial<Record<number, SessionRetryFn>> = {\n 401: loginRetryFn,\n 423: __unstable_twoFactorRetryFn,\n };\n const retryFn = error instanceof RechargeRequestError && error.status ? retryFnsByStatus[error.status] : undefined;\n if (!retryFn) throw error;\n\n const retrySession = await getRetrySession(retryFn, token, sentAtGeneration);\n if (!retrySession) throw error;\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': retrySession.apiToken,\n },\n });\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n // Encode the id as a single opaque path segment. Without this, an id\n // containing `../` or `?` could traverse to a different API route or\n // smuggle query params (H1-3884884 / SEC-4002).\n reqUrl = [reqUrl, encodePathSegment(id)].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query as Record<string, unknown>)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (response.status === 502 || response.status === 504) {\n throw new RechargeRequestError('A gateway error occurred while making the request', response.status);\n } else if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":[],"mappings":";;;;;;AAgBA,SAAS,eAAe,GAAA,EAAsC;AAC5D,EAAA,MAAM,MAAA,GAAS,CAAC,KAAA,KAAmB,kBAAA,CAAmB,UAAU,IAAA,GAAO,EAAA,GAAK,MAAA,CAAO,KAAK,CAAC,CAAA;AACzF,EAAA,OAAO,MAAA,CAAO,QAAQ,GAAG,CAAA,CACtB,O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AW,MAAA,IAAU,MAAA,CAAO,KAAA,EAAO;AACjC,MAAA,MAAM,IAAI,oBAAA,CAAqB,MAAA,CAAO,KAAA,EAAO,SAAS,MAAM,CAAA;AAAA,IAC9D,CAAA,MAAA,IAAW,MAAA,IAAU,MAAA,CAAO,MAAA,EAAQ;AAClC,MAAA,MAAM,IAAI,qBAAqB,IAAA,CAAK,SAAA,CAAU,OAAO,MAAM,CAAA,EAAG,SAAS,MAAM,CAAA;AAAA,IAC/E,CAAA,MAAO;AACL,MAAA,MAAM,IAAI,qBAAqB,sDAAsD,CAAA;AAAA,IACvF;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;;"}
|
|
1
|
+
{"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import { nanoid } from './id';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\nimport { encodePathSegment } from './url';\n\n/**\n * Converts a query object into a URL-encoded query string using the following rules:\n * - Arrays are serialized as comma-separated values: `a=1,2` (not `a[0]=1&a[1]=2`)\n * - Only the values are URL-encoded; keys are not encoded\n * - Properties with `undefined` values or empty arrays are omitted from the result\n *\n * Reference: qs\n */\nfunction stringifyQuery(obj: Record<string, unknown>): string {\n const encode = (value: unknown) => encodeURIComponent(value === null ? '' : String(value));\n return Object.entries(obj)\n .filter(([, value]) => value !== undefined && !(Array.isArray(value) && value.length === 0))\n .map(([key, value]) => `${key}=${Array.isArray(value) ? value.map(encode).join(',') : encode(value)}`)\n .join('&');\n}\n\nconst RESERVED_QUERY_KEYS = new Set(['shop_url']);\n\ntype SessionRetryFn = () => Promise<Session | undefined>;\n\ninterface SessionRetryState {\n inFlight?: Promise<Session | undefined>;\n latest?: { session: Session; generation: number };\n}\n\nconst sessionRetryStates = new WeakMap<SessionRetryFn, SessionRetryState>();\nlet sessionRetryGeneration = 0;\n\nfunction getSessionRetryState(retryFn: SessionRetryFn): SessionRetryState {\n let state = sessionRetryStates.get(retryFn);\n if (!state) {\n state = {};\n sessionRetryStates.set(retryFn, state);\n }\n return state;\n}\n\n/**\n * Gets a fresh session for a failed request. Concurrent failures share one `retryFn` call. A request sent before an\n * earlier call returned a new session retries with that session instead of calling `retryFn` again; a request sent\n * after it always calls `retryFn`, so the app still decides (for example, after the customer logs out).\n */\nfunction getRetrySession(\n retryFn: SessionRetryFn,\n failedToken: string,\n sentAtGeneration: number\n): Promise<Session | undefined> {\n const state = getSessionRetryState(retryFn);\n if (state.inFlight) return state.inFlight;\n if (state.latest && state.latest.generation > sentAtGeneration) return Promise.resolve(state.latest.session);\n\n state.inFlight = retryFn()\n .then(session => {\n if (session && session.apiToken !== failedToken) {\n sessionRetryGeneration += 1;\n state.latest = { session, generation: sessionRetryGeneration };\n }\n return session;\n })\n .finally(() => {\n state.inFlight = undefined;\n });\n return state.inFlight;\n}\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const {\n environment,\n environmentUri,\n storeIdentifier,\n loginRetryFn,\n __unstable_twoFactorRetryFn,\n appName,\n appVersion,\n } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const token = session.apiToken;\n if (!token) {\n throw new Error('No API token defined on session.');\n }\n const sentAtGeneration = sessionRetryGeneration;\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Sdk-Fn': session.internalFnCall,\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n 'X-Request-Id': session.internalRequestId,\n ...(session.tmp_fn_identifier ? { 'X-Recharge-Sdk-Fn-Identifier': session.tmp_fn_identifier } : {}),\n ...(headers ? headers : {}),\n };\n\n const callerQuery = query as Record<string, unknown> | undefined;\n const sanitizedCallerQuery = callerQuery\n ? Object.fromEntries(Object.entries(callerQuery).filter(([k]) => !RESERVED_QUERY_KEYS.has(k)))\n : undefined;\n\n const localQuery = {\n ...sanitizedCallerQuery,\n shop_url: storeIdentifier,\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n const retryFnsByStatus: Partial<Record<number, SessionRetryFn>> = {\n 401: loginRetryFn,\n 423: __unstable_twoFactorRetryFn,\n };\n const retryFn = error instanceof RechargeRequestError && error.status ? retryFnsByStatus[error.status] : undefined;\n if (!retryFn) throw error;\n\n const retrySession = await getRetrySession(retryFn, token, sentAtGeneration);\n if (!retrySession) throw error;\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': retrySession.apiToken,\n },\n });\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n // Encode the id as a single opaque path segment. Without this, an id\n // containing `../` or `?` could traverse to a different API route or\n // smuggle query params (H1-3884884 / SEC-4002).\n reqUrl = [reqUrl, encodePathSegment(id)].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query as Record<string, unknown>)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (response.status === 502 || response.status === 504) {\n throw new RechargeRequestError('A gateway error occurred while making the request', response.status);\n } else if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":[],"mappings":";;;;;;AAgBA,SAAS,eAAe,GAAA,EAAsC;AAC5D,EAAA,MAAM,MAAA,GAAS,CAAC,KAAA,KAAmB,kBAAA,CAAmB,UAAU,IAAA,GAAO,EAAA,GAAK,MAAA,CAAO,KAAK,CAAC,CAAA;AACzF,EAAA,OAAO,MAAA,CAAO,QAAQ,GAAG,CAAA,CACtB,OAAO,CAAC,GAAG,KAAK,CAAA,KAAM,UAAU,MAAA,IAAa,EAAE,MAAM,OAAA,CAAQ,KAAK,KAAK,KAAA,CAAM,MAAA,KAAW,CAAA,CAAE,CAAA,CAC1F,GAAA,CAAI,CAAC,CAAC,GAAA,EAAK,KAAK,MAAM,CAAA,EAAG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A,MAAM,IAAI,qBAAqB,IAAA,CAAK,SAAA,CAAU,OAAO,MAAM,CAAA,EAAG,SAAS,MAAM,CAAA;AAAA,IAC/E,CAAA,MAAO;AACL,MAAA,MAAM,IAAI,qBAAqB,sDAAsD,CAAA;AAAA,IACvF;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -2220,6 +2220,8 @@ interface Charge {
|
|
|
2220
2220
|
metafields?: Metafield[];
|
|
2221
2221
|
payment_methods?: PaymentMethod[];
|
|
2222
2222
|
subscriptions?: Subscription[];
|
|
2223
|
+
/** Null when the projection could not be built, which is not the same as a projection of zero. */
|
|
2224
|
+
credit_projection?: CreditProjection | null;
|
|
2223
2225
|
};
|
|
2224
2226
|
/** Error reason as sentence text (typically returned direct from the payment processor). e.g. "error": "Customer needs to update credit card" */
|
|
2225
2227
|
error?: string | null;
|
|
@@ -2232,6 +2234,31 @@ interface Charge {
|
|
|
2232
2234
|
/** The date when the next attempt will be placed. */
|
|
2233
2235
|
retry_date?: IsoDateString | null;
|
|
2234
2236
|
}
|
|
2237
|
+
type ExcludableCreditAccountType = 'manual' | 'reward' | 'referral';
|
|
2238
|
+
/** Credit a credit type could not spend on the Charge because the store excluded some of its products. */
|
|
2239
|
+
interface BlockedByExclusion {
|
|
2240
|
+
/** How much more this credit type would have applied had the store excluded no products. */
|
|
2241
|
+
amount: string;
|
|
2242
|
+
/** External (platform) product IDs on the Charge that this credit type cannot spend on. */
|
|
2243
|
+
excluded_product_ids: string[];
|
|
2244
|
+
}
|
|
2245
|
+
/** What a queued Charge would redeem in credits if it processed now, in the Charge's presentment currency. */
|
|
2246
|
+
interface CreditProjection {
|
|
2247
|
+
/** The code of the currency of the projected amounts, such as USD. */
|
|
2248
|
+
currency_code: string;
|
|
2249
|
+
/** Gift credit the Charge will redeem. */
|
|
2250
|
+
gift_to_apply: string;
|
|
2251
|
+
/** Non-gift credit the Charge will redeem. */
|
|
2252
|
+
non_gift_to_apply: string;
|
|
2253
|
+
/** Total credit the Charge will redeem if nothing changes. */
|
|
2254
|
+
total_to_apply: string;
|
|
2255
|
+
/** Like `total_to_apply`, but as if the customer applied credit to their next recurring charge. */
|
|
2256
|
+
total_to_apply_if_opted_in: string;
|
|
2257
|
+
/** Whether the max redemption limit would hold back non-gift credit if the customer opted in. Goes with `total_to_apply_if_opted_in`. */
|
|
2258
|
+
capped_by_redemption_limit: boolean;
|
|
2259
|
+
/** How much each credit type lost to the store's product exclusions. */
|
|
2260
|
+
blocked_by_exclusion: Record<ExcludableCreditAccountType, BlockedByExclusion>;
|
|
2261
|
+
}
|
|
2235
2262
|
interface ChargeResponse {
|
|
2236
2263
|
charge: Charge;
|
|
2237
2264
|
}
|
|
@@ -2241,8 +2268,10 @@ interface ChargeListResponse {
|
|
|
2241
2268
|
charges: Charge[];
|
|
2242
2269
|
}
|
|
2243
2270
|
type ChargeIncludes = 'address' | 'bundle_selections' | 'customer' | 'metafields' | 'payment_methods' | 'charge_activities' | 'subscriptions';
|
|
2271
|
+
/** `credit_projection` is only served when reading a single Charge. */
|
|
2272
|
+
type GetChargeIncludes = ChargeIncludes | 'credit_projection';
|
|
2244
2273
|
interface GetChargeOptions {
|
|
2245
|
-
include?:
|
|
2274
|
+
include?: GetChargeIncludes[];
|
|
2246
2275
|
}
|
|
2247
2276
|
type ChargeSortBy = 'id-asc' | 'id-desc' | 'updated_at-asc' | 'updated_at-desc' | 'scheduled_at-asc' | 'scheduled_at-desc';
|
|
2248
2277
|
interface ChargeListParams extends ListParams<ChargeSortBy> {
|
|
@@ -4481,4 +4510,4 @@ declare const api: {
|
|
|
4481
4510
|
declare function initRecharge(opt?: InitOptions): void;
|
|
4482
4511
|
|
|
4483
4512
|
export { activateMembership, activateSubscription, api, applyDiscountToAddress, applyDiscountToCharge, cancelMembership, cancelSubscription, changeMembership, claimOfferCustomerSurvey, createAddress, createBundleSelection, createMetafield, createOnetime, createPaymentMethod, createSubscription, createSubscriptions, delayOrder, deleteAddress, deleteBundleSelection, deleteMetafield, deleteOnetime, deleteSubscriptions, getActiveChurnLandingPageURL, getAddress, getBundleId, getBundleSelection, getBundleSelectionId, getCDNBundleSettings, getCDNProduct, getCDNProductAndSettings, getCDNProducts, getCDNProductsAndSettings, getCDNStoreSettings, getCDNWidgetSettings, getCharge, getCollection, getCreditSummary, getCustomer, getCustomerPortalAccess, getCustomerSurveyOffers, getCustomerSurveyReasons, getDeliverySchedule, getDynamicBundleItems, getFailedPaymentMethodRecoveryLandingPageURL, getGiftPurchase, getGiftRedemptionLandingPageURL, getMembership, getMembershipProgram, getOnetime, getOrder, getPaymentMethod, getPlan, getShippingCountries, getStoreSettings, getSubscription, getSubscriptionPricingPreview, getTieredDiscount, getTieredDiscountOffers, initFrictionlessPaymentV1, initRecharge, listAddresses, listBundleSelections, listCharges, listCollectionProducts, listCollections, listCreditAccounts, listGiftPurchases, listMembershipPrograms, listMemberships, listOnetimes, listOrders, listPaymentMethods, listPlans, listSubscriptionAddons, listSubscriptions, listTieredDiscounts, loadBundleData, loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, mergeAddresses, processCharge, productSearch, removeDiscountsFromAddress, removeDiscountsFromCharge, rescheduleCharge, resetCDNCache, sendCustomerNotification, sendPasswordlessCode, sendPasswordlessCodeAppProxy, setApplyCreditsToNextCharge, skipCharge, skipFutureCharge, skipGiftSubscriptionCharge, skipSubscriptionCharge, triggerCustomerPortalFlow, unskipCharge, updateAddress, updateBundle, updateBundleSelection, updateCustomer, updateMetafield, updateOnetime, updatePaymentMethod, updateSubscription, updateSubscriptionAddress, updateSubscriptionChargeDate, updateSubscriptions, validateBundle, validateBundleSelection, validateDynamicBundle, validatePasswordlessCode, validatePasswordlessCodeAppProxy };
|
|
4484
|
-
export type { ActivateMembershipRequest, AddToCartCallbackSettings, Addon, AddonProduct, AddonSettings, AddonType, AddonsSection, Address, AddressIncludes, AddressListParams, AddressListResponse, AddressResponse, AddressSortBy, AnalyticsData, Announcement, ApplyCreditOptions, AssociatedAddress, BaseCardDetails, BaseProduct, BaseProductVariant, BaseVariant, BasicSubscriptionParams, BooleanLike, BooleanNumbers, BooleanString, BooleanStringNumbers, BulkSubscriptionParams, BundleAppProxy, BundleData, BundleDataBaseProduct, BundleDataCollection, BundleDataSellingPlan, BundleDataSellingPlanGroup, BundleDataVariant, BundleFilterGroup, BundlePriceRule, BundleProduct, BundleProductGlobalStyles, BundleProductLayoutSettings, BundlePurchaseItem, BundlePurchaseItemParams, BundleSelection, BundleSelectionAppProxy, BundleSelectionItem, BundleSelectionItemRequiredCreateProps, BundleSelectionListParams, BundleSelectionsResponse, BundleSelectionsSortBy, BundleSettings, BundleTemplateSettings, BundleTemplateType, BundleTranslations, BundleVariant, BundleVariantOptionSource, BundleVariantOptionSourceBase, BundleVariantOptionSourceSubscription, BundleVariantRange, BundleVariantSelectionDefault, CDNBaseWidgetSettings, CDNBundleSettings, CDNBundleVariant, CDNBundleVariantOptionSource, CDNPlan, CDNProduct, CDNProductAndSettings, CDNProductKeyObject, CDNProductQuery_2020_12, CDNProductQuery_2022_06, CDNProductRaw, CDNProductResource, CDNProductResponseType, CDNProductType, CDNProductVariant_2022_06, CDNProduct_2022_06, CDNProductsAndSettings, CDNProductsAndSettingsResource, CDNStoreSettings, CDNSubscriptionOption, CDNVariant, CDNVersion, CDNWidgetSettings, CDNWidgetSettingsRaw, CDNWidgetSettingsResource, CRUDRequestOptions, CancelMembershipRequest, CancelSubscriptionRequest, CardDetailsFirstNameLastName, CardDetailsFullName, ChangeMembershipRequest, ChannelSettings, Charge, ChargeIncludes, ChargeListParams, ChargeListResponse, ChargeResponse, ChargeSortBy, ChargeStatus, Collection, CollectionBinding, CollectionListParams, CollectionTypes, CollectionsResponse, CollectionsSortBy, ColorString, CreateAddressRequest, CreateBundleSelectionRequest, CreateMetafieldRequest, CreateOnetimeRequest, CreatePaymentMethodRequest, CreateRecipientAddress, CreateSubscriptionRequest, CreateSubscriptionsParams, CreateSubscriptionsRequest, CreditAccount, CreditAccountIncludes, CreditAccountListParams, CreditAccountType, CreditAccountsResponse, CreditAccountsSortBy, CreditSummaryIncludes, CrossSellsSection, CrossSellsSettings, CurrencyPriceSet, Customer, CustomerCreditSummary, CustomerDeliveryScheduleParams, CustomerDeliveryScheduleResponse, CustomerIncludeGiftPurchase, CustomerIncludes, CustomerNotification, CustomerNotificationOptions, CustomerNotificationTemplate, CustomerNotificationType, CustomerPortalAccessOptions, CustomerPortalAccessResponse, CustomerPortalFlowAction, CustomerPortalSettings, CustomerSurveyOfferParams, CustomerSurveyOfferResponse, CustomerSurveyOffersResponse, CustomerSurveyReason, CustomerSurveyReasonsResponse, DefaultProduct, DefaultSelection, DefaultVariant, DelayOption, DeleteSubscriptionsParams, DeleteSubscriptionsRequest, Delivery, DeliveryLineItem, DeliveryOrder, DeliveryPaymentMethod, Discount, DiscountApplicationMethod, DiscountType, DynamicBundleItemAppProxy, DynamicBundlePropertiesAppProxy, DynamicPricingPreviewDetails, EligibleChargeType, EligibleLineItemType, ExternalAttributeSchema, ExternalId, ExternalProductStatus, ExternalTransactionId, FilterInputType, FilterMatchMode, FilterSource, FirstOption, GetAddressOptions, GetChargeOptions, GetCreditSummaryOptions, GetCustomerOptions, GetMembershipProgramOptions, GetOrderOptions, GetPaymentMethodOptions, GetRequestOptions, GetSubscriptionOptions, GiftPurchase, GiftPurchasesParams, GiftPurchasesResponse, HTMLString, Incentives, InitOptions, InternalSession, IntervalUnit, InventoryPolicy, IsoDateString, LineItem, ListParams, LoginResponse, Membership, MembershipBenefit, MembershipIncludes, MembershipListParams, MembershipListResponse, MembershipProgram, MembershipProgramIncludes, MembershipProgramListParams, MembershipProgramListResponse, MembershipProgramResponse, MembershipProgramSortBy, MembershipProgramStatus, MembershipResponse, MembershipStatus, MembershipsSortBy, MergeAddressesRequest, Metafield, MetafieldOptionalCreateProps, MetafieldOwnerResource, MetafieldRequiredCreateProps, Method, Modifier, MultiStepSettings, OfferAttributes, OnePageSettings, Onetime, OnetimeIncludes, OnetimeListParams, OnetimeOptionalCreateProps, OnetimeRequiredCreateProps, OnetimeSubscription, OnetimesResponse, OnetimesSortBy, OnlineStoreOptions, Options, Order, OrderIncludes, OrderListParams, OrderSortBy, OrderStatus, OrderType, OrdersResponse, PasswordlessCodeResponse, PasswordlessOptions, PasswordlessValidateResponse, PaymentDetails, PaymentErrorCallback, PaymentFieldEventCallback, PaymentFormConfig, PaymentFormController, PaymentFormEventHandlers, PaymentMethod, PaymentMethodFormOptions, PaymentMethodIncludes, PaymentMethodListParams, PaymentMethodOptionalCreateProps, PaymentMethodRequiredCreateProps, PaymentMethodSortBy, PaymentMethodStatus, PaymentMethodTokenCallback, PaymentMethodsResponse, PaymentType, Plan, PlanAddonSettings, PlanListParams, PlanSortBy, PlanType, PlansResponse, PriceRange, PriceRule, PriceSet, PricingProgressionResetTrigger, ProcessorName, Product, ProductImage, ProductInclude, ProductListResponse, ProductOption, ProductSearchParams_2020_12, ProductSearchParams_2022_06, ProductSearchResponse_2020_12, ProductSearchResponse_2022_06, ProductSearchType, ProductSource, ProductValueOption, ProductVariant_2020_12, ProductVariant_2022_06, Product_2020_12, Product_2022_06, Property, PublicBundleData, PublishStatus, PunchCardProgress, PunchCardProgressData, QuantityRange, RecurringSubscription, ReferralInfo, ReferralUrl, Request, RequestHeaders, RequestOptions, SellingPlan, SellingPlanAllocation, SellingPlanGroup, Session, ShippingCountriesOptions, ShippingCountriesResponse, ShippingCountry, ShippingLine, ShippingProvince, ShopifyStorefrontOptions, ShopifyUpdatePaymentInfoOptions, SkipChargeParams, SkipFutureChargeAddressRequest, SkipFutureChargeAddressResponse, SortBy, SortField, SortKeys, StepSettings, StepSettingsCommon, StepSettingsTypes, StoreSettings, StorefrontEnvironment, StorefrontOptions, StorefrontPurchaseOption, SubType, Subscription, SubscriptionBase, SubscriptionCancelled, SubscriptionIncludes, SubscriptionListAddonsParams, SubscriptionListParams, SubscriptionOption, SubscriptionOptionalCreateProps, SubscriptionPreferences, SubscriptionPricingPreview, SubscriptionPricingPreviewRequest, SubscriptionRequiredCreateProps, SubscriptionSortBy, SubscriptionStatus, Subscription_2021_01, SubscriptionsResponse, TaxLine, Tier, TieredDiscount, TieredDiscountOffer, TieredDiscountOfferLineItem, TieredDiscountOfferTarget, TieredDiscountOfferTier, TieredDiscountOffersRequest, TieredDiscountOffersResponse, TieredDiscountStatus, TieredDiscountsParams, TieredDiscountsResponse, Translations, TriggerCustomerPortalFlowOptions, TriggerCustomerPortalFlowResponse, UpdateAddressParams, UpdateAddressRequest, UpdateBundlePurchaseItem, UpdateBundleSelectionRequest, UpdateCustomerRequest, UpdateMetafieldRequest, UpdateOnetimeRequest, UpdatePaymentMethodRequest, UpdateSubscriptionChargeDateParams, UpdateSubscriptionParams, UpdateSubscriptionRequest, UpdateSubscriptionsParams, UpdateSubscriptionsRequest, Variant, VariantSelector, VariantSelectorStepSetting, WidgetIconColor, WidgetTemplateType, WidgetVisibility, intervalUnit, membershipIncludes };
|
|
4513
|
+
export type { ActivateMembershipRequest, AddToCartCallbackSettings, Addon, AddonProduct, AddonSettings, AddonType, AddonsSection, Address, AddressIncludes, AddressListParams, AddressListResponse, AddressResponse, AddressSortBy, AnalyticsData, Announcement, ApplyCreditOptions, AssociatedAddress, BaseCardDetails, BaseProduct, BaseProductVariant, BaseVariant, BasicSubscriptionParams, BlockedByExclusion, BooleanLike, BooleanNumbers, BooleanString, BooleanStringNumbers, BulkSubscriptionParams, BundleAppProxy, BundleData, BundleDataBaseProduct, BundleDataCollection, BundleDataSellingPlan, BundleDataSellingPlanGroup, BundleDataVariant, BundleFilterGroup, BundlePriceRule, BundleProduct, BundleProductGlobalStyles, BundleProductLayoutSettings, BundlePurchaseItem, BundlePurchaseItemParams, BundleSelection, BundleSelectionAppProxy, BundleSelectionItem, BundleSelectionItemRequiredCreateProps, BundleSelectionListParams, BundleSelectionsResponse, BundleSelectionsSortBy, BundleSettings, BundleTemplateSettings, BundleTemplateType, BundleTranslations, BundleVariant, BundleVariantOptionSource, BundleVariantOptionSourceBase, BundleVariantOptionSourceSubscription, BundleVariantRange, BundleVariantSelectionDefault, CDNBaseWidgetSettings, CDNBundleSettings, CDNBundleVariant, CDNBundleVariantOptionSource, CDNPlan, CDNProduct, CDNProductAndSettings, CDNProductKeyObject, CDNProductQuery_2020_12, CDNProductQuery_2022_06, CDNProductRaw, CDNProductResource, CDNProductResponseType, CDNProductType, CDNProductVariant_2022_06, CDNProduct_2022_06, CDNProductsAndSettings, CDNProductsAndSettingsResource, CDNStoreSettings, CDNSubscriptionOption, CDNVariant, CDNVersion, CDNWidgetSettings, CDNWidgetSettingsRaw, CDNWidgetSettingsResource, CRUDRequestOptions, CancelMembershipRequest, CancelSubscriptionRequest, CardDetailsFirstNameLastName, CardDetailsFullName, ChangeMembershipRequest, ChannelSettings, Charge, ChargeIncludes, ChargeListParams, ChargeListResponse, ChargeResponse, ChargeSortBy, ChargeStatus, Collection, CollectionBinding, CollectionListParams, CollectionTypes, CollectionsResponse, CollectionsSortBy, ColorString, CreateAddressRequest, CreateBundleSelectionRequest, CreateMetafieldRequest, CreateOnetimeRequest, CreatePaymentMethodRequest, CreateRecipientAddress, CreateSubscriptionRequest, CreateSubscriptionsParams, CreateSubscriptionsRequest, CreditAccount, CreditAccountIncludes, CreditAccountListParams, CreditAccountType, CreditAccountsResponse, CreditAccountsSortBy, CreditProjection, CreditSummaryIncludes, CrossSellsSection, CrossSellsSettings, CurrencyPriceSet, Customer, CustomerCreditSummary, CustomerDeliveryScheduleParams, CustomerDeliveryScheduleResponse, CustomerIncludeGiftPurchase, CustomerIncludes, CustomerNotification, CustomerNotificationOptions, CustomerNotificationTemplate, CustomerNotificationType, CustomerPortalAccessOptions, CustomerPortalAccessResponse, CustomerPortalFlowAction, CustomerPortalSettings, CustomerSurveyOfferParams, CustomerSurveyOfferResponse, CustomerSurveyOffersResponse, CustomerSurveyReason, CustomerSurveyReasonsResponse, DefaultProduct, DefaultSelection, DefaultVariant, DelayOption, DeleteSubscriptionsParams, DeleteSubscriptionsRequest, Delivery, DeliveryLineItem, DeliveryOrder, DeliveryPaymentMethod, Discount, DiscountApplicationMethod, DiscountType, DynamicBundleItemAppProxy, DynamicBundlePropertiesAppProxy, DynamicPricingPreviewDetails, EligibleChargeType, EligibleLineItemType, ExcludableCreditAccountType, ExternalAttributeSchema, ExternalId, ExternalProductStatus, ExternalTransactionId, FilterInputType, FilterMatchMode, FilterSource, FirstOption, GetAddressOptions, GetChargeIncludes, GetChargeOptions, GetCreditSummaryOptions, GetCustomerOptions, GetMembershipProgramOptions, GetOrderOptions, GetPaymentMethodOptions, GetRequestOptions, GetSubscriptionOptions, GiftPurchase, GiftPurchasesParams, GiftPurchasesResponse, HTMLString, Incentives, InitOptions, InternalSession, IntervalUnit, InventoryPolicy, IsoDateString, LineItem, ListParams, LoginResponse, Membership, MembershipBenefit, MembershipIncludes, MembershipListParams, MembershipListResponse, MembershipProgram, MembershipProgramIncludes, MembershipProgramListParams, MembershipProgramListResponse, MembershipProgramResponse, MembershipProgramSortBy, MembershipProgramStatus, MembershipResponse, MembershipStatus, MembershipsSortBy, MergeAddressesRequest, Metafield, MetafieldOptionalCreateProps, MetafieldOwnerResource, MetafieldRequiredCreateProps, Method, Modifier, MultiStepSettings, OfferAttributes, OnePageSettings, Onetime, OnetimeIncludes, OnetimeListParams, OnetimeOptionalCreateProps, OnetimeRequiredCreateProps, OnetimeSubscription, OnetimesResponse, OnetimesSortBy, OnlineStoreOptions, Options, Order, OrderIncludes, OrderListParams, OrderSortBy, OrderStatus, OrderType, OrdersResponse, PasswordlessCodeResponse, PasswordlessOptions, PasswordlessValidateResponse, PaymentDetails, PaymentErrorCallback, PaymentFieldEventCallback, PaymentFormConfig, PaymentFormController, PaymentFormEventHandlers, PaymentMethod, PaymentMethodFormOptions, PaymentMethodIncludes, PaymentMethodListParams, PaymentMethodOptionalCreateProps, PaymentMethodRequiredCreateProps, PaymentMethodSortBy, PaymentMethodStatus, PaymentMethodTokenCallback, PaymentMethodsResponse, PaymentType, Plan, PlanAddonSettings, PlanListParams, PlanSortBy, PlanType, PlansResponse, PriceRange, PriceRule, PriceSet, PricingProgressionResetTrigger, ProcessorName, Product, ProductImage, ProductInclude, ProductListResponse, ProductOption, ProductSearchParams_2020_12, ProductSearchParams_2022_06, ProductSearchResponse_2020_12, ProductSearchResponse_2022_06, ProductSearchType, ProductSource, ProductValueOption, ProductVariant_2020_12, ProductVariant_2022_06, Product_2020_12, Product_2022_06, Property, PublicBundleData, PublishStatus, PunchCardProgress, PunchCardProgressData, QuantityRange, RecurringSubscription, ReferralInfo, ReferralUrl, Request, RequestHeaders, RequestOptions, SellingPlan, SellingPlanAllocation, SellingPlanGroup, Session, ShippingCountriesOptions, ShippingCountriesResponse, ShippingCountry, ShippingLine, ShippingProvince, ShopifyStorefrontOptions, ShopifyUpdatePaymentInfoOptions, SkipChargeParams, SkipFutureChargeAddressRequest, SkipFutureChargeAddressResponse, SortBy, SortField, SortKeys, StepSettings, StepSettingsCommon, StepSettingsTypes, StoreSettings, StorefrontEnvironment, StorefrontOptions, StorefrontPurchaseOption, SubType, Subscription, SubscriptionBase, SubscriptionCancelled, SubscriptionIncludes, SubscriptionListAddonsParams, SubscriptionListParams, SubscriptionOption, SubscriptionOptionalCreateProps, SubscriptionPreferences, SubscriptionPricingPreview, SubscriptionPricingPreviewRequest, SubscriptionRequiredCreateProps, SubscriptionSortBy, SubscriptionStatus, Subscription_2021_01, SubscriptionsResponse, TaxLine, Tier, TieredDiscount, TieredDiscountOffer, TieredDiscountOfferLineItem, TieredDiscountOfferTarget, TieredDiscountOfferTier, TieredDiscountOffersRequest, TieredDiscountOffersResponse, TieredDiscountStatus, TieredDiscountsParams, TieredDiscountsResponse, Translations, TriggerCustomerPortalFlowOptions, TriggerCustomerPortalFlowResponse, UpdateAddressParams, UpdateAddressRequest, UpdateBundlePurchaseItem, UpdateBundleSelectionRequest, UpdateCustomerRequest, UpdateMetafieldRequest, UpdateOnetimeRequest, UpdatePaymentMethodRequest, UpdateSubscriptionChargeDateParams, UpdateSubscriptionParams, UpdateSubscriptionRequest, UpdateSubscriptionsParams, UpdateSubscriptionsRequest, Variant, VariantSelector, VariantSelectorStepSetting, WidgetIconColor, WidgetTemplateType, WidgetVisibility, intervalUnit, membershipIncludes };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
// recharge-client-2.
|
|
2
|
-
(function(O,D){typeof exports=="object"&&typeof module<"u"?module.exports=D():typeof define=="function"&&define.amd?define(D):(O=typeof globalThis<"u"?globalThis:O||self,O.recharge=D())})(this,(function(){"use strict";const O="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";function D(t=21){let e="";for(let r=0;r<t;r++)e+=O[Math.random()*64|0];return e}let me={storeIdentifier:"",environment:"prod"};function it(t){me=t}function y(){return me}const st=(t,e="")=>{switch(t){case"prod":return"https://api.rechargeapps.com";case"stage":return"https://api.stage.rechargeapps.com";case"preprod":case"prestage":return`${e}/api`}},ot=(t,e="")=>{switch(t){case"prod":return"https://admin.rechargeapps.com";case"stage":return"https://admin.stage.rechargeapps.com";case"preprod":case"prestage":return e}},at=t=>{switch(t){case"prod":case"preprod":return"https://static.rechargecdn.com";case"stage":case"prestage":return"https://static.stage.rechargecdn.com"}},fe="/tools/recurring";class F{constructor(e,r){this.name="RechargeRequestError",this.message=e,this.status=r}}function p(t){return encodeURIComponent(`${t}`.trim())}function ct(t){const e=r=>encodeURIComponent(r===null?"":String(r));return Object.entries(t).filter(([,r])=>r!==void 0&&!(Array.isArray(r)&&r.length===0)).map(([r,n])=>`${r}=${Array.isArray(n)?n.map(e).join(","):e(n)}`).join("&")}const dt=new Set(["shop_url"]),ge=new WeakMap;let J=0;function ut(t){let e=ge.get(t);return e||(e={},ge.set(t,e)),e}function lt(t,e,r){const n=ut(t);return n.inFlight?n.inFlight:n.latest&&n.latest.generation>r?Promise.resolve(n.latest.session):(n.inFlight=t().then(i=>(i&&i.apiToken!==e&&(J+=1,n.latest={session:i,generation:J}),i)).finally(()=>{n.inFlight=void 0}),n.inFlight)}function a(t,e){return{...t,internalFnCall:t.internalFnCall??e,internalRequestId:t.internalRequestId??D()}}async function j(t,e,r={}){const n=y();return I(t,`${at(n.environment)}/store/${n.storeIdentifier}${e}`,r)}async function c(t,e,{id:r,query:n,data:i,headers:s}={},o){const{environment:u,environmentUri:h,storeIdentifier:_,loginRetryFn:f,__unstable_twoFactorRetryFn:b,appName:v,appVersion:d}=y();if(!_)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const m=o.apiToken;if(!m)throw new Error("No API token defined on session.");const w=J,C=st(u,h),k={"X-Recharge-Access-Token":m,"X-Recharge-Version":"2021-11","X-Recharge-Sdk-Fn":o.internalFnCall,...v?{"X-Recharge-Sdk-App-Name":v}:{},...d?{"X-Recharge-Sdk-App-Version":d}:{},"X-Recharge-Sdk-Version":"2.9.0","X-Request-Id":o.internalRequestId,...o.tmp_fn_identifier?{"X-Recharge-Sdk-Fn-Identifier":o.tmp_fn_identifier}:{},...s||{}},T=n,G={...T?Object.fromEntries(Object.entries(T).filter(([P])=>!dt.has(P))):void 0,shop_url:_};try{return await I(t,`${C}${e}`,{id:r,query:G,data:i,headers:k})}catch(P){const he={401:f,423:b},K=P instanceof F&&P.status?he[P.status]:void 0;if(!K)throw P;const Y=await lt(K,m,w);if(!Y)throw P;return I(t,`${C}${e}`,{id:r,query:G,data:i,headers:{...k,"X-Recharge-Access-Token":Y.apiToken}})}}async function A(t,e,r={}){return I(t,`${fe}${e}`,r)}async function I(t,e,{id:r,query:n,data:i,headers:s}={}){let o=e.trim();if(r&&(o=[o,p(r)].join("/")),n){let b;[o,b]=o.split("?");const v=[b,ct(n)].join("&").replace(/^&/,"");o=`${o}${v?`?${v}`:""}`}let u;i&&t!=="get"&&(u=JSON.stringify(i));const h={Accept:"application/json","Content-Type":"application/json","X-Recharge-App":"storefront-client",...s||{}},_=await fetch(o,{method:t,headers:h,body:u});let f;try{f=await _.json()}catch{}if(!_.ok)throw _.status===502||_.status===504?new F("A gateway error occurred while making the request",_.status):f&&f.error?new F(f.error,_.status):f&&f.errors?new F(JSON.stringify(f.errors),_.status):new F("A connection error occurred while making the request");return f}function pt(t,e){return c("get","/addresses",{query:e},a(t,"listAddresses"))}async function _t(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{address:n}=await c("get","/addresses",{id:e,query:{include:r?.include}},a(t,"getAddress"));return n}async function ht(t,e){const{address:r}=await c("post","/addresses",{data:{...e,customer_id:t.customerId?Number(t.customerId):void 0}},a(t,"createAddress"));return r}async function Q(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{address:i}=await c("put","/addresses",{id:e,data:r,query:n},a(t,"updateAddress"));return i}async function mt(t,e,r,n){return Q(a(t,"applyDiscountToAddress"),e,{discounts:[{code:r}]},n)}async function ft(t,e,r){if(e===void 0||e==="")throw new Error("Id is required");return Q(a(t,"removeDiscountsFromAddress"),e,{discounts:[]},r)}function gt(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/addresses",{id:e},a(t,"deleteAddress"))}async function wt(t,e){const{address:r}=await c("post","/addresses/merge",{data:e},a(t,"mergeAddresses"));return r}async function yt(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/addresses/${p(e)}/charges/skip`,{data:r},a(t,"skipFutureCharge"));return n}var bt=Object.freeze({__proto__:null,applyDiscountToAddress:mt,createAddress:ht,deleteAddress:gt,getAddress:_t,listAddresses:pt,mergeAddresses:wt,removeDiscountsFromAddress:ft,skipFutureCharge:yt,updateAddress:Q});async function vt(){const{storefrontAccessToken:t}=y(),e={};t&&(e["X-Recharge-Storefront-Access-Token"]=t);const r=await A("get","/access",{headers:e});return{apiToken:r.api_token,customerId:r.customer_id,message:r.message}}async function St(t,e){return we(t,e)}async function we(t,e){if(!t)throw new Error("Shopify storefront token is required");const{storeIdentifier:r}=y();if(!r)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{api_token:n,customer_id:i,message:s}=await R("post","/shopify_storefront_access",{data:{customer_token:e,storefront_token:t,shop_url:r}});return n?{apiToken:n,customerId:i,message:s}:null}async function $t(t){const{storeIdentifier:e}=y();if(!e)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{api_token:r,customer_id:n,message:i}=await R("post","/shopify_customer_account_api_access",{data:{customer_token:t,shop_url:e}});return r?{apiToken:r,customerId:n,message:i}:null}async function It(t,e={}){if(!t)throw new Error("Email is required.");const{storeIdentifier:r}=y();if(!r)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{send_email:n,send_sms:i}=e,s=await R("post","/attempt_login",{data:{email:t,shop:r,...n!==void 0?{send_email:n}:{},...i!==void 0?{send_sms:i}:{}}});if(s.errors)throw new Error(s.errors);return s.session_token}async function qt(t,e={}){if(!t)throw new Error("Email is required.");const{storefrontAccessToken:r}=y(),n={};r&&(n["X-Recharge-Storefront-Access-Token"]=r);const{send_email:i,send_sms:s}=e,o=await A("post","/attempt_login",{data:{email:t,...i!==void 0?{send_email:i}:{},...s!==void 0?{send_sms:s}:{}},headers:n});if(o.errors)throw new Error(o.errors);return o.session_token}async function Et(t,e,r){if(!t)throw new Error("Email is required.");if(!e)throw new Error("Session token is required.");if(!r)throw new Error("Code is required.");const{storeIdentifier:n}=y();if(!n)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const i=await R("post","/validate_login",{data:{code:r,email:t,session_token:e,shop:n}});if(i.errors)throw new Error(i.errors);return{apiToken:i.api_token,customerId:i.customer_id}}async function Ct(t,e,r){if(!t)throw new Error("Email is required.");if(!e)throw new Error("Session token is required.");if(!r)throw new Error("Code is required.");const{storefrontAccessToken:n}=y(),i={};n&&(i["X-Recharge-Storefront-Access-Token"]=n);const s=await A("post","/validate_login",{data:{code:r,email:t,session_token:e},headers:i});if(s.errors)throw new Error(s.errors);return{apiToken:s.api_token,customerId:s.customer_id}}function kt(t){if(window.ReCharge?.token)return window.ReCharge.token;if(!t)return null;try{return window.sessionStorage.getItem(`rc_cp_token:${t}`)}catch{return null}}function xt(){const{customerHash:t}=y(),{pathname:e,search:r}=window.location,n=new URLSearchParams(r),i=e.split("/").filter(Boolean),s=i.findIndex(h=>h==="portal"),o=s!==-1?i[s+1]:t,u=n.get("token")||kt(o);if(!u||!o)throw new Error("Not in context of Recharge Customer Portal or URL did not contain correct params");return{customerHash:o,token:u}}async function Pt(){const{customerHash:t,token:e}=xt(),{storeIdentifier:r}=y(),n=await R("post",`/customers/${p(t)}/access`,{data:{token:e,shop:r}});return{apiToken:n.api_token,customerId:n.customer_id}}async function R(t,e,{id:r,query:n,data:i,headers:s}={}){const{environment:o,environmentUri:u,storefrontAccessToken:h,appName:_,appVersion:f}=y(),b=ot(o,u),v={...h?{"X-Recharge-Storefront-Access-Token":h}:{},..._?{"X-Recharge-Sdk-App-Name":_}:{},...f?{"X-Recharge-Sdk-App-Version":f}:{},"X-Recharge-Sdk-Version":"2.9.0",...s||{}};return I(t,`${b}${e}`,{id:r,query:n,data:i,headers:v})}var At=Object.freeze({__proto__:null,loginCustomerPortal:Pt,loginShopifyApi:St,loginShopifyAppProxy:vt,loginWithShopifyCustomerAccount:$t,loginWithShopifyStorefront:we,sendPasswordlessCode:It,sendPasswordlessCodeAppProxy:qt,validatePasswordlessCode:Et,validatePasswordlessCodeAppProxy:Ct});const ye="XdrError";class l extends Error{constructor(e){super(e),this.name=ye}static[Symbol.hasInstance](e){return e instanceof Error&&e.name===ye}}function be(t){return(4-t%4)%4}function ve(t){if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Se(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new l(`${e}: expected uint32 length`)}function Z(t,e,r,n){if(typeof t!="number"||!Number.isInteger(t)||t<e||t>r)throw new l(`${n}: expected integer in range ${e}..${r}`)}function Dt(t,e,r,n){if(typeof t!="bigint"||t<e||t>r)throw new l(`${n}: expected bigint in range ${e}..${r}`)}function Tt(t,e){if(!(t instanceof Uint8Array))throw new l(`${e}: expected Uint8Array`);try{Uint8Array.prototype.at.call(t,0)}catch{throw new l(`${e}: Uint8Array is detached or out of bounds`)}}function Ot(t,e){if(!Array.isArray(t))throw new l(`${e}: expected array`)}const $e=1500;class Ft{#e=0;#i=0;#t;#n;#s;bytes;constructor(e,r=$e){if(r<0||!Number.isInteger(r))throw new l(`invalid maxDepth ${r}`);if(this.#t=r,!ArrayBuffer.isView(e)||e.BYTES_PER_ELEMENT!==1)throw new TypeError("Reader expects a Uint8Array");this.bytes=Object.getPrototypeOf(e)===Uint8Array.prototype?e:e.byteLength===0?new Uint8Array(0):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),this.#n=this.bytes.buffer?.detached?new DataView(new ArrayBuffer(0)):new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.#s=this.#n.byteLength}#r(e,r){if(this.remaining<e)throw new l(`${r}: incomplete XDR data at offset ${this.#e}, expected ${e} byte(s)`);const n=this.#e;return this.#e+=e,n}get offset(){return this.#e}get remaining(){return this.#s-this.#e}enter(e){if(this.#i+=1,this.#i>this.#t)throw this.#i-=1,new l(`${e}: max recursion depth ${this.#t} exceeded`)}exit(){this.#i-=1}done(e){if(this.remaining!==0)throw new l(`${e}: trailing ${this.remaining} byte(s) after XDR value`)}readBytes(e,r){if(e<0||!Number.isInteger(e))throw new l(`${r}: invalid byte length ${e}`);if(this.remaining<e)throw new l(`${r}: incomplete XDR data at offset ${this.#e}, expected ${e} byte(s)`);const n=this.bytes.slice(this.#e,this.#e+e);if(n.length!==e)throw new l(`${r}: input shrank during decode`);return this.#e+=e,n}skipPadding(e,r){if(e<0||!Number.isInteger(e))throw new l(`${r}: invalid byte length ${e}`);const n=be(e);if(n===0)return;const i=this.#r(n,r);for(let s=0;s<n;s++)if(this.bytes[i+s]!==0)throw this.#e=i,new l(`${r}: non-zero XDR padding`)}readInt32(e){return this.#n.getInt32(this.#r(4,e),!1)}readUint32(e){return this.#n.getUint32(this.#r(4,e),!1)}readBigInt64(e){return this.#n.getBigInt64(this.#r(8,e),!1)}readBigUint64(e){return this.#n.getBigUint64(this.#r(8,e),!1)}readFloat32(e){return this.#n.getFloat32(this.#r(4,e),!1)}readFloat64(e){return this.#n.getFloat64(this.#r(8,e),!1)}}const Rt=8192;class Ie{#e=new Uint8Array(Rt);#i=new DataView(this.#e.buffer);#t=0;#n=0;#s;constructor(e=$e){if(e<0||!Number.isInteger(e))throw new l(`invalid maxDepth ${e}`);this.#s=e}get offset(){return this.#t}enter(e){if(this.#n+=1,this.#n>this.#s)throw this.#n-=1,new l(`${e}: max recursion depth ${this.#s} exceeded`)}exit(){this.#n-=1}writeBytes(e){this.#o(e.length),this.#e.set(e,this.#t),this.#t+=e.length}writePadding(e){const r=be(e);r>0&&(this.#o(r),this.#e.fill(0,this.#t,this.#t+r),this.#t+=r)}writeInt32(e){const r=this.#r(4);this.#i.setInt32(r,e,!1),this.#t+=4}writeUint32(e){const r=this.#r(4);this.#i.setUint32(r,e,!1),this.#t+=4}writeBigInt64(e){const r=this.#r(8);this.#i.setBigInt64(r,e,!1),this.#t+=8}writeBigUint64(e){const r=this.#r(8);this.#i.setBigUint64(r,e,!1),this.#t+=8}writeFloat32(e){const r=this.#r(4);this.#i.setFloat32(r,e,!1),this.#t+=4}writeFloat64(e){const r=this.#r(8);this.#i.setFloat64(r,e,!1),this.#t+=8}#r(e){return this.#o(e),this.#t}toUint8Array(){return this.#e.slice(0,this.#t)}#o(e){const r=this.#t+e;if(r<=this.#e.length)return;let n=this.#e.length;for(;n<r;)n*=2;const i=new Uint8Array(n);i.set(this.#e),this.#e=i,this.#i=new DataView(i.buffer)}}const Nt=4294967295;class x{name;constructor(e=void 0){this.name=e}encode(e,r){const n=new Ie(r?.maxDepth);return this._write(e,n,this.name??this.kind),n.toUint8Array()}decode(e,r){const n=new Ft(e,r?.maxDepth),i=this._read(n,this.name??this.kind);return n.done(this.name??this.kind),i}validateXdr(e,r){try{return this.decode(e,r),!0}catch(n){if(n instanceof l)return!1;throw n}}validate(e){try{const r=new Ie;return this._write(e,r,this.name??this.kind),!0}catch(r){if(r instanceof l)return!1;throw r}}}class Bt extends x{kind="array";element;maxLength;constructor(e,r){super(),Se(r,"array maxLength"),this.element=e,this.maxLength=r}_read(e,r){e.enter(r);try{const n=e.readUint32(r);if(n>this.maxLength)throw new l(`${r}: array length ${n} exceeds maximum ${this.maxLength}`);if(n>e.remaining)throw new l(`${r}: array length ${n} exceeds remaining ${e.remaining} byte(s)`);return jt(e,n,this.element,r)}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(Ot(e,n),e.length>this.maxLength)throw new l(`${n}: array length ${e.length} exceeds maximum ${this.maxLength}`);r.writeUint32(e.length),Ut(e,r,this.element,n)}finally{r.exit()}}}function Mt(t,e){return new Bt(t,e)}function jt(t,e,r,n){const i=[];for(let s=0;s<e;s+=1){const o=t.offset,u=r._read(t,`${n}[${s}]`);if(t.offset===o)throw new l(`${n}[${s}]: element type '${r.name??r.kind}' consumed no input; an array element must encode to at least one byte`);i.push(u)}return i}function Ut(t,e,r,n){let i=0;for(const s of t){const o=e.offset;if(r._write(s,e,`${n}[${i}]`),e.offset===o)throw new l(`${n}[${i}]: element type '${r.name??r.kind}' encoded to zero bytes; an array element must encode to at least one byte`);i+=1}}const Lt=new Set(["__proto__","name","kind","encode","decode","validate","_read","_write","nameByValue"]);class Vt extends x{kind="enum";nameByValue;#e=new Set;constructor(e,r){super(e);const n=new Map;for(const[i,s]of Object.entries(r)){if(Z(s,-2147483648,2147483647,`${e}.${i}`),this.#e.has(s))throw new l(`${e}: duplicate enum value ${s}`);this.#e.add(s),n.set(s,i)}this.nameByValue=n}_read(e,r){const n=e.readInt32(r);if(!this.#e.has(n))throw new l(`${r}: unknown enum value ${n}`);return n}_write(e,r,n){if(typeof e!="number"||!this.#e.has(e))throw new l(`${n}: unknown enum value ${String(e)}`);r.writeInt32(e)}}function zt(t,e){for(const n of Object.getOwnPropertyNames(e))if(Lt.has(n))throw new l(`${t}: enum member name ${n} collides with reserved property`);const r=new Vt(t,e);return Object.assign(r,e)}class Xt extends x{kind="int32";_read(e,r){return e.readInt32(r)}_write(e,r,n){Z(e,-2147483648,2147483647,n),r.writeInt32(e)}}function qe(){return new Xt}class Ht extends x{constructor(e){super(),this.maxLength=e,Se(e,"string maxLength")}maxLength;kind="string";_read(e,r){const n=e.readUint32(r);if(n>this.maxLength)throw new l(`${r}: string byte length ${n} exceeds maximum ${this.maxLength}`);const i=e.readBytes(n,r);return e.skipPadding(n,r),i}_write(e,r,n){if(Tt(e,n),e.length>this.maxLength)throw new l(`${n}: string byte length ${e.length} exceeds maximum ${this.maxLength}`);r.writeUint32(e.length),r.writeBytes(e),r.writePadding(e.length)}}function Wt(t){return new Ht(t)}class Gt extends x{kind="struct";entries;constructor(e,r){if(super(e),Object.getOwnPropertyNames(r).includes("__proto__"))throw new l(`${e}: struct field name '__proto__' is not allowed`);this.entries=Object.entries(r)}_read(e,r){e.enter(r);try{const n={};for(const[i,s]of this.entries)n[i]=s._read(e,`${r}.${i}`);return n}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(!ve(e))throw new l(`${n}: expected plain object`);const i=e;for(const[s,o]of this.entries){if(!Object.prototype.hasOwnProperty.call(i,s))throw new l(`${n}.${s}: missing struct field`);o._write(i[s],r,`${n}.${s}`)}}finally{r.exit()}}}function Ee(t,e){return new Gt(t,e)}class Kt extends x{kind="uint32";_read(e,r){return e.readUint32(r)}_write(e,r,n){Z(e,0,4294967295,n),r.writeUint32(e)}}function Ce(){return new Kt}class Yt extends x{kind="uint64";_read(e,r){return e.readBigUint64(r)}_write(e,r,n){Dt(e,0n,(1n<<64n)-1n,n),r.writeBigUint64(e)}}function U(){return new Yt}const ee="default";class Jt extends x{kind="union";switchOn;cases;defaultArm;switchKey;#e=new Map;constructor(e,r,n,i,s){if(super(e),s==="__proto__")throw new l(`${e}: switchKey '__proto__' is not allowed`);if(this.switchOn=r,this.cases=n,this.defaultArm=i,this.switchKey=s,n.length===0&&i===void 0)throw new l(`${e}: union needs at least one case or a default arm`);const o=new Set;for(const u of n){if(!r.validate(u.discriminant))throw new l(`${e}.${u.name}: case discriminator ${String(u.discriminant)} is not a valid ${r.name??r.kind} value`);if(o.has(u.name))throw new l(`${e}: duplicate union case name ${u.name}`);if(o.add(u.name),this.#e.has(u.discriminant))throw new l(`${e}: duplicate union discriminator ${String(u.discriminant)}`);ke(e,u.name,u.arm,s),this.#e.set(u.discriminant,u)}i!==void 0&&ke(e,ee,i,s)}_read(e,r){e.enter(r);try{const n=this.switchOn._read(e,`${r}.${this.switchKey}`),i=this.#e.get(n),s=i?.arm??this.defaultArm;if(s===void 0)throw new l(`${r}: no case for union discriminator ${String(n)}`);return Zt(n,s,this.switchKey,e,`${r}.${i?.name??ee}`)}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(!ve(e)||!Object.prototype.hasOwnProperty.call(e,this.switchKey))throw new l(`${n}: expected union object with ${this.switchKey} discriminator`);const i=e,s=i[this.switchKey],o=this.#e.get(s),u=o?.arm??this.defaultArm;if(u===void 0)throw new l(`${n}: no case for union discriminator ${String(s)}`);this.switchOn._write(s,r,`${n}.${this.switchKey}`),er(i,u,r,`${n}.${o?.name??ee}`)}finally{r.exit()}}}function Qt(t,e){return{kind:"field",name:t,schema:e}}function te(t,e,r){return{name:t,discriminant:e,arm:r}}function re(t,e){const r=e.switchKey??"type";return new Jt(t,e.switchOn,e.cases,e.defaultArm,r)}function Zt(t,e,r,n,i){const s={};return s[r]=t,L(e)?(s[e.name]=e.schema._read(n,`${i}.${e.name}`),s):(e._read(n,i),s)}function er(t,e,r,n){if(L(e)){if(!Object.prototype.hasOwnProperty.call(t,e.name))throw new l(`${n}.${e.name}: missing union arm payload`);e.schema._write(t[e.name],r,`${n}.${e.name}`);return}e._write(void 0,r,n)}function ke(t,e,r,n){if(L(r)&&r.name===n)throw new l(`${t}.${e}: union arm payload field must not be named ${n}`);if(L(r)&&r.name==="__proto__")throw new l(`${t}.${e}: union arm payload field name '__proto__' is not allowed`)}function L(t){return"schema"in t}class tr extends x{kind="void";_read(){}_write(e,r,n){if(e!==void 0)throw new l(`${n}: expected void`)}}function xe(){return new tr}var Pe=t=>{throw TypeError(t)},ne=(t,e,r)=>e.has(t)||Pe("Cannot "+r),g=(t,e,r)=>(ne(t,e,"read from private field"),e.get(t)),V=(t,e,r)=>e.has(t)?Pe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ie=(t,e,r,n)=>(ne(t,e,"write to private field"),e.set(t,r),r),$=(t,e,r)=>(ne(t,e,"access private method"),r),q,E,N,S,Ae,De,se,B,z;const rr=new TextEncoder,Te={v:0};function nr(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}const oe=zt("EnvelopeType",{envelopeTypeBundle:0}),ir=re("BundleItemExt",{switchOn:qe(),switchKey:"v",cases:[te("v0",0,xe())]}),sr=Ee("BundleItem",{collectionId:U(),productId:U(),variantId:U(),sku:Wt(Nt),quantity:Ce(),ext:ir}),or=re("BundleExt",{switchOn:qe(),switchKey:"v",cases:[te("v0",0,xe())]}),ar=Ee("Bundle",{variantId:U(),items:Mt(sr,500),version:Ce(),ext:or}),cr=re("BundleEnvelope",{switchOn:oe,switchKey:"type",cases:[te("envelopeTypeBundle",oe.envelopeTypeBundle,Qt("v1",ar))]});function dr(t){const e={type:oe.envelopeTypeBundle,v1:{variantId:BigInt(t.variantId.toString()),items:t.items.map(r=>({collectionId:BigInt(r.collectionId.toString()),productId:BigInt(r.productId.toString()),variantId:BigInt(r.variantId.toString()),sku:rr.encode(r.sku||""),quantity:r.quantity,ext:Te})),version:Math.floor(Date.now()/1e3),ext:Te}};return nr(cr.encode(e))}class ur{constructor(e,r){V(this,S),V(this,q),V(this,E),V(this,N),ie(this,q,$(this,S,Ae).call(this,r)),ie(this,N,$(this,S,De).call(this,r)),ie(this,E,e)}isInitialDataValid(){if(!g(this,N))throw"Bundle data does not exist for the given product.";if(!g(this,q))throw"Bundle settings do not exist for the given product.";if(!Array.isArray(g(this,E))||!g(this,E).length)throw"No bundle selection items provided.";return!0}isValidVariant(e){if(!g(this,q)?.variantsSettings[e])throw`The ${e} bundle variant is invalid.`;return!0}isSelectionInVariantRange(e){const r=g(this,E).reduce((i,s)=>i+s.quantity,0),n=g(this,q)?.variantsSettings[e].ranges||[];if(!$(this,S,se).call(this,n,r))throw"The total number of products does not fall within the required variant range.";return!0}areItemsInMaxPerItemBound(){const e=g(this,q)?.bundleSettings.maxPerItem||0,r=g(this,E).filter(({quantity:n})=>n>e);if(e&&r.length)throw`The selected products (${$(this,S,B).call(this,r.map(({externalProductId:n})=>n)).join(", ")}) exceed the maximum limit of ${e} items per product.`;return!0}areSelectedCollectionsValid(e){const r=g(this,q)?.variantsSettings[e]?.optionSources,n=g(this,E).filter(({collectionId:i})=>!r||!$(this,S,z).call(this,r,i));if(n.length)throw`The collections (${$(this,S,B).call(this,n.map(({collectionId:i})=>i)).join(", ")}) are no longer valid for the bundle variant (${e}).`;return!0}areItemsQuantitiesValidForTheCollection(e){const r=g(this,E).reduce((s,o)=>(s[o.collectionId]=o.quantity+(s[o.collectionId]||0),s),Object.create(null)),n=g(this,q)?.variantsSettings[e],i=Object.values(n?.optionSources||{}).filter(s=>{const o=r[s.collectionId]||0;return!$(this,S,se).call(this,[s],o)});if(!n||i.length)throw`The selection exceeds the limits for the collections (${$(this,S,B).call(this,i.map(({collectionId:s})=>s)).join(", ")}).`;return!0}areSelectedProductsValid(e){const r=g(this,q)?.variantsSettings[e]?.optionSources||{},n=Object.values(r).reduce((s,o)=>{const u=g(this,N)?.collections[o.collectionId];return u&&(s[o.collectionId]=u),s},Object.create(null));if(!Object.values(n).length)throw`No collections found for the bundle variant (${e}).`;const i=g(this,E).filter(({externalProductId:s,collectionId:o})=>$(this,S,z).call(this,n,o)?!$(this,S,z).call(this,n[o].products,s):!0);if(i.length)throw`The products (${$(this,S,B).call(this,i.map(({externalProductId:s})=>s)).join(", ")}) are no longer valid for the bundle product.`;return!0}isBundleSelectionValid(e){return this.isInitialDataValid(),this.isValidVariant(e),this.isSelectionInVariantRange(e),this.areItemsInMaxPerItemBound(),this.areSelectedCollectionsValid(e),this.areItemsQuantitiesValidForTheCollection(e),this.areSelectedProductsValid(e),!0}}q=new WeakMap,E=new WeakMap,N=new WeakMap,S=new WeakSet,Ae=function(t){try{const e=t.bundle_settings;return{bundleSettings:{maxPerItem:e.max_quantity_per_variant,isCustomizable:e.is_customizable},variantsSettings:e.variants.reduce((r,n)=>{if(!n.enabled)return r;let i=[{min:n.items_count,max:n.items_count}];return n.items_count||(i=n.ranges.map(({quantity_max:s,quantity_min:o})=>({min:o,max:s}))),r[n.external_variant_id]={externalVariantId:n.external_variant_id,optionSources:n.option_sources.reduce((s,o)=>(s[o.option_source_id]={min:o.quantity_min,max:o.quantity_max,collectionId:o.option_source_id},s),Object.create(null)),ranges:i},r},Object.create(null))}}catch{return null}},De=function(t){try{const e=Object.values(t.collections).reduce((r,n)=>(r[n.id]={...n,products:n.products.reduce((i,s)=>(i[s.id]=s,i),Object.create(null))},r),Object.create(null));return{...t,collections:e}}catch{return null}},se=function(t,e){return!!t.filter(({min:r,max:n})=>{const i=r??e,s=n??e;return i<=e&&e<=s}).length},B=function(t){return Array.from(new Set(t))},z=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};const lr="/bundling-storefront-manager";function Oe(t){return dr({variantId:t.externalVariantId,items:t.selections.map(e=>({collectionId:e.collectionId,productId:e.externalProductId,variantId:e.externalVariantId,quantity:e.quantity,sku:""}))})}async function pr(t){const e=y(),r=await ae(t);if(r!==!0)throw new Error(r);const n=Oe(t);try{const i=await A("post",`${lr}/api/v1/bundles`,{data:{bundle:n},headers:{Origin:`https://${e.storeIdentifier}`}});if(!i.id||i.code!==200)throw new Error(`1: failed generating rb_id: ${JSON.stringify(i)}`);return i.id}catch(i){throw new Error(`2: failed generating rb_id ${i}`)}}async function _r(t,e){const r=await ae(e);if(r!==!0)throw new Error(r);const n=Oe(e);try{const i=await c("post","/bundle_selections/bundle_id",{data:{bundle:n}},a(t,"getBundleSelectionId"));if(!i.id||i.code!==200)throw new Error(`1: failed generating rb_id: ${JSON.stringify(i)}`);return i.id}catch(i){throw new Error(`2: failed generating rb_id ${i}`)}}function hr(t,e){const r=Fe(t);if(r!==!0)throw new Error(`Dynamic Bundle is invalid. ${r}`);const n=`${D(9)}:${t.externalProductId}`;return t.selections.map(i=>{const s={id:i.externalVariantId,quantity:i.quantity,properties:{_rc_bundle:n,_rc_bundle_variant:t.externalVariantId,_rc_bundle_parent:e,_rc_bundle_collection_id:i.collectionId}};return i.sellingPlan?s.selling_plan=i.sellingPlan:i.shippingIntervalFrequency&&(s.properties.shipping_interval_frequency=i.shippingIntervalFrequency,s.properties.shipping_interval_unit_type=i.shippingIntervalUnitType,s.id=`${i.discountedVariantId}`),s})}async function ae(t){try{return t?t.selections.length===0?"No selections defined":!0:"Bundle is not defined"}catch(e){return`Error fetching bundle settings: ${e}`}}async function mr(t){try{const e=await A("get",`/bundle-data/${p(t.externalProductId)}`);return{valid:new ur(t.selections,e).isBundleSelectionValid(t.externalVariantId)}}catch(e){return{valid:!1,error:String(e)}}}const fr={day:["day","days","Days"],days:["day","days","Days"],Days:["day","days","Days"],week:["week","weeks","Weeks"],weeks:["week","weeks","Weeks"],Weeks:["week","weeks","Weeks"],month:["month","months","Months"],months:["month","months","Months"],Months:["month","months","Months"]};function Fe(t){if(!t)return"No bundle defined.";if(t.selections.length===0)return"No selections defined.";const{shippingIntervalFrequency:e,shippingIntervalUnitType:r}=t.selections.find(n=>n.shippingIntervalFrequency||n.shippingIntervalUnitType)||{};if(e||r){if(!e||!r)return"Shipping intervals do not match on selections.";{const n=fr[r];for(let i=0;i<t.selections.length;i++){const{shippingIntervalFrequency:s,shippingIntervalUnitType:o}=t.selections[i];if(s&&s!==e||o&&!n.includes(o))return"Shipping intervals do not match on selections."}}}return!0}async function gr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{bundle_selection:r}=await c("get","/bundle_selections",{id:e},a(t,"getBundleSelection"));return r}function wr(t,e){return c("get","/bundle_selections",{query:e},a(t,"listBundleSelections"))}async function yr(t,e){const{bundle_selection:r}=await c("post","/bundle_selections",{data:e},a(t,"createBundleSelection"));return r}async function br(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{bundle_selection:n}=await c("put","/bundle_selections",{id:e,data:r},a(t,"updateBundleSelection"));return n}function vr(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/bundle_selections",{id:e},a(t,"deleteBundleSelection"))}async function Sr(t,e,r,n){if(e===void 0||e==="")throw new Error("Purchase item ID is required");const{subscription:i}=await c("put","/bundles",{id:e,data:r,query:n},a(t,"updateBundle"));return i}var $r=Object.freeze({__proto__:null,createBundleSelection:yr,deleteBundleSelection:vr,getBundleId:pr,getBundleSelection:gr,getBundleSelectionId:_r,getDynamicBundleItems:hr,listBundleSelections:wr,updateBundle:Sr,updateBundleSelection:br,validateBundle:ae,validateBundleSelection:mr,validateDynamicBundle:Fe});const Ir=t=>{const e=t.layout_settings.addons,r=t.layout_settings.crossSells,n=t.customization_window,i=t.layout_settings?.defaultVariantId??t.default_bundle_variant_id,s=t.layout_settings.defaultFrequency,o=t.layout_settings.addToCartCallback;return{default_variant_id:i?String(i):null,is_customizable:t.is_customizable,price_rule:String(t.price_rule).toUpperCase(),customization_window:n?{active_days:n,disabled_message:t.customization_window_disabled_message||""}:null,addons:e.collectionId?{collection_id:e.collectionId,collection_handle:e.collectionHandle}:null,cross_sells:r.collectionId?{collection_id:e.collectionId,collection_handle:e.collectionHandle}:null,default_selling_plan_id:s||null,collapsible_collections:t.layout_settings.collapsibleSections,max_quantity_per_variant:t.max_quantity_per_variant,show_product_variants:t.layout_settings.showVariants,product_details_modal_enabled:t.layout_settings.learnMoreModal,addToCartBehavior:{type:o.type==="none"?"cart_page":o.type,value:o.value}}},qr=t=>t.tiered_discounts.length===0?null:{tiered_discounts:t.tiered_discounts},X=t=>({id:t.id,name:t.name,options:t.options.map(e=>({name:e.name,value:e.value})),recurring_deliveries:t.recurring_deliveries,price_adjustments:t.price_adjustments.map(({value:e,value_type:r})=>({value:e,value_type:r}))}),Re=t=>({name:t.name,options:t.options.map(e=>({name:e.name,values:e.values})),selling_plans:t.selling_plans.map(X)}),Ne=t=>({id:String(t.id),title:t.title,price:t.price,compare_at_price:t.compare_at_price,options:t.options,available_for_sale:t.available}),ce=t=>t==null||typeof t=="string"?t:"src"in t?t.src:null,Be=t=>({id:String(t.id),title:t.title,description:t.description,available_for_sale:t.available,featured_image:ce(t.featured_image),images:t.images,requires_selling_plan:t.requires_selling_plan,selling_plan_groups:t.selling_plan_groups.map(Re)}),Me=t=>{const e=Cr(t.selling_plan_groups);return{...Be(t),handle:t.handle,tags:t.tags,price_range:{min:t.price_min,max:t.price_max},compare_at_price_range:{min:t.compare_at_price_min,max:t.compare_at_price_max},options:t.options,variants:t.variants.map(r=>({...Ne(r),selling_plan_allocations:r.selling_plan_allocations.map(n=>({price:n.price,compare_at_price:n.compare_at_price,selling_plan:X(e[`${n.selling_plan_group_id}-${n.selling_plan_id}`])})),option1:r.option1,option2:r.option2,option3:r.option3,sku:r.sku||"",requires_shipping:r.requires_shipping,taxable:r.taxable,featured_image:ce(r.featured_image),public_title:r.public_title,requires_selling_plan:r.requires_selling_plan}))}},Er=({items_count:t,ranges:e})=>e.length>0?e.map(({quantity_max:r,quantity_min:n})=>({min:n,max:r})):[{min:t,max:t}],Cr=t=>t.reduce((e,r)=>(r.selling_plans.forEach(n=>{const i=`${r.id}-${n.id}`;e[i]=n}),e),{}),kr=t=>Array.isArray(t)?t:[];function de(t){const e=Ir(t.bundle_settings),r=t.variants.reduce((n,i)=>(n[i.id]=i,n),{});return{id:String(t.id),title:t.title,description:t.description||null,handle:t.handle,options:t.options.map(n=>({name:n.name,position:n.position,values:n.values})),default_variant_id:e.default_variant_id,default_selling_plan_id:e.default_selling_plan_id?Number(e.default_selling_plan_id):null,available_for_sale:t.available,requires_selling_plan:t.requires_selling_plan,bundle_settings:{is_customizable:e.is_customizable,price_rule:e.price_rule,customization_window:e.customization_window,max_quantity_per_variant:e.max_quantity_per_variant,collapsible_collections:e.collapsible_collections,show_product_variants:e.show_product_variants,product_details_modal_enabled:e.product_details_modal_enabled,show_variants_as_individual_products:t.bundle_settings.settings.display_variants_as_separate_products_in_list,post_add_to_cart_behavior:e.addToCartBehavior,cross_sells_default_purchase_type:t.bundle_settings.layout_settings.crossSells.defaultPurchaseType??null},variants:t.bundle_settings.variants.filter(({enabled:n})=>n).map((n,i)=>{const s=r[String(n.external_variant_id)];return{id:String(n.external_variant_id),title:s.title,price:s.price,compare_at_price:s.compare_at_price,image:s.image||"",available_for_sale:s.available,options:s.options,requires_selling_plan:s.requires_selling_plan,selling_plan_allocations:s.selling_plan_allocations.map(o=>({price:o.price,compare_at_price:o.compare_at_price,selling_plan:X(o.selling_plan)})),ranges:Er(n),collections:n.option_sources.map(o=>({id:o.option_source_id,source_platform:"shopify",min:o.quantity_min||0,max:o.quantity_max,position:o.position})),default_selections:n.selection_defaults.map(o=>({quantity:o.quantity,product:{id:String(o.product.id),handle:o.handle,title:o.product.title,description:o.product.description,images:o.product.images},variant:{id:o.external_variant_id,title:o.variant.title,featured_image:ce(o.variant.featured_image),sku:o.sku||""}})),position:i}}),selling_plan_groups:t.selling_plan_groups.map(Re),collections:Object.values(t.collections).reduce((n,i)=>(Array.isArray(i.products)&&(n[String(i.id)]={id:String(i.id),title:i.title,handle:i.handle,products:i.products.map(Me)}),n),{}),addons:t.addons.products.length?{collection_id:e.addons?.collection_id||"",collection_handle:e.addons?.collection_handle||"",products:t.addons.products.map(n=>({...Be(n),price_range:{min:n.price,max:n.price},compare_at_price_range:{min:n.compare_at_price||0,max:n.compare_at_price},variants:n.variants.map(i=>({...Ne(i),image:i.image,selling_plan_allocations:i.selling_plan_allocations.map(s=>({price:s.price,compare_at_price:s.compare_at_price,selling_plan:X(s.selling_plan)}))}))}))}:null,cross_sells:t.cross_sells.products.length?{collection_id:e.cross_sells?.collection_id||"",collection_handle:e.cross_sells?.collection_handle||"",products:t.cross_sells.products.map(Me)}:null,incentives:qr(t.incentives),filters:kr(t.filters),templates:t.bundle_settings.layout_settings.templates||null,globalStyles:t.bundle_settings.layout_settings.globalStyles||null}}async function xr(t,e){return e?.source==="shopify_storefront"?Ar():Pr(t,e?.country_code)}async function Pr(t,e){const{appName:r,appVersion:n}=y(),i={"X-Recharge-Sdk-Fn":"loadFromOnlineStore","X-Recharge-Sdk-Version":"2.9.0",...r?{"X-Recharge-Sdk-App-Name":r}:{},...n?{"X-Recharge-Sdk-App-Version":n}:{}};if(!e){const o=await A("get",`/bundle-data/${p(t)}`,{headers:i});return de(o)}const s=new FormData;s.append("form_type","localization"),s.append("_method","put"),s.append("return_to",`${fe}/bundle-data/${t}`),s.append("country_code",e);try{const o=await I("post","/localization",{headers:{"Content-Type":"multipart/form-data",...i},data:s});return de(o)}catch{const o=await A("get",`/bundle-data/${p(t)}`,{headers:i});return de(o)}}async function Ar(t,e){if(!y().storeIdentifier)throw new Error("Store identifier is required for Shopify Storefront API requests");return{}}var Dr=Object.freeze({__proto__:null,loadBundleData:xr});function Tr(t){try{return JSON.parse(t)}catch{return t}}function Or(t){return Object.entries(t).reduce((e,[r,n])=>({...e,[r]:Tr(n)}),{})}const je=t=>typeof t=="string"?t!=="0"&&t!=="false":!!t;function ue(t,e){const r=new Set(e),n={};for(const i of Object.keys(t))r.has(i)||(n[i]=t[i]);return n}function Ue(t){const e=Or(t),r=e.auto_inject===void 0?!0:e.auto_inject,n=e.display_on??[],i=e.first_option==="autodeliver";return{...ue(e,["display_on","first_option"]),auto_inject:r,valid_pages:n,is_subscription_first:i,autoInject:r,validPages:n,isSubscriptionFirst:i}}function Le(t){const e=t.subscription_options?.storefront_purchase_options==="subscription_only";return{...t,is_subscription_only:e,isSubscriptionOnly:e}}function Fr(t){return t.map(e=>{const r={};return Object.entries(e).forEach(([n,i])=>{Object.defineProperty(r,n,{value:Le(i),enumerable:!0,writable:!0,configurable:!0})}),r})}const le="2020-12",Rr={store_currency:{currency_code:"USD",currency_symbol:"$",decimal_separator:".",thousands_separator:",",currency_symbol_location:"left"}},M=new Map;function H(t,e){return M.has(t)||M.set(t,e()),M.get(t)}async function pe(t,e){if(t===void 0||t==="")throw new Error("ID is required");const r=e?.version??"2020-12",{product:n}=await H(`product.${t}.${r}`,()=>j("get",`/product/${r}/${p(t)}.json`));return r==="2020-12"?Le(n):n}async function Ve(){return await H("storeSettings",()=>j("get",`/${le}/store_settings.json`).catch(()=>Rr))}async function ze(){const{widget_settings:t}=await H("widgetSettings",()=>j("get",`/${le}/widget_settings.json`));return Ue(t)}async function Xe(){const{products:t,widget_settings:e,store_settings:r,meta:n}=await H("productsAndSettings",()=>j("get",`/product/${le}/products.json`));return n?.status==="error"?Promise.reject(n.message):{products:Fr(t),widget_settings:Ue(e),store_settings:r??{}}}async function Nr(){const{products:t}=await Xe();return t}async function Br(t){const[e,r,n]=await Promise.all([pe(t),Ve(),ze()]);return{product:e,store_settings:r,widget_settings:n,storeSettings:r,widgetSettings:n}}async function Mr(t){const{bundle_product:e}=await pe(t);return e}async function He(){return Array.from(M.keys()).forEach(t=>M.delete(t))}var jr=Object.freeze({__proto__:null,getCDNBundleSettings:Mr,getCDNProduct:pe,getCDNProductAndSettings:Br,getCDNProducts:Nr,getCDNProductsAndSettings:Xe,getCDNStoreSettings:Ve,getCDNWidgetSettings:ze,resetCDNCache:He});async function Ur(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("get","/charges",{id:e,query:{include:r?.include}},a(t,"getCharge"));return n}function Lr(t,e){return c("get","/charges",{query:e},a(t,"listCharges"))}async function Vr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/charges/${p(e)}/apply_discount`,{data:{discount_code:r}},a(t,"applyDiscountToCharge"));return n}async function zr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{charge:r}=await c("post",`/charges/${p(e)}/remove_discount`,{},a(t,"removeDiscountsFromCharge"));return r}async function Xr(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");if(r===void 0||r.length===0)throw new Error("Purchase item IDs are required");const{charge:i}=await c("post",`/charges/${p(e)}/skip`,{query:n,data:{purchase_item_ids:r.map(s=>Number(s))}},a(t,"skipCharge"));return i}async function Hr(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");if(r===void 0||r.length===0)throw new Error("Purchase item IDs are required");const{charge:i}=await c("post",`/charges/${p(e)}/unskip`,{query:n,data:{purchase_item_ids:r.map(s=>Number(s))}},a(t,"unskipCharge"));return i}async function Wr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{charge:r}=await c("post",`/charges/${p(e)}/process`,{},a(t,"processCharge"));return r}async function Gr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/charges/${p(e)}/change_next_charge_date`,{data:{next_charge_date:r}},a(t,"rescheduleCharge"));return n}var Kr=Object.freeze({__proto__:null,applyDiscountToCharge:Vr,getCharge:Ur,listCharges:Lr,processCharge:Wr,removeDiscountsFromCharge:zr,rescheduleCharge:Gr,skipCharge:Xr,unskipCharge:Hr});async function We(t,e){if(!["2020-12","2022-06"].includes(e.format_version))throw new Error("Missing or unsupported format_version.");return c("get","/product_search",{query:e,headers:{"X-Recharge-Version":"2021-01"}},a(t,"productSearch"))}var Yr=Object.freeze({__proto__:null,productSearch:We});async function Ge(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{collection:r}=await c("get","/collections",{id:e},a(t,"getCollection"));return r}function Jr(t,e){return c("get","/collections",{query:e},a(t,"listCollections"))}async function Qr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");if(!["2020-12","2022-06"].includes(r.format_version))throw new Error("Missing or unsupported format_version.");const n=a(t,"listCollectionProducts"),[{sort_order:i,manual_sort_order:s},{products:o}]=await Promise.all([Ge(n,e),We(n,{...r,collection_ids:[e],limit:250})]);if(i==="manual")return{products:s.reduce((u,h)=>{const _=o.find(f=>f.external_product_id===h);return _&&u.push(_),u},[])};{const u=Zr(i);return{products:o.slice().sort(u)}}}function Ke(t,e){const r=t.external_created_at,n=e.external_created_at;return r<n?-1:n>r?1:0}function Ye(t,e){const r=t.external_product_id,n=e.external_product_id;return r<n?-1:n>r?1:0}function Je(t,e){const r=t.title.toLowerCase(),n=e.title.toLowerCase();return r<n?-1:n>r?1:0}function Zr(t){switch(t){case"created_at-asc":return Ke;case"created_at-desc":return(e,r)=>Ke(r,e);case"id-asc":return Ye;case"id-desc":return(e,r)=>Ye(r,e);case"title-asc":return Je;case"title-desc":return(e,r)=>Je(r,e)}}var en=Object.freeze({__proto__:null,getCollection:Ge,listCollectionProducts:Qr,listCollections:Jr});async function tn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer:n}=await c("get","/customers",{id:r,query:{include:e?.include}},a(t,"getCustomer"));return n}async function Qe(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer:n}=await c("put","/customers",{id:r,data:e},a(t,"updateCustomer"));return n}async function rn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{deliveries:n}=await c("get",`/customers/${p(r)}/delivery_schedule`,{query:e},a(t,"getDeliverySchedule"));return n}async function W(t,e){return c("get","/portal_access",{query:e},a(t,"getCustomerPortalAccess"))}function _e(t){return t.replace(/\/portal\/?$/,"/pages/")}async function nn(t,e,r){if(e===void 0||e==="")throw new Error("Subscription ID is required");const{base_url:n,customer_hash:i,temp_token:s}=await W(a(t,"getActiveChurnLandingPageURL"));return`${_e(n)}${i}/subscriptions/${e}/cancel?token=${s}&subscription=${e}&redirect_to=${encodeURIComponent(r)}`}async function sn(t){const{base_url:e,customer_hash:r,temp_token:n}=await W(a(t,"getFailedPaymentMethodRecoveryLandingPageURL"));return`${_e(e)}account/payment-methods?token=${n}&hash=${r}`}async function on(t,e,r){if(e===void 0||e==="")throw new Error("Gift ID is required");const{base_url:n,customer_hash:i,temp_token:s}=await W(a(t,"getGiftRedemptionLandingPageURL"));return`${_e(n)}${i}/gifts/${e}?token=${s}&redirect_to=${encodeURIComponent(r)}`}const Ze={SHOPIFY_UPDATE_PAYMENT_INFO:{type:"email",template_type:"shopify_update_payment_information"},SHOPIFY_MIGRATE_PAYMENT_INFO:{type:"email",template_type:"shopify_migrate_payment_information"}};async function an(t,e,r){const n=t.customerId;if(!n)throw new Error("Not logged in.");if(!Object.prototype.hasOwnProperty.call(Ze,e))throw new Error("Notification not supported.");const i=Ze[e];return c("post",`/customers/${p(n)}/notifications`,{data:{...i,template_vars:r}},a(t,"sendCustomerNotification"))}async function cn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{credit_summary:n}=await c("get",`/customers/${p(r)}/credit_summary`,{query:{include:e?.include}},a(t,"getCreditSummary"));return n}var dn=Object.freeze({__proto__:null,getActiveChurnLandingPageURL:nn,getCreditSummary:cn,getCustomer:tn,getCustomerPortalAccess:W,getDeliverySchedule:rn,getFailedPaymentMethodRecoveryLandingPageURL:sn,getGiftRedemptionLandingPageURL:on,sendCustomerNotification:an,updateCustomer:Qe});async function un(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{credit_summary:n}=await c("get",`/customers/${p(r)}/credit_summary`,{query:{include:e?.include,presentment_currency_code:e?.presentment_currency_code}},a(t,"getCreditSummary"));return n}function ln(t,{recurring:e}){if(!t.customerId)throw new Error("Not logged in.");const r={};return e!==void 0&&(r.apply_credit_to_next_recurring_charge=e),Qe(a(t,"setApplyCreditsToNextCharge"),r)}async function pn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer_id:n,...i}=e??{};return await c("get","/credit_accounts",{query:{...i,customer_id:r}},a(t,"listCreditAccounts"))}var _n=Object.freeze({__proto__:null,getCreditSummary:un,listCreditAccounts:pn,setApplyCreditsToNextCharge:ln});async function hn(t,e,r){return await c("post","/customer_surveys/cancellation_prevention",{data:{customer_id:e,subscription_id:r}},a(t,"getCustomerSurveyReasons"))}async function mn(t,e,r,n){return await c("post",`/customer_surveys/${p(r)}/customer_response`,{data:{customer_id:e,response_id:n}},a(t,"getCustomerSurveyOffers"))}async function fn(t,e){return await c("post","/offers/claim",{data:e},a(t,"claimOfferCustomerSurvey")),{}}var gn=Object.freeze({__proto__:null,claimOfferCustomerSurvey:fn,getCustomerSurveyOffers:mn,getCustomerSurveyReasons:hn});async function wn(t,e,r,n){if(e===void 0||e==="")throw new Error("Subscription ID is required");return c("post",`/flows/customer_portal_flow/subscription/${p(e)}`,{query:{action:r,flow_id:n?.flow_id},data:{}},a(t,"triggerCustomerPortalFlow"))}var yn=Object.freeze({__proto__:null,triggerCustomerPortalFlow:wn});function bn(t,e){if(!t.customerId)throw new Error("Not logged in.");return c("get","/gift_purchases",{query:e},a(t,"listGiftPurchases"))}async function vn(t,e){if(!t.customerId)throw new Error("Not logged in.");if(e===void 0||e==="")throw new Error("ID is required");const{gift_purchase:r}=await c("get","/gift_purchases",{id:e},a(t,"getGiftPurchase"));return r}var Sn=Object.freeze({__proto__:null,getGiftPurchase:vn,listGiftPurchases:bn});function $n(t,e){return c("get","/incentives/tiered_discounts",{query:e},a(t,"listTieredDiscounts"))}async function In(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{tiered_discount:r}=await c("get",`/incentives/tiered_discounts/${p(e)}`,{},a(t,"getTieredDiscount"));return r}function qn(t,e){return c("post","/incentives/tiered_discounts/offers",{data:e},a(t,"getTieredDiscountOffers"))}var En=Object.freeze({__proto__:null,getTieredDiscount:In,getTieredDiscountOffers:qn,listTieredDiscounts:$n});async function Cn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{membership:r}=await c("get","/memberships",{id:e},a(t,"getMembership"));return r}function kn(t,e){return c("get","/memberships",{query:e},a(t,"listMemberships"))}async function xn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/cancel`,{data:r},a(t,"cancelMembership"));return n}async function Pn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/activate`,{data:r},a(t,"activateMembership"));return n}async function An(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/change`,{data:r},a(t,"changeMembership"));return n}var Dn=Object.freeze({__proto__:null,activateMembership:Pn,cancelMembership:xn,changeMembership:An,getMembership:Cn,listMemberships:kn});async function Tn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership_program:n}=await c("get","/membership_programs",{id:e,query:{include:r?.include}},a(t,"getMembershipProgram"));return n}function On(t,e){return c("get","/membership_programs",{query:e},a(t,"listMembershipPrograms"))}var Fn=Object.freeze({__proto__:null,getMembershipProgram:Tn,listMembershipPrograms:On});async function Rn(t,e){const{metafield:r}=await c("post","/metafields",{data:{metafield:e}},a(t,"createMetafield"));return r}async function Nn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{metafield:n}=await c("put","/metafields",{id:e,data:{metafield:r}},a(t,"updateMetafield"));return n}function Bn(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/metafields",{id:e},a(t,"deleteMetafield"))}var Mn=Object.freeze({__proto__:null,createMetafield:Rn,deleteMetafield:Bn,updateMetafield:Nn});async function jn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{onetime:r}=await c("get","/onetimes",{id:e},a(t,"getOnetime"));return r}function Un(t,e){return c("get","/onetimes",{query:e},a(t,"listOnetimes"))}async function Ln(t,e){const{onetime:r}=await c("post","/onetimes",{data:e},a(t,"createOnetime"));return r}async function Vn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{onetime:n}=await c("put","/onetimes",{id:e,data:r},a(t,"updateOnetime"));return n}function zn(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/onetimes",{id:e},a(t,"deleteOnetime"))}var Xn=Object.freeze({__proto__:null,createOnetime:Ln,deleteOnetime:zn,getOnetime:jn,listOnetimes:Un,updateOnetime:Vn});async function Hn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{order:n}=await c("get","/orders",{id:e,query:{include:r?.include}},a(t,"getOrder"));return n}function Wn(t,e){return c("get","/orders",{query:e},a(t,"listOrders"))}async function Gn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{order:r}=await c("post",`/orders/${p(e)}/delay`,{},a(t,"delayOrder"));return r}var Kn=Object.freeze({__proto__:null,delayOrder:Gn,getOrder:Hn,listOrders:Wn});function Yn(t){try{const e=new URL(t),r=e.hostname==="spreedly.com"||e.hostname.endsWith(".spreedly.com");return e.protocol==="https:"&&r?e:null}catch{return null}}async function Jn(t,e){return typeof window<"u"&&window.Spreedly?Promise.resolve():new Promise((r,n)=>{if(typeof document>"u"){n(new Error("Document is not available. This function must be called in a browser environment."));return}const i=Yn(t);if(!i){n(new Error("Payment iFrame script must be served over https from spreedly.com"));return}const s=Date.now()+3e4;let o;const u=()=>{window.Spreedly?r():Date.now()>=s?n(new Error("Timed out loading payment iFrame script")):o=setTimeout(u,50)};if(Array.from(document.scripts).find(_=>_.src===i.href&&_.integrity===e)){u();return}const h=document.createElement("script");h.src=i.href,h.integrity=e,h.crossOrigin="anonymous",h.addEventListener("error",()=>{clearTimeout(o),n(new Error("Failed to load payment iFrame script"))}),document.head.appendChild(h),u()})}async function Qn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{payment_method:n}=await c("get","/payment_methods",{id:e,query:{include:r?.include}},a(t,"getPaymentMethod"));return n}async function et(t,e){const{payment_method:r}=await c("post","/payment_methods",{data:{...e,customer_id:t.customerId}},a(t,"createPaymentMethod"));return r}async function Zn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{payment_method:n}=await c("put","/payment_methods",{id:e,data:r},a(t,"updatePaymentMethod"));return n}function ei(t,e){return c("get","/payment_methods",{query:e},a(t,"listPaymentMethods"))}async function ti(t,e){const r=await ri(t,e),n=r.external.environment_key,i=r.payment_method_intent_id,s=r.external_customer_id.ecommerce,o=r.external.resource_url,u=r.external.integrity_hash,h=r.payment_method?.processor_payment_method_token;await Jn(o,u);let _=!1,f=null,b=null,v=null;return{mount(d,m){if(typeof window>"u"||!window.Spreedly)throw new Error("Payment script failed to load");window.Spreedly.init(n,{numberEl:d.numberElementId,cvvEl:d.cvvElementId}),window.Spreedly.on("ready",()=>{_=!0,d.styles&&(window.Spreedly.setStyle("number",d.styles),window.Spreedly.setStyle("cvv",d.styles)),d.numberLabel&&window.Spreedly.setLabel("number",d.numberLabel),d.cvvLabel&&window.Spreedly.setLabel("cvv",d.cvvLabel),d.numberPlaceholder&&window.Spreedly.setPlaceholder("number",d.numberPlaceholder),d.cvvPlaceholder&&window.Spreedly.setPlaceholder("cvv",d.cvvPlaceholder),d.numberFormat==="plainFormat"?(d.numberFieldType&&window.Spreedly.setFieldType("number",d.numberFieldType),d.cvvFieldType&&window.Spreedly.setFieldType("cvv",d.cvvFieldType),window.Spreedly.setNumberFormat("plainFormat")):d.numberFormat==="maskedFormat"?(window.Spreedly.setFieldType("cvv","text"),window.Spreedly.setFieldType("number","text"),window.Spreedly.setNumberFormat("maskedFormat")):d.numberFormat==="prettyFormat"?(d.numberFieldType==="text"||d.numberFieldType==="tel"?window.Spreedly.setFieldType("number",d.numberFieldType):window.Spreedly.setFieldType("number","tel"),d.cvvFieldType==="text"||d.cvvFieldType==="tel"?window.Spreedly.setFieldType("cvv",d.cvvFieldType):window.Spreedly.setFieldType("cvv","tel"),window.Spreedly.setNumberFormat("prettyFormat")):(d.numberFieldType&&window.Spreedly.setFieldType("number",d.numberFieldType),d.cvvFieldType&&window.Spreedly.setFieldType("cvv",d.cvvFieldType)),m?.onReady?.()}),window.Spreedly.on("fieldEvent",(w,C,k,T)=>{m?.onFieldEvent?.(w,C,k,T)}),window.Spreedly.on("errors",w=>{m?.onErrors?.(w)}),window.Spreedly.on("paymentMethod",(w,C)=>{f=w,m?.onPaymentMethod?.(w,C),b&&(f=null,b(w),b=null)})},tokenize(d){if(!_||!window.Spreedly)throw new Error("Payment form is not initialized");let m=String(d.year);m.length===2&&(m=`20${m}`);const w=String(d.month).padStart(2,"0");"full_name"in d?window.Spreedly.tokenizeCreditCard({full_name:d.full_name,month:w,year:m}):window.Spreedly.tokenizeCreditCard({first_name:d.first_name,last_name:d.last_name,month:w,year:m})},async submit(d){if(!_)throw new Error("Payment form is not initialized");if(f){const m=f;return f=null,tt(t,m,d,{external_payment_method_id:h,payment_method_intent_id:i,external_customer_id:s})}return new Promise((m,w)=>{v=d,b=async C=>{try{const k=await tt(t,C,v,{external_payment_method_id:h,payment_method_intent_id:i,external_customer_id:s});m(k)}catch(k){w(k)}finally{v=null}},this.tokenize(d.card_details)})},reset(){window.Spreedly&&window.Spreedly.reload(),f=null,b=null,v=null},unmount(){window.Spreedly&&window.Spreedly.removeHandlers(),_=!1,f=null,b=null,v=null},addEventHandlers(d){d.onReady&&window.Spreedly.on("ready",d.onReady),d.onFieldEvent&&window.Spreedly.on("fieldEvent",d.onFieldEvent),d.onErrors&&window.Spreedly.on("errors",d.onErrors),d.onPaymentMethod&&window.Spreedly.on("paymentMethod",d.onPaymentMethod)},removeHandlers(){window.Spreedly&&window.Spreedly.removeHandlers()},setFieldType(d,m){window.Spreedly.setFieldType(d,m)},setLabel(d,m){window.Spreedly.setLabel(d,m)},setNumberFormat(d){window.Spreedly.setNumberFormat(d)},setPlaceholder(d,m){window.Spreedly.setPlaceholder(d,m)},setStyle(d,m){window.Spreedly.setStyle(d,m)}}}async function ri(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");return await c("post","/payment_method_intents",{data:{customer_id:r,payment_method_id:e}},a(t,"createFrictionlessPaymentIntentV1"))}async function tt(t,e,{billing_address:r,default_payment_method:n,address_ids:i,apply_to_all_subscription_addresses:s},{external_payment_method_id:o,payment_method_intent_id:u,external_customer_id:h}){return await et(a(t,"submitFrictionlessPaymentMethodV1"),{default:n??!1,payment_type:"CREDIT_CARD",processor_customer_token:h.toString(),processor_name:"frictionless",processor_payment_method_token:e,billing_address:r,payment_method_intent_id:u,address_ids:i,external_payment_method_id:o,apply_to_all_subscription_addresses:s})}var ni=Object.freeze({__proto__:null,createPaymentMethod:et,getPaymentMethod:Qn,initFrictionlessPaymentV1:ti,listPaymentMethods:ei,updatePaymentMethod:Zn});async function ii(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{plan:r}=await c("get","/plans",{id:e},a(t,"getPlan"));return r}function si(t,e){return c("get","/plans",{query:e},a(t,"listPlans"))}var oi=Object.freeze({__proto__:null,getPlan:ii,listPlans:si});async function ai(t,e){return await c("get","/shop/shipping_countries",{query:e,headers:{"X-Recharge-Version":"2021-01"}},a(t,"getShippingCountries"))}async function ci(t){return await c("get","/shop/settings",{headers:{"X-Recharge-Version":"2021-01"}},a(t,"getStoreSettings"))}var di=Object.freeze({__proto__:null,getShippingCountries:ai,getStoreSettings:ci});function ui(t,e){return{...ue(e,["address_id","external_variant_id","external_product_id","charge_interval_frequency","order_interval_frequency","price","status"]),customer_id:parseInt(t,10),shopify_variant_id:e.external_variant_id.ecommerce?parseInt(e.external_variant_id.ecommerce,10):void 0,...e.charge_interval_frequency?{charge_interval_frequency:`${e.charge_interval_frequency}`}:{},...e.order_interval_frequency?{order_interval_frequency:`${e.order_interval_frequency}`}:{},status:e.status?e.status.toUpperCase():void 0}}function li(t,e){return{...ue(e,["external_variant_id","external_product_id","charge_interval_frequency","order_interval_frequency","price","use_external_variant_defaults"]),shopify_variant_id:e.external_variant_id?.ecommerce?parseInt(e.external_variant_id.ecommerce,10):void 0,...e.charge_interval_frequency?{charge_interval_frequency:`${e.charge_interval_frequency}`}:void 0,...e.order_interval_frequency?{order_interval_frequency:`${e.order_interval_frequency}`}:void 0,force_update:t}}function rt(t){const{id:e,address_id:r,customer_id:n,analytics_data:i,cancellation_reason:s,cancellation_reason_comments:o,cancelled_at:u,charge_interval_frequency:h,created_at:_,expire_after_specific_number_of_charges:f,shopify_product_id:b,shopify_variant_id:v,has_queued_charges:d,is_prepaid:m,is_skippable:w,is_swappable:C,max_retries_reached:k,next_charge_scheduled_at:T,order_day_of_month:G,order_day_of_week:P,order_interval_frequency:he,order_interval_unit:K,presentment_currency:Y,price:Ai,product_title:Di,properties:Ti,quantity:Oi,sku:Fi,sku_override:Ri,status:Ni,updated_at:Bi,variant_title:Mi}=t;return{id:e,address_id:r,customer_id:n,analytics_data:i,cancellation_reason:s,cancellation_reason_comments:o,cancelled_at:u,charge_interval_frequency:parseInt(h,10),created_at:_,expire_after_specific_number_of_charges:f,external_product_id:{ecommerce:`${b}`},external_variant_id:{ecommerce:`${v}`},has_queued_charges:je(d),is_prepaid:m,is_skippable:w,is_swappable:C,max_retries_reached:je(k),next_charge_scheduled_at:T,order_day_of_month:G,order_day_of_week:P,order_interval_frequency:parseInt(he,10),order_interval_unit:K,presentment_currency:Y,price:`${Ai}`,product_title:Di??"",properties:Ti,quantity:Oi,sku:Fi,sku_override:Ri,status:Ni.toLowerCase(),updated_at:Bi,variant_title:Mi}}async function pi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("get","/subscriptions",{id:e,query:{include:r?.include}},a(t,"getSubscription"));return n}function _i(t,e){return c("get","/subscriptions",{query:e},a(t,"listSubscriptions"))}function hi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");return c("get",`/subscriptions/${p(e)}/addons`,{query:r},a(t,"listSubscriptionAddons"))}async function mi(t,e,r){const{subscription:n}=await c("post","/subscriptions",{data:e,query:r},a(t,"createSubscription"));return n}async function fi(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("put","/subscriptions",{id:e,data:r,query:n},a(t,"updateSubscription"));return i}async function gi(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("post",`/subscriptions/${p(e)}/set_next_charge_date`,{data:{date:r},query:n},a(t,"updateSubscriptionChargeDate"));return i}async function wi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/change_address`,{data:{address_id:r}},a(t,"updateSubscriptionAddress"));return n}async function yi(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("post",`/subscriptions/${p(e)}/cancel`,{data:r,query:n},a(t,"cancelSubscription"));return i}async function bi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/activate`,{query:r},a(t,"activateSubscription"));return n}async function vi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/subscriptions/${p(e)}/charges/skip`,{data:{date:r,subscription_id:`${e}`}},a(t,"skipSubscriptionCharge"));return n}async function Si(t,e,r={}){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/pricing_preview`,{data:r},a(t,"getSubscriptionPricingPreview"));return n}async function $i(t,e,r){if(e===void 0||e.length===0)throw new Error("Subscription IDs are required");const{onetimes:n}=await c("post","/purchase_items/skip_gift",{data:{purchase_item_ids:e.map(Number),recipient_address:r}},a(t,"skipGiftSubscriptionCharge"));return n}async function Ii(t,e,r){const n=e.length;if(n<1||n>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:i}=t;if(!i)throw new Error("No customerId in session.");const s=e[0].address_id;if(!e.every(_=>_.address_id===s))throw new Error("All subscriptions must have the same address_id.");const o=e.map(_=>ui(i,_));let u;r?.allow_onetimes!==void 0&&(u={allow_onetimes:r.allow_onetimes});const{subscriptions:h}=await c("post",`/addresses/${p(s)}/subscriptions-bulk`,{data:{subscriptions:o,commit_update:!!r?.commit},headers:{"X-Recharge-Version":"2021-01"},query:u},a(t,"createSubscriptions"));return h.map(rt)}async function qi(t,e,r,n){if(e===void 0||e==="")throw new Error("Address ID is required");const i=r.length;if(i<1||i>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:s}=t;if(!s)throw new Error("No customerId in session.");const o=!!n?.force_update,u=r.map(f=>li(o,f));let h;n?.allow_onetimes!==void 0&&(h={allow_onetimes:n.allow_onetimes});const{subscriptions:_}=await c("put",`/addresses/${p(e)}/subscriptions-bulk`,{data:{subscriptions:u,commit_update:!!n?.commit},headers:{"X-Recharge-Version":"2021-01"},query:h},a(t,"updateSubscriptions"));return _.map(rt)}async function Ei(t,e,r,n){if(e===void 0||e==="")throw new Error("Address ID is required");const i=r.length;if(i<1||i>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:s}=t;if(!s)throw new Error("No customerId in session.");let o;n?.allow_onetimes!==void 0&&(o={allow_onetimes:n.allow_onetimes}),await c("delete",`/addresses/${p(e)}/subscriptions-bulk`,{data:{subscriptions:r,send_email:!!n?.send_email,commit_update:!!n?.commit},headers:{"X-Recharge-Version":"2021-01"},query:o},a(t,"deleteSubscriptions"))}var Ci=Object.freeze({__proto__:null,activateSubscription:bi,cancelSubscription:yi,createSubscription:mi,createSubscriptions:Ii,deleteSubscriptions:Ei,getSubscription:pi,getSubscriptionPricingPreview:Si,listSubscriptionAddons:hi,listSubscriptions:_i,skipGiftSubscriptionCharge:$i,skipSubscriptionCharge:vi,updateSubscription:fi,updateSubscriptionAddress:wi,updateSubscriptionChargeDate:gi,updateSubscriptions:qi});const ki={get(t,e){return I("get",t,e)},post(t,e){return I("post",t,e)},put(t,e){return I("put",t,e)},delete(t,e){return I("delete",t,e)}};function xi(t){if(t)return t;if(window?.Shopify?.shop)return window.Shopify.shop;let e=window?.domain;if(!e){const r=location?.href.match(/(?:http[s]*:\/\/)*(.*?)\.(?=admin\.rechargeapps\.com)/i)?.[1].replace(/-sp$/,"");r&&(e=`${r}.myshopify.com`)}if(e)return e;throw new Error("No storeIdentifier was passed into init.")}function Pi(t={}){const e=t,{storefrontAccessToken:r}=t;if(r&&!r.startsWith("strfnt"))throw new Error("Incorrect storefront access token used. See https://storefront.rechargepayments.com/client/docs/getting_started/package_setup/#initialization-- for more information.");it({storeIdentifier:xi(t.storeIdentifier),loginRetryFn:t.loginRetryFn,__unstable_twoFactorRetryFn:t.__unstable_twoFactorRetryFn,storefrontAccessToken:r,appName:t.appName,appVersion:t.appVersion,environment:e.environment?e.environment:"prod",environmentUri:e.environmentUri,customerHash:e.customerHash}),He()}const nt={init:Pi,api:ki,address:bt,auth:At,bundle:$r,bundleData:Dr,charge:Kr,cdn:jr,collection:en,credit:_n,customer:dn,customerSurveys:gn,flow:yn,gift:Sn,tieredDiscount:En,membership:Dn,membershipProgram:Fn,metafield:Mn,onetime:Xn,order:Kn,paymentMethod:ni,plan:oi,product:Yr,store:di,subscription:Ci};try{nt.init()}catch{}return nt}));
|
|
1
|
+
// recharge-client-2.10.0.min.js | MIT License | © Recharge Inc.
|
|
2
|
+
(function(O,D){typeof exports=="object"&&typeof module<"u"?module.exports=D():typeof define=="function"&&define.amd?define(D):(O=typeof globalThis<"u"?globalThis:O||self,O.recharge=D())})(this,(function(){"use strict";const O="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";function D(t=21){let e="";for(let r=0;r<t;r++)e+=O[Math.random()*64|0];return e}let me={storeIdentifier:"",environment:"prod"};function it(t){me=t}function y(){return me}const st=(t,e="")=>{switch(t){case"prod":return"https://api.rechargeapps.com";case"stage":return"https://api.stage.rechargeapps.com";case"preprod":case"prestage":return`${e}/api`}},ot=(t,e="")=>{switch(t){case"prod":return"https://admin.rechargeapps.com";case"stage":return"https://admin.stage.rechargeapps.com";case"preprod":case"prestage":return e}},at=t=>{switch(t){case"prod":case"preprod":return"https://static.rechargecdn.com";case"stage":case"prestage":return"https://static.stage.rechargecdn.com"}},fe="/tools/recurring";class F{constructor(e,r){this.name="RechargeRequestError",this.message=e,this.status=r}}function p(t){return encodeURIComponent(`${t}`.trim())}function ct(t){const e=r=>encodeURIComponent(r===null?"":String(r));return Object.entries(t).filter(([,r])=>r!==void 0&&!(Array.isArray(r)&&r.length===0)).map(([r,n])=>`${r}=${Array.isArray(n)?n.map(e).join(","):e(n)}`).join("&")}const dt=new Set(["shop_url"]),ge=new WeakMap;let J=0;function ut(t){let e=ge.get(t);return e||(e={},ge.set(t,e)),e}function lt(t,e,r){const n=ut(t);return n.inFlight?n.inFlight:n.latest&&n.latest.generation>r?Promise.resolve(n.latest.session):(n.inFlight=t().then(i=>(i&&i.apiToken!==e&&(J+=1,n.latest={session:i,generation:J}),i)).finally(()=>{n.inFlight=void 0}),n.inFlight)}function a(t,e){return{...t,internalFnCall:t.internalFnCall??e,internalRequestId:t.internalRequestId??D()}}async function j(t,e,r={}){const n=y();return I(t,`${at(n.environment)}/store/${n.storeIdentifier}${e}`,r)}async function c(t,e,{id:r,query:n,data:i,headers:s}={},o){const{environment:u,environmentUri:h,storeIdentifier:_,loginRetryFn:f,__unstable_twoFactorRetryFn:b,appName:v,appVersion:d}=y();if(!_)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const m=o.apiToken;if(!m)throw new Error("No API token defined on session.");const w=J,C=st(u,h),k={"X-Recharge-Access-Token":m,"X-Recharge-Version":"2021-11","X-Recharge-Sdk-Fn":o.internalFnCall,...v?{"X-Recharge-Sdk-App-Name":v}:{},...d?{"X-Recharge-Sdk-App-Version":d}:{},"X-Recharge-Sdk-Version":"2.10.0","X-Request-Id":o.internalRequestId,...o.tmp_fn_identifier?{"X-Recharge-Sdk-Fn-Identifier":o.tmp_fn_identifier}:{},...s||{}},T=n,G={...T?Object.fromEntries(Object.entries(T).filter(([P])=>!dt.has(P))):void 0,shop_url:_};try{return await I(t,`${C}${e}`,{id:r,query:G,data:i,headers:k})}catch(P){const he={401:f,423:b},K=P instanceof F&&P.status?he[P.status]:void 0;if(!K)throw P;const Y=await lt(K,m,w);if(!Y)throw P;return I(t,`${C}${e}`,{id:r,query:G,data:i,headers:{...k,"X-Recharge-Access-Token":Y.apiToken}})}}async function A(t,e,r={}){return I(t,`${fe}${e}`,r)}async function I(t,e,{id:r,query:n,data:i,headers:s}={}){let o=e.trim();if(r&&(o=[o,p(r)].join("/")),n){let b;[o,b]=o.split("?");const v=[b,ct(n)].join("&").replace(/^&/,"");o=`${o}${v?`?${v}`:""}`}let u;i&&t!=="get"&&(u=JSON.stringify(i));const h={Accept:"application/json","Content-Type":"application/json","X-Recharge-App":"storefront-client",...s||{}},_=await fetch(o,{method:t,headers:h,body:u});let f;try{f=await _.json()}catch{}if(!_.ok)throw _.status===502||_.status===504?new F("A gateway error occurred while making the request",_.status):f&&f.error?new F(f.error,_.status):f&&f.errors?new F(JSON.stringify(f.errors),_.status):new F("A connection error occurred while making the request");return f}function pt(t,e){return c("get","/addresses",{query:e},a(t,"listAddresses"))}async function _t(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{address:n}=await c("get","/addresses",{id:e,query:{include:r?.include}},a(t,"getAddress"));return n}async function ht(t,e){const{address:r}=await c("post","/addresses",{data:{...e,customer_id:t.customerId?Number(t.customerId):void 0}},a(t,"createAddress"));return r}async function Q(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{address:i}=await c("put","/addresses",{id:e,data:r,query:n},a(t,"updateAddress"));return i}async function mt(t,e,r,n){return Q(a(t,"applyDiscountToAddress"),e,{discounts:[{code:r}]},n)}async function ft(t,e,r){if(e===void 0||e==="")throw new Error("Id is required");return Q(a(t,"removeDiscountsFromAddress"),e,{discounts:[]},r)}function gt(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/addresses",{id:e},a(t,"deleteAddress"))}async function wt(t,e){const{address:r}=await c("post","/addresses/merge",{data:e},a(t,"mergeAddresses"));return r}async function yt(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/addresses/${p(e)}/charges/skip`,{data:r},a(t,"skipFutureCharge"));return n}var bt=Object.freeze({__proto__:null,applyDiscountToAddress:mt,createAddress:ht,deleteAddress:gt,getAddress:_t,listAddresses:pt,mergeAddresses:wt,removeDiscountsFromAddress:ft,skipFutureCharge:yt,updateAddress:Q});async function vt(){const{storefrontAccessToken:t}=y(),e={};t&&(e["X-Recharge-Storefront-Access-Token"]=t);const r=await A("get","/access",{headers:e});return{apiToken:r.api_token,customerId:r.customer_id,message:r.message}}async function St(t,e){return we(t,e)}async function we(t,e){if(!t)throw new Error("Shopify storefront token is required");const{storeIdentifier:r}=y();if(!r)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{api_token:n,customer_id:i,message:s}=await R("post","/shopify_storefront_access",{data:{customer_token:e,storefront_token:t,shop_url:r}});return n?{apiToken:n,customerId:i,message:s}:null}async function $t(t){const{storeIdentifier:e}=y();if(!e)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{api_token:r,customer_id:n,message:i}=await R("post","/shopify_customer_account_api_access",{data:{customer_token:t,shop_url:e}});return r?{apiToken:r,customerId:n,message:i}:null}async function It(t,e={}){if(!t)throw new Error("Email is required.");const{storeIdentifier:r}=y();if(!r)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{send_email:n,send_sms:i}=e,s=await R("post","/attempt_login",{data:{email:t,shop:r,...n!==void 0?{send_email:n}:{},...i!==void 0?{send_sms:i}:{}}});if(s.errors)throw new Error(s.errors);return s.session_token}async function qt(t,e={}){if(!t)throw new Error("Email is required.");const{storefrontAccessToken:r}=y(),n={};r&&(n["X-Recharge-Storefront-Access-Token"]=r);const{send_email:i,send_sms:s}=e,o=await A("post","/attempt_login",{data:{email:t,...i!==void 0?{send_email:i}:{},...s!==void 0?{send_sms:s}:{}},headers:n});if(o.errors)throw new Error(o.errors);return o.session_token}async function Et(t,e,r){if(!t)throw new Error("Email is required.");if(!e)throw new Error("Session token is required.");if(!r)throw new Error("Code is required.");const{storeIdentifier:n}=y();if(!n)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const i=await R("post","/validate_login",{data:{code:r,email:t,session_token:e,shop:n}});if(i.errors)throw new Error(i.errors);return{apiToken:i.api_token,customerId:i.customer_id}}async function Ct(t,e,r){if(!t)throw new Error("Email is required.");if(!e)throw new Error("Session token is required.");if(!r)throw new Error("Code is required.");const{storefrontAccessToken:n}=y(),i={};n&&(i["X-Recharge-Storefront-Access-Token"]=n);const s=await A("post","/validate_login",{data:{code:r,email:t,session_token:e},headers:i});if(s.errors)throw new Error(s.errors);return{apiToken:s.api_token,customerId:s.customer_id}}function kt(t){if(window.ReCharge?.token)return window.ReCharge.token;if(!t)return null;try{return window.sessionStorage.getItem(`rc_cp_token:${t}`)}catch{return null}}function xt(){const{customerHash:t}=y(),{pathname:e,search:r}=window.location,n=new URLSearchParams(r),i=e.split("/").filter(Boolean),s=i.findIndex(h=>h==="portal"),o=s!==-1?i[s+1]:t,u=n.get("token")||kt(o);if(!u||!o)throw new Error("Not in context of Recharge Customer Portal or URL did not contain correct params");return{customerHash:o,token:u}}async function Pt(){const{customerHash:t,token:e}=xt(),{storeIdentifier:r}=y(),n=await R("post",`/customers/${p(t)}/access`,{data:{token:e,shop:r}});return{apiToken:n.api_token,customerId:n.customer_id}}async function R(t,e,{id:r,query:n,data:i,headers:s}={}){const{environment:o,environmentUri:u,storefrontAccessToken:h,appName:_,appVersion:f}=y(),b=ot(o,u),v={...h?{"X-Recharge-Storefront-Access-Token":h}:{},..._?{"X-Recharge-Sdk-App-Name":_}:{},...f?{"X-Recharge-Sdk-App-Version":f}:{},"X-Recharge-Sdk-Version":"2.10.0",...s||{}};return I(t,`${b}${e}`,{id:r,query:n,data:i,headers:v})}var At=Object.freeze({__proto__:null,loginCustomerPortal:Pt,loginShopifyApi:St,loginShopifyAppProxy:vt,loginWithShopifyCustomerAccount:$t,loginWithShopifyStorefront:we,sendPasswordlessCode:It,sendPasswordlessCodeAppProxy:qt,validatePasswordlessCode:Et,validatePasswordlessCodeAppProxy:Ct});const ye="XdrError";class l extends Error{constructor(e){super(e),this.name=ye}static[Symbol.hasInstance](e){return e instanceof Error&&e.name===ye}}function be(t){return(4-t%4)%4}function ve(t){if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Se(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new l(`${e}: expected uint32 length`)}function Z(t,e,r,n){if(typeof t!="number"||!Number.isInteger(t)||t<e||t>r)throw new l(`${n}: expected integer in range ${e}..${r}`)}function Dt(t,e,r,n){if(typeof t!="bigint"||t<e||t>r)throw new l(`${n}: expected bigint in range ${e}..${r}`)}function Tt(t,e){if(!(t instanceof Uint8Array))throw new l(`${e}: expected Uint8Array`);try{Uint8Array.prototype.at.call(t,0)}catch{throw new l(`${e}: Uint8Array is detached or out of bounds`)}}function Ot(t,e){if(!Array.isArray(t))throw new l(`${e}: expected array`)}const $e=1500;class Ft{#e=0;#i=0;#t;#n;#s;bytes;constructor(e,r=$e){if(r<0||!Number.isInteger(r))throw new l(`invalid maxDepth ${r}`);if(this.#t=r,!ArrayBuffer.isView(e)||e.BYTES_PER_ELEMENT!==1)throw new TypeError("Reader expects a Uint8Array");this.bytes=Object.getPrototypeOf(e)===Uint8Array.prototype?e:e.byteLength===0?new Uint8Array(0):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),this.#n=this.bytes.buffer?.detached?new DataView(new ArrayBuffer(0)):new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.#s=this.#n.byteLength}#r(e,r){if(this.remaining<e)throw new l(`${r}: incomplete XDR data at offset ${this.#e}, expected ${e} byte(s)`);const n=this.#e;return this.#e+=e,n}get offset(){return this.#e}get remaining(){return this.#s-this.#e}enter(e){if(this.#i+=1,this.#i>this.#t)throw this.#i-=1,new l(`${e}: max recursion depth ${this.#t} exceeded`)}exit(){this.#i-=1}done(e){if(this.remaining!==0)throw new l(`${e}: trailing ${this.remaining} byte(s) after XDR value`)}readBytes(e,r){if(e<0||!Number.isInteger(e))throw new l(`${r}: invalid byte length ${e}`);if(this.remaining<e)throw new l(`${r}: incomplete XDR data at offset ${this.#e}, expected ${e} byte(s)`);const n=this.bytes.slice(this.#e,this.#e+e);if(n.length!==e)throw new l(`${r}: input shrank during decode`);return this.#e+=e,n}skipPadding(e,r){if(e<0||!Number.isInteger(e))throw new l(`${r}: invalid byte length ${e}`);const n=be(e);if(n===0)return;const i=this.#r(n,r);for(let s=0;s<n;s++)if(this.bytes[i+s]!==0)throw this.#e=i,new l(`${r}: non-zero XDR padding`)}readInt32(e){return this.#n.getInt32(this.#r(4,e),!1)}readUint32(e){return this.#n.getUint32(this.#r(4,e),!1)}readBigInt64(e){return this.#n.getBigInt64(this.#r(8,e),!1)}readBigUint64(e){return this.#n.getBigUint64(this.#r(8,e),!1)}readFloat32(e){return this.#n.getFloat32(this.#r(4,e),!1)}readFloat64(e){return this.#n.getFloat64(this.#r(8,e),!1)}}const Rt=8192;class Ie{#e=new Uint8Array(Rt);#i=new DataView(this.#e.buffer);#t=0;#n=0;#s;constructor(e=$e){if(e<0||!Number.isInteger(e))throw new l(`invalid maxDepth ${e}`);this.#s=e}get offset(){return this.#t}enter(e){if(this.#n+=1,this.#n>this.#s)throw this.#n-=1,new l(`${e}: max recursion depth ${this.#s} exceeded`)}exit(){this.#n-=1}writeBytes(e){this.#o(e.length),this.#e.set(e,this.#t),this.#t+=e.length}writePadding(e){const r=be(e);r>0&&(this.#o(r),this.#e.fill(0,this.#t,this.#t+r),this.#t+=r)}writeInt32(e){const r=this.#r(4);this.#i.setInt32(r,e,!1),this.#t+=4}writeUint32(e){const r=this.#r(4);this.#i.setUint32(r,e,!1),this.#t+=4}writeBigInt64(e){const r=this.#r(8);this.#i.setBigInt64(r,e,!1),this.#t+=8}writeBigUint64(e){const r=this.#r(8);this.#i.setBigUint64(r,e,!1),this.#t+=8}writeFloat32(e){const r=this.#r(4);this.#i.setFloat32(r,e,!1),this.#t+=4}writeFloat64(e){const r=this.#r(8);this.#i.setFloat64(r,e,!1),this.#t+=8}#r(e){return this.#o(e),this.#t}toUint8Array(){return this.#e.slice(0,this.#t)}#o(e){const r=this.#t+e;if(r<=this.#e.length)return;let n=this.#e.length;for(;n<r;)n*=2;const i=new Uint8Array(n);i.set(this.#e),this.#e=i,this.#i=new DataView(i.buffer)}}const Nt=4294967295;class x{name;constructor(e=void 0){this.name=e}encode(e,r){const n=new Ie(r?.maxDepth);return this._write(e,n,this.name??this.kind),n.toUint8Array()}decode(e,r){const n=new Ft(e,r?.maxDepth),i=this._read(n,this.name??this.kind);return n.done(this.name??this.kind),i}validateXdr(e,r){try{return this.decode(e,r),!0}catch(n){if(n instanceof l)return!1;throw n}}validate(e){try{const r=new Ie;return this._write(e,r,this.name??this.kind),!0}catch(r){if(r instanceof l)return!1;throw r}}}class Bt extends x{kind="array";element;maxLength;constructor(e,r){super(),Se(r,"array maxLength"),this.element=e,this.maxLength=r}_read(e,r){e.enter(r);try{const n=e.readUint32(r);if(n>this.maxLength)throw new l(`${r}: array length ${n} exceeds maximum ${this.maxLength}`);if(n>e.remaining)throw new l(`${r}: array length ${n} exceeds remaining ${e.remaining} byte(s)`);return jt(e,n,this.element,r)}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(Ot(e,n),e.length>this.maxLength)throw new l(`${n}: array length ${e.length} exceeds maximum ${this.maxLength}`);r.writeUint32(e.length),Ut(e,r,this.element,n)}finally{r.exit()}}}function Mt(t,e){return new Bt(t,e)}function jt(t,e,r,n){const i=[];for(let s=0;s<e;s+=1){const o=t.offset,u=r._read(t,`${n}[${s}]`);if(t.offset===o)throw new l(`${n}[${s}]: element type '${r.name??r.kind}' consumed no input; an array element must encode to at least one byte`);i.push(u)}return i}function Ut(t,e,r,n){let i=0;for(const s of t){const o=e.offset;if(r._write(s,e,`${n}[${i}]`),e.offset===o)throw new l(`${n}[${i}]: element type '${r.name??r.kind}' encoded to zero bytes; an array element must encode to at least one byte`);i+=1}}const Lt=new Set(["__proto__","name","kind","encode","decode","validate","_read","_write","nameByValue"]);class Vt extends x{kind="enum";nameByValue;#e=new Set;constructor(e,r){super(e);const n=new Map;for(const[i,s]of Object.entries(r)){if(Z(s,-2147483648,2147483647,`${e}.${i}`),this.#e.has(s))throw new l(`${e}: duplicate enum value ${s}`);this.#e.add(s),n.set(s,i)}this.nameByValue=n}_read(e,r){const n=e.readInt32(r);if(!this.#e.has(n))throw new l(`${r}: unknown enum value ${n}`);return n}_write(e,r,n){if(typeof e!="number"||!this.#e.has(e))throw new l(`${n}: unknown enum value ${String(e)}`);r.writeInt32(e)}}function zt(t,e){for(const n of Object.getOwnPropertyNames(e))if(Lt.has(n))throw new l(`${t}: enum member name ${n} collides with reserved property`);const r=new Vt(t,e);return Object.assign(r,e)}class Xt extends x{kind="int32";_read(e,r){return e.readInt32(r)}_write(e,r,n){Z(e,-2147483648,2147483647,n),r.writeInt32(e)}}function qe(){return new Xt}class Ht extends x{constructor(e){super(),this.maxLength=e,Se(e,"string maxLength")}maxLength;kind="string";_read(e,r){const n=e.readUint32(r);if(n>this.maxLength)throw new l(`${r}: string byte length ${n} exceeds maximum ${this.maxLength}`);const i=e.readBytes(n,r);return e.skipPadding(n,r),i}_write(e,r,n){if(Tt(e,n),e.length>this.maxLength)throw new l(`${n}: string byte length ${e.length} exceeds maximum ${this.maxLength}`);r.writeUint32(e.length),r.writeBytes(e),r.writePadding(e.length)}}function Wt(t){return new Ht(t)}class Gt extends x{kind="struct";entries;constructor(e,r){if(super(e),Object.getOwnPropertyNames(r).includes("__proto__"))throw new l(`${e}: struct field name '__proto__' is not allowed`);this.entries=Object.entries(r)}_read(e,r){e.enter(r);try{const n={};for(const[i,s]of this.entries)n[i]=s._read(e,`${r}.${i}`);return n}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(!ve(e))throw new l(`${n}: expected plain object`);const i=e;for(const[s,o]of this.entries){if(!Object.prototype.hasOwnProperty.call(i,s))throw new l(`${n}.${s}: missing struct field`);o._write(i[s],r,`${n}.${s}`)}}finally{r.exit()}}}function Ee(t,e){return new Gt(t,e)}class Kt extends x{kind="uint32";_read(e,r){return e.readUint32(r)}_write(e,r,n){Z(e,0,4294967295,n),r.writeUint32(e)}}function Ce(){return new Kt}class Yt extends x{kind="uint64";_read(e,r){return e.readBigUint64(r)}_write(e,r,n){Dt(e,0n,(1n<<64n)-1n,n),r.writeBigUint64(e)}}function U(){return new Yt}const ee="default";class Jt extends x{kind="union";switchOn;cases;defaultArm;switchKey;#e=new Map;constructor(e,r,n,i,s){if(super(e),s==="__proto__")throw new l(`${e}: switchKey '__proto__' is not allowed`);if(this.switchOn=r,this.cases=n,this.defaultArm=i,this.switchKey=s,n.length===0&&i===void 0)throw new l(`${e}: union needs at least one case or a default arm`);const o=new Set;for(const u of n){if(!r.validate(u.discriminant))throw new l(`${e}.${u.name}: case discriminator ${String(u.discriminant)} is not a valid ${r.name??r.kind} value`);if(o.has(u.name))throw new l(`${e}: duplicate union case name ${u.name}`);if(o.add(u.name),this.#e.has(u.discriminant))throw new l(`${e}: duplicate union discriminator ${String(u.discriminant)}`);ke(e,u.name,u.arm,s),this.#e.set(u.discriminant,u)}i!==void 0&&ke(e,ee,i,s)}_read(e,r){e.enter(r);try{const n=this.switchOn._read(e,`${r}.${this.switchKey}`),i=this.#e.get(n),s=i?.arm??this.defaultArm;if(s===void 0)throw new l(`${r}: no case for union discriminator ${String(n)}`);return Zt(n,s,this.switchKey,e,`${r}.${i?.name??ee}`)}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(!ve(e)||!Object.prototype.hasOwnProperty.call(e,this.switchKey))throw new l(`${n}: expected union object with ${this.switchKey} discriminator`);const i=e,s=i[this.switchKey],o=this.#e.get(s),u=o?.arm??this.defaultArm;if(u===void 0)throw new l(`${n}: no case for union discriminator ${String(s)}`);this.switchOn._write(s,r,`${n}.${this.switchKey}`),er(i,u,r,`${n}.${o?.name??ee}`)}finally{r.exit()}}}function Qt(t,e){return{kind:"field",name:t,schema:e}}function te(t,e,r){return{name:t,discriminant:e,arm:r}}function re(t,e){const r=e.switchKey??"type";return new Jt(t,e.switchOn,e.cases,e.defaultArm,r)}function Zt(t,e,r,n,i){const s={};return s[r]=t,L(e)?(s[e.name]=e.schema._read(n,`${i}.${e.name}`),s):(e._read(n,i),s)}function er(t,e,r,n){if(L(e)){if(!Object.prototype.hasOwnProperty.call(t,e.name))throw new l(`${n}.${e.name}: missing union arm payload`);e.schema._write(t[e.name],r,`${n}.${e.name}`);return}e._write(void 0,r,n)}function ke(t,e,r,n){if(L(r)&&r.name===n)throw new l(`${t}.${e}: union arm payload field must not be named ${n}`);if(L(r)&&r.name==="__proto__")throw new l(`${t}.${e}: union arm payload field name '__proto__' is not allowed`)}function L(t){return"schema"in t}class tr extends x{kind="void";_read(){}_write(e,r,n){if(e!==void 0)throw new l(`${n}: expected void`)}}function xe(){return new tr}var Pe=t=>{throw TypeError(t)},ne=(t,e,r)=>e.has(t)||Pe("Cannot "+r),g=(t,e,r)=>(ne(t,e,"read from private field"),e.get(t)),V=(t,e,r)=>e.has(t)?Pe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ie=(t,e,r,n)=>(ne(t,e,"write to private field"),e.set(t,r),r),$=(t,e,r)=>(ne(t,e,"access private method"),r),q,E,N,S,Ae,De,se,B,z;const rr=new TextEncoder,Te={v:0};function nr(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}const oe=zt("EnvelopeType",{envelopeTypeBundle:0}),ir=re("BundleItemExt",{switchOn:qe(),switchKey:"v",cases:[te("v0",0,xe())]}),sr=Ee("BundleItem",{collectionId:U(),productId:U(),variantId:U(),sku:Wt(Nt),quantity:Ce(),ext:ir}),or=re("BundleExt",{switchOn:qe(),switchKey:"v",cases:[te("v0",0,xe())]}),ar=Ee("Bundle",{variantId:U(),items:Mt(sr,500),version:Ce(),ext:or}),cr=re("BundleEnvelope",{switchOn:oe,switchKey:"type",cases:[te("envelopeTypeBundle",oe.envelopeTypeBundle,Qt("v1",ar))]});function dr(t){const e={type:oe.envelopeTypeBundle,v1:{variantId:BigInt(t.variantId.toString()),items:t.items.map(r=>({collectionId:BigInt(r.collectionId.toString()),productId:BigInt(r.productId.toString()),variantId:BigInt(r.variantId.toString()),sku:rr.encode(r.sku||""),quantity:r.quantity,ext:Te})),version:Math.floor(Date.now()/1e3),ext:Te}};return nr(cr.encode(e))}class ur{constructor(e,r){V(this,S),V(this,q),V(this,E),V(this,N),ie(this,q,$(this,S,Ae).call(this,r)),ie(this,N,$(this,S,De).call(this,r)),ie(this,E,e)}isInitialDataValid(){if(!g(this,N))throw"Bundle data does not exist for the given product.";if(!g(this,q))throw"Bundle settings do not exist for the given product.";if(!Array.isArray(g(this,E))||!g(this,E).length)throw"No bundle selection items provided.";return!0}isValidVariant(e){if(!g(this,q)?.variantsSettings[e])throw`The ${e} bundle variant is invalid.`;return!0}isSelectionInVariantRange(e){const r=g(this,E).reduce((i,s)=>i+s.quantity,0),n=g(this,q)?.variantsSettings[e].ranges||[];if(!$(this,S,se).call(this,n,r))throw"The total number of products does not fall within the required variant range.";return!0}areItemsInMaxPerItemBound(){const e=g(this,q)?.bundleSettings.maxPerItem||0,r=g(this,E).filter(({quantity:n})=>n>e);if(e&&r.length)throw`The selected products (${$(this,S,B).call(this,r.map(({externalProductId:n})=>n)).join(", ")}) exceed the maximum limit of ${e} items per product.`;return!0}areSelectedCollectionsValid(e){const r=g(this,q)?.variantsSettings[e]?.optionSources,n=g(this,E).filter(({collectionId:i})=>!r||!$(this,S,z).call(this,r,i));if(n.length)throw`The collections (${$(this,S,B).call(this,n.map(({collectionId:i})=>i)).join(", ")}) are no longer valid for the bundle variant (${e}).`;return!0}areItemsQuantitiesValidForTheCollection(e){const r=g(this,E).reduce((s,o)=>(s[o.collectionId]=o.quantity+(s[o.collectionId]||0),s),Object.create(null)),n=g(this,q)?.variantsSettings[e],i=Object.values(n?.optionSources||{}).filter(s=>{const o=r[s.collectionId]||0;return!$(this,S,se).call(this,[s],o)});if(!n||i.length)throw`The selection exceeds the limits for the collections (${$(this,S,B).call(this,i.map(({collectionId:s})=>s)).join(", ")}).`;return!0}areSelectedProductsValid(e){const r=g(this,q)?.variantsSettings[e]?.optionSources||{},n=Object.values(r).reduce((s,o)=>{const u=g(this,N)?.collections[o.collectionId];return u&&(s[o.collectionId]=u),s},Object.create(null));if(!Object.values(n).length)throw`No collections found for the bundle variant (${e}).`;const i=g(this,E).filter(({externalProductId:s,collectionId:o})=>$(this,S,z).call(this,n,o)?!$(this,S,z).call(this,n[o].products,s):!0);if(i.length)throw`The products (${$(this,S,B).call(this,i.map(({externalProductId:s})=>s)).join(", ")}) are no longer valid for the bundle product.`;return!0}isBundleSelectionValid(e){return this.isInitialDataValid(),this.isValidVariant(e),this.isSelectionInVariantRange(e),this.areItemsInMaxPerItemBound(),this.areSelectedCollectionsValid(e),this.areItemsQuantitiesValidForTheCollection(e),this.areSelectedProductsValid(e),!0}}q=new WeakMap,E=new WeakMap,N=new WeakMap,S=new WeakSet,Ae=function(t){try{const e=t.bundle_settings;return{bundleSettings:{maxPerItem:e.max_quantity_per_variant,isCustomizable:e.is_customizable},variantsSettings:e.variants.reduce((r,n)=>{if(!n.enabled)return r;let i=[{min:n.items_count,max:n.items_count}];return n.items_count||(i=n.ranges.map(({quantity_max:s,quantity_min:o})=>({min:o,max:s}))),r[n.external_variant_id]={externalVariantId:n.external_variant_id,optionSources:n.option_sources.reduce((s,o)=>(s[o.option_source_id]={min:o.quantity_min,max:o.quantity_max,collectionId:o.option_source_id},s),Object.create(null)),ranges:i},r},Object.create(null))}}catch{return null}},De=function(t){try{const e=Object.values(t.collections).reduce((r,n)=>(r[n.id]={...n,products:n.products.reduce((i,s)=>(i[s.id]=s,i),Object.create(null))},r),Object.create(null));return{...t,collections:e}}catch{return null}},se=function(t,e){return!!t.filter(({min:r,max:n})=>{const i=r??e,s=n??e;return i<=e&&e<=s}).length},B=function(t){return Array.from(new Set(t))},z=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};const lr="/bundling-storefront-manager";function Oe(t){return dr({variantId:t.externalVariantId,items:t.selections.map(e=>({collectionId:e.collectionId,productId:e.externalProductId,variantId:e.externalVariantId,quantity:e.quantity,sku:""}))})}async function pr(t){const e=y(),r=await ae(t);if(r!==!0)throw new Error(r);const n=Oe(t);try{const i=await A("post",`${lr}/api/v1/bundles`,{data:{bundle:n},headers:{Origin:`https://${e.storeIdentifier}`}});if(!i.id||i.code!==200)throw new Error(`1: failed generating rb_id: ${JSON.stringify(i)}`);return i.id}catch(i){throw new Error(`2: failed generating rb_id ${i}`)}}async function _r(t,e){const r=await ae(e);if(r!==!0)throw new Error(r);const n=Oe(e);try{const i=await c("post","/bundle_selections/bundle_id",{data:{bundle:n}},a(t,"getBundleSelectionId"));if(!i.id||i.code!==200)throw new Error(`1: failed generating rb_id: ${JSON.stringify(i)}`);return i.id}catch(i){throw new Error(`2: failed generating rb_id ${i}`)}}function hr(t,e){const r=Fe(t);if(r!==!0)throw new Error(`Dynamic Bundle is invalid. ${r}`);const n=`${D(9)}:${t.externalProductId}`;return t.selections.map(i=>{const s={id:i.externalVariantId,quantity:i.quantity,properties:{_rc_bundle:n,_rc_bundle_variant:t.externalVariantId,_rc_bundle_parent:e,_rc_bundle_collection_id:i.collectionId}};return i.sellingPlan?s.selling_plan=i.sellingPlan:i.shippingIntervalFrequency&&(s.properties.shipping_interval_frequency=i.shippingIntervalFrequency,s.properties.shipping_interval_unit_type=i.shippingIntervalUnitType,s.id=`${i.discountedVariantId}`),s})}async function ae(t){try{return t?t.selections.length===0?"No selections defined":!0:"Bundle is not defined"}catch(e){return`Error fetching bundle settings: ${e}`}}async function mr(t){try{const e=await A("get",`/bundle-data/${p(t.externalProductId)}`);return{valid:new ur(t.selections,e).isBundleSelectionValid(t.externalVariantId)}}catch(e){return{valid:!1,error:String(e)}}}const fr={day:["day","days","Days"],days:["day","days","Days"],Days:["day","days","Days"],week:["week","weeks","Weeks"],weeks:["week","weeks","Weeks"],Weeks:["week","weeks","Weeks"],month:["month","months","Months"],months:["month","months","Months"],Months:["month","months","Months"]};function Fe(t){if(!t)return"No bundle defined.";if(t.selections.length===0)return"No selections defined.";const{shippingIntervalFrequency:e,shippingIntervalUnitType:r}=t.selections.find(n=>n.shippingIntervalFrequency||n.shippingIntervalUnitType)||{};if(e||r){if(!e||!r)return"Shipping intervals do not match on selections.";{const n=fr[r];for(let i=0;i<t.selections.length;i++){const{shippingIntervalFrequency:s,shippingIntervalUnitType:o}=t.selections[i];if(s&&s!==e||o&&!n.includes(o))return"Shipping intervals do not match on selections."}}}return!0}async function gr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{bundle_selection:r}=await c("get","/bundle_selections",{id:e},a(t,"getBundleSelection"));return r}function wr(t,e){return c("get","/bundle_selections",{query:e},a(t,"listBundleSelections"))}async function yr(t,e){const{bundle_selection:r}=await c("post","/bundle_selections",{data:e},a(t,"createBundleSelection"));return r}async function br(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{bundle_selection:n}=await c("put","/bundle_selections",{id:e,data:r},a(t,"updateBundleSelection"));return n}function vr(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/bundle_selections",{id:e},a(t,"deleteBundleSelection"))}async function Sr(t,e,r,n){if(e===void 0||e==="")throw new Error("Purchase item ID is required");const{subscription:i}=await c("put","/bundles",{id:e,data:r,query:n},a(t,"updateBundle"));return i}var $r=Object.freeze({__proto__:null,createBundleSelection:yr,deleteBundleSelection:vr,getBundleId:pr,getBundleSelection:gr,getBundleSelectionId:_r,getDynamicBundleItems:hr,listBundleSelections:wr,updateBundle:Sr,updateBundleSelection:br,validateBundle:ae,validateBundleSelection:mr,validateDynamicBundle:Fe});const Ir=t=>{const e=t.layout_settings.addons,r=t.layout_settings.crossSells,n=t.customization_window,i=t.layout_settings?.defaultVariantId??t.default_bundle_variant_id,s=t.layout_settings.defaultFrequency,o=t.layout_settings.addToCartCallback;return{default_variant_id:i?String(i):null,is_customizable:t.is_customizable,price_rule:String(t.price_rule).toUpperCase(),customization_window:n?{active_days:n,disabled_message:t.customization_window_disabled_message||""}:null,addons:e.collectionId?{collection_id:e.collectionId,collection_handle:e.collectionHandle}:null,cross_sells:r.collectionId?{collection_id:e.collectionId,collection_handle:e.collectionHandle}:null,default_selling_plan_id:s||null,collapsible_collections:t.layout_settings.collapsibleSections,max_quantity_per_variant:t.max_quantity_per_variant,show_product_variants:t.layout_settings.showVariants,product_details_modal_enabled:t.layout_settings.learnMoreModal,addToCartBehavior:{type:o.type==="none"?"cart_page":o.type,value:o.value}}},qr=t=>t.tiered_discounts.length===0?null:{tiered_discounts:t.tiered_discounts},X=t=>({id:t.id,name:t.name,options:t.options.map(e=>({name:e.name,value:e.value})),recurring_deliveries:t.recurring_deliveries,price_adjustments:t.price_adjustments.map(({value:e,value_type:r})=>({value:e,value_type:r}))}),Re=t=>({name:t.name,options:t.options.map(e=>({name:e.name,values:e.values})),selling_plans:t.selling_plans.map(X)}),Ne=t=>({id:String(t.id),title:t.title,price:t.price,compare_at_price:t.compare_at_price,options:t.options,available_for_sale:t.available}),ce=t=>t==null||typeof t=="string"?t:"src"in t?t.src:null,Be=t=>({id:String(t.id),title:t.title,description:t.description,available_for_sale:t.available,featured_image:ce(t.featured_image),images:t.images,requires_selling_plan:t.requires_selling_plan,selling_plan_groups:t.selling_plan_groups.map(Re)}),Me=t=>{const e=Cr(t.selling_plan_groups);return{...Be(t),handle:t.handle,tags:t.tags,price_range:{min:t.price_min,max:t.price_max},compare_at_price_range:{min:t.compare_at_price_min,max:t.compare_at_price_max},options:t.options,variants:t.variants.map(r=>({...Ne(r),selling_plan_allocations:r.selling_plan_allocations.map(n=>({price:n.price,compare_at_price:n.compare_at_price,selling_plan:X(e[`${n.selling_plan_group_id}-${n.selling_plan_id}`])})),option1:r.option1,option2:r.option2,option3:r.option3,sku:r.sku||"",requires_shipping:r.requires_shipping,taxable:r.taxable,featured_image:ce(r.featured_image),public_title:r.public_title,requires_selling_plan:r.requires_selling_plan}))}},Er=({items_count:t,ranges:e})=>e.length>0?e.map(({quantity_max:r,quantity_min:n})=>({min:n,max:r})):[{min:t,max:t}],Cr=t=>t.reduce((e,r)=>(r.selling_plans.forEach(n=>{const i=`${r.id}-${n.id}`;e[i]=n}),e),{}),kr=t=>Array.isArray(t)?t:[];function de(t){const e=Ir(t.bundle_settings),r=t.variants.reduce((n,i)=>(n[i.id]=i,n),{});return{id:String(t.id),title:t.title,description:t.description||null,handle:t.handle,options:t.options.map(n=>({name:n.name,position:n.position,values:n.values})),default_variant_id:e.default_variant_id,default_selling_plan_id:e.default_selling_plan_id?Number(e.default_selling_plan_id):null,available_for_sale:t.available,requires_selling_plan:t.requires_selling_plan,bundle_settings:{is_customizable:e.is_customizable,price_rule:e.price_rule,customization_window:e.customization_window,max_quantity_per_variant:e.max_quantity_per_variant,collapsible_collections:e.collapsible_collections,show_product_variants:e.show_product_variants,product_details_modal_enabled:e.product_details_modal_enabled,show_variants_as_individual_products:t.bundle_settings.settings.display_variants_as_separate_products_in_list,post_add_to_cart_behavior:e.addToCartBehavior,cross_sells_default_purchase_type:t.bundle_settings.layout_settings.crossSells.defaultPurchaseType??null},variants:t.bundle_settings.variants.filter(({enabled:n})=>n).map((n,i)=>{const s=r[String(n.external_variant_id)];return{id:String(n.external_variant_id),title:s.title,price:s.price,compare_at_price:s.compare_at_price,image:s.image||"",available_for_sale:s.available,options:s.options,requires_selling_plan:s.requires_selling_plan,selling_plan_allocations:s.selling_plan_allocations.map(o=>({price:o.price,compare_at_price:o.compare_at_price,selling_plan:X(o.selling_plan)})),ranges:Er(n),collections:n.option_sources.map(o=>({id:o.option_source_id,source_platform:"shopify",min:o.quantity_min||0,max:o.quantity_max,position:o.position})),default_selections:n.selection_defaults.map(o=>({quantity:o.quantity,product:{id:String(o.product.id),handle:o.handle,title:o.product.title,description:o.product.description,images:o.product.images},variant:{id:o.external_variant_id,title:o.variant.title,featured_image:ce(o.variant.featured_image),sku:o.sku||""}})),position:i}}),selling_plan_groups:t.selling_plan_groups.map(Re),collections:Object.values(t.collections).reduce((n,i)=>(Array.isArray(i.products)&&(n[String(i.id)]={id:String(i.id),title:i.title,handle:i.handle,products:i.products.map(Me)}),n),{}),addons:t.addons.products.length?{collection_id:e.addons?.collection_id||"",collection_handle:e.addons?.collection_handle||"",products:t.addons.products.map(n=>({...Be(n),price_range:{min:n.price,max:n.price},compare_at_price_range:{min:n.compare_at_price||0,max:n.compare_at_price},variants:n.variants.map(i=>({...Ne(i),image:i.image,selling_plan_allocations:i.selling_plan_allocations.map(s=>({price:s.price,compare_at_price:s.compare_at_price,selling_plan:X(s.selling_plan)}))}))}))}:null,cross_sells:t.cross_sells.products.length?{collection_id:e.cross_sells?.collection_id||"",collection_handle:e.cross_sells?.collection_handle||"",products:t.cross_sells.products.map(Me)}:null,incentives:qr(t.incentives),filters:kr(t.filters),templates:t.bundle_settings.layout_settings.templates||null,globalStyles:t.bundle_settings.layout_settings.globalStyles||null}}async function xr(t,e){return e?.source==="shopify_storefront"?Ar():Pr(t,e?.country_code)}async function Pr(t,e){const{appName:r,appVersion:n}=y(),i={"X-Recharge-Sdk-Fn":"loadFromOnlineStore","X-Recharge-Sdk-Version":"2.10.0",...r?{"X-Recharge-Sdk-App-Name":r}:{},...n?{"X-Recharge-Sdk-App-Version":n}:{}};if(!e){const o=await A("get",`/bundle-data/${p(t)}`,{headers:i});return de(o)}const s=new FormData;s.append("form_type","localization"),s.append("_method","put"),s.append("return_to",`${fe}/bundle-data/${t}`),s.append("country_code",e);try{const o=await I("post","/localization",{headers:{"Content-Type":"multipart/form-data",...i},data:s});return de(o)}catch{const o=await A("get",`/bundle-data/${p(t)}`,{headers:i});return de(o)}}async function Ar(t,e){if(!y().storeIdentifier)throw new Error("Store identifier is required for Shopify Storefront API requests");return{}}var Dr=Object.freeze({__proto__:null,loadBundleData:xr});function Tr(t){try{return JSON.parse(t)}catch{return t}}function Or(t){return Object.entries(t).reduce((e,[r,n])=>({...e,[r]:Tr(n)}),{})}const je=t=>typeof t=="string"?t!=="0"&&t!=="false":!!t;function ue(t,e){const r=new Set(e),n={};for(const i of Object.keys(t))r.has(i)||(n[i]=t[i]);return n}function Ue(t){const e=Or(t),r=e.auto_inject===void 0?!0:e.auto_inject,n=e.display_on??[],i=e.first_option==="autodeliver";return{...ue(e,["display_on","first_option"]),auto_inject:r,valid_pages:n,is_subscription_first:i,autoInject:r,validPages:n,isSubscriptionFirst:i}}function Le(t){const e=t.subscription_options?.storefront_purchase_options==="subscription_only";return{...t,is_subscription_only:e,isSubscriptionOnly:e}}function Fr(t){return t.map(e=>{const r={};return Object.entries(e).forEach(([n,i])=>{Object.defineProperty(r,n,{value:Le(i),enumerable:!0,writable:!0,configurable:!0})}),r})}const le="2020-12",Rr={store_currency:{currency_code:"USD",currency_symbol:"$",decimal_separator:".",thousands_separator:",",currency_symbol_location:"left"}},M=new Map;function H(t,e){return M.has(t)||M.set(t,e()),M.get(t)}async function pe(t,e){if(t===void 0||t==="")throw new Error("ID is required");const r=e?.version??"2020-12",{product:n}=await H(`product.${t}.${r}`,()=>j("get",`/product/${r}/${p(t)}.json`));return r==="2020-12"?Le(n):n}async function Ve(){return await H("storeSettings",()=>j("get",`/${le}/store_settings.json`).catch(()=>Rr))}async function ze(){const{widget_settings:t}=await H("widgetSettings",()=>j("get",`/${le}/widget_settings.json`));return Ue(t)}async function Xe(){const{products:t,widget_settings:e,store_settings:r,meta:n}=await H("productsAndSettings",()=>j("get",`/product/${le}/products.json`));return n?.status==="error"?Promise.reject(n.message):{products:Fr(t),widget_settings:Ue(e),store_settings:r??{}}}async function Nr(){const{products:t}=await Xe();return t}async function Br(t){const[e,r,n]=await Promise.all([pe(t),Ve(),ze()]);return{product:e,store_settings:r,widget_settings:n,storeSettings:r,widgetSettings:n}}async function Mr(t){const{bundle_product:e}=await pe(t);return e}async function He(){return Array.from(M.keys()).forEach(t=>M.delete(t))}var jr=Object.freeze({__proto__:null,getCDNBundleSettings:Mr,getCDNProduct:pe,getCDNProductAndSettings:Br,getCDNProducts:Nr,getCDNProductsAndSettings:Xe,getCDNStoreSettings:Ve,getCDNWidgetSettings:ze,resetCDNCache:He});async function Ur(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("get","/charges",{id:e,query:{include:r?.include}},a(t,"getCharge"));return n}function Lr(t,e){return c("get","/charges",{query:e},a(t,"listCharges"))}async function Vr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/charges/${p(e)}/apply_discount`,{data:{discount_code:r}},a(t,"applyDiscountToCharge"));return n}async function zr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{charge:r}=await c("post",`/charges/${p(e)}/remove_discount`,{},a(t,"removeDiscountsFromCharge"));return r}async function Xr(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");if(r===void 0||r.length===0)throw new Error("Purchase item IDs are required");const{charge:i}=await c("post",`/charges/${p(e)}/skip`,{query:n,data:{purchase_item_ids:r.map(s=>Number(s))}},a(t,"skipCharge"));return i}async function Hr(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");if(r===void 0||r.length===0)throw new Error("Purchase item IDs are required");const{charge:i}=await c("post",`/charges/${p(e)}/unskip`,{query:n,data:{purchase_item_ids:r.map(s=>Number(s))}},a(t,"unskipCharge"));return i}async function Wr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{charge:r}=await c("post",`/charges/${p(e)}/process`,{},a(t,"processCharge"));return r}async function Gr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/charges/${p(e)}/change_next_charge_date`,{data:{next_charge_date:r}},a(t,"rescheduleCharge"));return n}var Kr=Object.freeze({__proto__:null,applyDiscountToCharge:Vr,getCharge:Ur,listCharges:Lr,processCharge:Wr,removeDiscountsFromCharge:zr,rescheduleCharge:Gr,skipCharge:Xr,unskipCharge:Hr});async function We(t,e){if(!["2020-12","2022-06"].includes(e.format_version))throw new Error("Missing or unsupported format_version.");return c("get","/product_search",{query:e,headers:{"X-Recharge-Version":"2021-01"}},a(t,"productSearch"))}var Yr=Object.freeze({__proto__:null,productSearch:We});async function Ge(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{collection:r}=await c("get","/collections",{id:e},a(t,"getCollection"));return r}function Jr(t,e){return c("get","/collections",{query:e},a(t,"listCollections"))}async function Qr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");if(!["2020-12","2022-06"].includes(r.format_version))throw new Error("Missing or unsupported format_version.");const n=a(t,"listCollectionProducts"),[{sort_order:i,manual_sort_order:s},{products:o}]=await Promise.all([Ge(n,e),We(n,{...r,collection_ids:[e],limit:250})]);if(i==="manual")return{products:s.reduce((u,h)=>{const _=o.find(f=>f.external_product_id===h);return _&&u.push(_),u},[])};{const u=Zr(i);return{products:o.slice().sort(u)}}}function Ke(t,e){const r=t.external_created_at,n=e.external_created_at;return r<n?-1:n>r?1:0}function Ye(t,e){const r=t.external_product_id,n=e.external_product_id;return r<n?-1:n>r?1:0}function Je(t,e){const r=t.title.toLowerCase(),n=e.title.toLowerCase();return r<n?-1:n>r?1:0}function Zr(t){switch(t){case"created_at-asc":return Ke;case"created_at-desc":return(e,r)=>Ke(r,e);case"id-asc":return Ye;case"id-desc":return(e,r)=>Ye(r,e);case"title-asc":return Je;case"title-desc":return(e,r)=>Je(r,e)}}var en=Object.freeze({__proto__:null,getCollection:Ge,listCollectionProducts:Qr,listCollections:Jr});async function tn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer:n}=await c("get","/customers",{id:r,query:{include:e?.include}},a(t,"getCustomer"));return n}async function Qe(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer:n}=await c("put","/customers",{id:r,data:e},a(t,"updateCustomer"));return n}async function rn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{deliveries:n}=await c("get",`/customers/${p(r)}/delivery_schedule`,{query:e},a(t,"getDeliverySchedule"));return n}async function W(t,e){return c("get","/portal_access",{query:e},a(t,"getCustomerPortalAccess"))}function _e(t){return t.replace(/\/portal\/?$/,"/pages/")}async function nn(t,e,r){if(e===void 0||e==="")throw new Error("Subscription ID is required");const{base_url:n,customer_hash:i,temp_token:s}=await W(a(t,"getActiveChurnLandingPageURL"));return`${_e(n)}${i}/subscriptions/${e}/cancel?token=${s}&subscription=${e}&redirect_to=${encodeURIComponent(r)}`}async function sn(t){const{base_url:e,customer_hash:r,temp_token:n}=await W(a(t,"getFailedPaymentMethodRecoveryLandingPageURL"));return`${_e(e)}account/payment-methods?token=${n}&hash=${r}`}async function on(t,e,r){if(e===void 0||e==="")throw new Error("Gift ID is required");const{base_url:n,customer_hash:i,temp_token:s}=await W(a(t,"getGiftRedemptionLandingPageURL"));return`${_e(n)}${i}/gifts/${e}?token=${s}&redirect_to=${encodeURIComponent(r)}`}const Ze={SHOPIFY_UPDATE_PAYMENT_INFO:{type:"email",template_type:"shopify_update_payment_information"},SHOPIFY_MIGRATE_PAYMENT_INFO:{type:"email",template_type:"shopify_migrate_payment_information"}};async function an(t,e,r){const n=t.customerId;if(!n)throw new Error("Not logged in.");if(!Object.prototype.hasOwnProperty.call(Ze,e))throw new Error("Notification not supported.");const i=Ze[e];return c("post",`/customers/${p(n)}/notifications`,{data:{...i,template_vars:r}},a(t,"sendCustomerNotification"))}async function cn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{credit_summary:n}=await c("get",`/customers/${p(r)}/credit_summary`,{query:{include:e?.include}},a(t,"getCreditSummary"));return n}var dn=Object.freeze({__proto__:null,getActiveChurnLandingPageURL:nn,getCreditSummary:cn,getCustomer:tn,getCustomerPortalAccess:W,getDeliverySchedule:rn,getFailedPaymentMethodRecoveryLandingPageURL:sn,getGiftRedemptionLandingPageURL:on,sendCustomerNotification:an,updateCustomer:Qe});async function un(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{credit_summary:n}=await c("get",`/customers/${p(r)}/credit_summary`,{query:{include:e?.include,presentment_currency_code:e?.presentment_currency_code}},a(t,"getCreditSummary"));return n}function ln(t,{recurring:e}){if(!t.customerId)throw new Error("Not logged in.");const r={};return e!==void 0&&(r.apply_credit_to_next_recurring_charge=e),Qe(a(t,"setApplyCreditsToNextCharge"),r)}async function pn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer_id:n,...i}=e??{};return await c("get","/credit_accounts",{query:{...i,customer_id:r}},a(t,"listCreditAccounts"))}var _n=Object.freeze({__proto__:null,getCreditSummary:un,listCreditAccounts:pn,setApplyCreditsToNextCharge:ln});async function hn(t,e,r){return await c("post","/customer_surveys/cancellation_prevention",{data:{customer_id:e,subscription_id:r}},a(t,"getCustomerSurveyReasons"))}async function mn(t,e,r,n){return await c("post",`/customer_surveys/${p(r)}/customer_response`,{data:{customer_id:e,response_id:n}},a(t,"getCustomerSurveyOffers"))}async function fn(t,e){return await c("post","/offers/claim",{data:e},a(t,"claimOfferCustomerSurvey")),{}}var gn=Object.freeze({__proto__:null,claimOfferCustomerSurvey:fn,getCustomerSurveyOffers:mn,getCustomerSurveyReasons:hn});async function wn(t,e,r,n){if(e===void 0||e==="")throw new Error("Subscription ID is required");return c("post",`/flows/customer_portal_flow/subscription/${p(e)}`,{query:{action:r,flow_id:n?.flow_id},data:{}},a(t,"triggerCustomerPortalFlow"))}var yn=Object.freeze({__proto__:null,triggerCustomerPortalFlow:wn});function bn(t,e){if(!t.customerId)throw new Error("Not logged in.");return c("get","/gift_purchases",{query:e},a(t,"listGiftPurchases"))}async function vn(t,e){if(!t.customerId)throw new Error("Not logged in.");if(e===void 0||e==="")throw new Error("ID is required");const{gift_purchase:r}=await c("get","/gift_purchases",{id:e},a(t,"getGiftPurchase"));return r}var Sn=Object.freeze({__proto__:null,getGiftPurchase:vn,listGiftPurchases:bn});function $n(t,e){return c("get","/incentives/tiered_discounts",{query:e},a(t,"listTieredDiscounts"))}async function In(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{tiered_discount:r}=await c("get",`/incentives/tiered_discounts/${p(e)}`,{},a(t,"getTieredDiscount"));return r}function qn(t,e){return c("post","/incentives/tiered_discounts/offers",{data:e},a(t,"getTieredDiscountOffers"))}var En=Object.freeze({__proto__:null,getTieredDiscount:In,getTieredDiscountOffers:qn,listTieredDiscounts:$n});async function Cn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{membership:r}=await c("get","/memberships",{id:e},a(t,"getMembership"));return r}function kn(t,e){return c("get","/memberships",{query:e},a(t,"listMemberships"))}async function xn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/cancel`,{data:r},a(t,"cancelMembership"));return n}async function Pn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/activate`,{data:r},a(t,"activateMembership"));return n}async function An(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/change`,{data:r},a(t,"changeMembership"));return n}var Dn=Object.freeze({__proto__:null,activateMembership:Pn,cancelMembership:xn,changeMembership:An,getMembership:Cn,listMemberships:kn});async function Tn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership_program:n}=await c("get","/membership_programs",{id:e,query:{include:r?.include}},a(t,"getMembershipProgram"));return n}function On(t,e){return c("get","/membership_programs",{query:e},a(t,"listMembershipPrograms"))}var Fn=Object.freeze({__proto__:null,getMembershipProgram:Tn,listMembershipPrograms:On});async function Rn(t,e){const{metafield:r}=await c("post","/metafields",{data:{metafield:e}},a(t,"createMetafield"));return r}async function Nn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{metafield:n}=await c("put","/metafields",{id:e,data:{metafield:r}},a(t,"updateMetafield"));return n}function Bn(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/metafields",{id:e},a(t,"deleteMetafield"))}var Mn=Object.freeze({__proto__:null,createMetafield:Rn,deleteMetafield:Bn,updateMetafield:Nn});async function jn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{onetime:r}=await c("get","/onetimes",{id:e},a(t,"getOnetime"));return r}function Un(t,e){return c("get","/onetimes",{query:e},a(t,"listOnetimes"))}async function Ln(t,e){const{onetime:r}=await c("post","/onetimes",{data:e},a(t,"createOnetime"));return r}async function Vn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{onetime:n}=await c("put","/onetimes",{id:e,data:r},a(t,"updateOnetime"));return n}function zn(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/onetimes",{id:e},a(t,"deleteOnetime"))}var Xn=Object.freeze({__proto__:null,createOnetime:Ln,deleteOnetime:zn,getOnetime:jn,listOnetimes:Un,updateOnetime:Vn});async function Hn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{order:n}=await c("get","/orders",{id:e,query:{include:r?.include}},a(t,"getOrder"));return n}function Wn(t,e){return c("get","/orders",{query:e},a(t,"listOrders"))}async function Gn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{order:r}=await c("post",`/orders/${p(e)}/delay`,{},a(t,"delayOrder"));return r}var Kn=Object.freeze({__proto__:null,delayOrder:Gn,getOrder:Hn,listOrders:Wn});function Yn(t){try{const e=new URL(t),r=e.hostname==="spreedly.com"||e.hostname.endsWith(".spreedly.com");return e.protocol==="https:"&&r?e:null}catch{return null}}async function Jn(t,e){return typeof window<"u"&&window.Spreedly?Promise.resolve():new Promise((r,n)=>{if(typeof document>"u"){n(new Error("Document is not available. This function must be called in a browser environment."));return}const i=Yn(t);if(!i){n(new Error("Payment iFrame script must be served over https from spreedly.com"));return}const s=Date.now()+3e4;let o;const u=()=>{window.Spreedly?r():Date.now()>=s?n(new Error("Timed out loading payment iFrame script")):o=setTimeout(u,50)};if(Array.from(document.scripts).find(_=>_.src===i.href&&_.integrity===e)){u();return}const h=document.createElement("script");h.src=i.href,h.integrity=e,h.crossOrigin="anonymous",h.addEventListener("error",()=>{clearTimeout(o),n(new Error("Failed to load payment iFrame script"))}),document.head.appendChild(h),u()})}async function Qn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{payment_method:n}=await c("get","/payment_methods",{id:e,query:{include:r?.include}},a(t,"getPaymentMethod"));return n}async function et(t,e){const{payment_method:r}=await c("post","/payment_methods",{data:{...e,customer_id:t.customerId}},a(t,"createPaymentMethod"));return r}async function Zn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{payment_method:n}=await c("put","/payment_methods",{id:e,data:r},a(t,"updatePaymentMethod"));return n}function ei(t,e){return c("get","/payment_methods",{query:e},a(t,"listPaymentMethods"))}async function ti(t,e){const r=await ri(t,e),n=r.external.environment_key,i=r.payment_method_intent_id,s=r.external_customer_id.ecommerce,o=r.external.resource_url,u=r.external.integrity_hash,h=r.payment_method?.processor_payment_method_token;await Jn(o,u);let _=!1,f=null,b=null,v=null;return{mount(d,m){if(typeof window>"u"||!window.Spreedly)throw new Error("Payment script failed to load");window.Spreedly.init(n,{numberEl:d.numberElementId,cvvEl:d.cvvElementId}),window.Spreedly.on("ready",()=>{_=!0,d.styles&&(window.Spreedly.setStyle("number",d.styles),window.Spreedly.setStyle("cvv",d.styles)),d.numberLabel&&window.Spreedly.setLabel("number",d.numberLabel),d.cvvLabel&&window.Spreedly.setLabel("cvv",d.cvvLabel),d.numberPlaceholder&&window.Spreedly.setPlaceholder("number",d.numberPlaceholder),d.cvvPlaceholder&&window.Spreedly.setPlaceholder("cvv",d.cvvPlaceholder),d.numberFormat==="plainFormat"?(d.numberFieldType&&window.Spreedly.setFieldType("number",d.numberFieldType),d.cvvFieldType&&window.Spreedly.setFieldType("cvv",d.cvvFieldType),window.Spreedly.setNumberFormat("plainFormat")):d.numberFormat==="maskedFormat"?(window.Spreedly.setFieldType("cvv","text"),window.Spreedly.setFieldType("number","text"),window.Spreedly.setNumberFormat("maskedFormat")):d.numberFormat==="prettyFormat"?(d.numberFieldType==="text"||d.numberFieldType==="tel"?window.Spreedly.setFieldType("number",d.numberFieldType):window.Spreedly.setFieldType("number","tel"),d.cvvFieldType==="text"||d.cvvFieldType==="tel"?window.Spreedly.setFieldType("cvv",d.cvvFieldType):window.Spreedly.setFieldType("cvv","tel"),window.Spreedly.setNumberFormat("prettyFormat")):(d.numberFieldType&&window.Spreedly.setFieldType("number",d.numberFieldType),d.cvvFieldType&&window.Spreedly.setFieldType("cvv",d.cvvFieldType)),m?.onReady?.()}),window.Spreedly.on("fieldEvent",(w,C,k,T)=>{m?.onFieldEvent?.(w,C,k,T)}),window.Spreedly.on("errors",w=>{m?.onErrors?.(w)}),window.Spreedly.on("paymentMethod",(w,C)=>{f=w,m?.onPaymentMethod?.(w,C),b&&(f=null,b(w),b=null)})},tokenize(d){if(!_||!window.Spreedly)throw new Error("Payment form is not initialized");let m=String(d.year);m.length===2&&(m=`20${m}`);const w=String(d.month).padStart(2,"0");"full_name"in d?window.Spreedly.tokenizeCreditCard({full_name:d.full_name,month:w,year:m}):window.Spreedly.tokenizeCreditCard({first_name:d.first_name,last_name:d.last_name,month:w,year:m})},async submit(d){if(!_)throw new Error("Payment form is not initialized");if(f){const m=f;return f=null,tt(t,m,d,{external_payment_method_id:h,payment_method_intent_id:i,external_customer_id:s})}return new Promise((m,w)=>{v=d,b=async C=>{try{const k=await tt(t,C,v,{external_payment_method_id:h,payment_method_intent_id:i,external_customer_id:s});m(k)}catch(k){w(k)}finally{v=null}},this.tokenize(d.card_details)})},reset(){window.Spreedly&&window.Spreedly.reload(),f=null,b=null,v=null},unmount(){window.Spreedly&&window.Spreedly.removeHandlers(),_=!1,f=null,b=null,v=null},addEventHandlers(d){d.onReady&&window.Spreedly.on("ready",d.onReady),d.onFieldEvent&&window.Spreedly.on("fieldEvent",d.onFieldEvent),d.onErrors&&window.Spreedly.on("errors",d.onErrors),d.onPaymentMethod&&window.Spreedly.on("paymentMethod",d.onPaymentMethod)},removeHandlers(){window.Spreedly&&window.Spreedly.removeHandlers()},setFieldType(d,m){window.Spreedly.setFieldType(d,m)},setLabel(d,m){window.Spreedly.setLabel(d,m)},setNumberFormat(d){window.Spreedly.setNumberFormat(d)},setPlaceholder(d,m){window.Spreedly.setPlaceholder(d,m)},setStyle(d,m){window.Spreedly.setStyle(d,m)}}}async function ri(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");return await c("post","/payment_method_intents",{data:{customer_id:r,payment_method_id:e}},a(t,"createFrictionlessPaymentIntentV1"))}async function tt(t,e,{billing_address:r,default_payment_method:n,address_ids:i,apply_to_all_subscription_addresses:s},{external_payment_method_id:o,payment_method_intent_id:u,external_customer_id:h}){return await et(a(t,"submitFrictionlessPaymentMethodV1"),{default:n??!1,payment_type:"CREDIT_CARD",processor_customer_token:h.toString(),processor_name:"frictionless",processor_payment_method_token:e,billing_address:r,payment_method_intent_id:u,address_ids:i,external_payment_method_id:o,apply_to_all_subscription_addresses:s})}var ni=Object.freeze({__proto__:null,createPaymentMethod:et,getPaymentMethod:Qn,initFrictionlessPaymentV1:ti,listPaymentMethods:ei,updatePaymentMethod:Zn});async function ii(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{plan:r}=await c("get","/plans",{id:e},a(t,"getPlan"));return r}function si(t,e){return c("get","/plans",{query:e},a(t,"listPlans"))}var oi=Object.freeze({__proto__:null,getPlan:ii,listPlans:si});async function ai(t,e){return await c("get","/shop/shipping_countries",{query:e,headers:{"X-Recharge-Version":"2021-01"}},a(t,"getShippingCountries"))}async function ci(t){return await c("get","/shop/settings",{headers:{"X-Recharge-Version":"2021-01"}},a(t,"getStoreSettings"))}var di=Object.freeze({__proto__:null,getShippingCountries:ai,getStoreSettings:ci});function ui(t,e){return{...ue(e,["address_id","external_variant_id","external_product_id","charge_interval_frequency","order_interval_frequency","price","status"]),customer_id:parseInt(t,10),shopify_variant_id:e.external_variant_id.ecommerce?parseInt(e.external_variant_id.ecommerce,10):void 0,...e.charge_interval_frequency?{charge_interval_frequency:`${e.charge_interval_frequency}`}:{},...e.order_interval_frequency?{order_interval_frequency:`${e.order_interval_frequency}`}:{},status:e.status?e.status.toUpperCase():void 0}}function li(t,e){return{...ue(e,["external_variant_id","external_product_id","charge_interval_frequency","order_interval_frequency","price","use_external_variant_defaults"]),shopify_variant_id:e.external_variant_id?.ecommerce?parseInt(e.external_variant_id.ecommerce,10):void 0,...e.charge_interval_frequency?{charge_interval_frequency:`${e.charge_interval_frequency}`}:void 0,...e.order_interval_frequency?{order_interval_frequency:`${e.order_interval_frequency}`}:void 0,force_update:t}}function rt(t){const{id:e,address_id:r,customer_id:n,analytics_data:i,cancellation_reason:s,cancellation_reason_comments:o,cancelled_at:u,charge_interval_frequency:h,created_at:_,expire_after_specific_number_of_charges:f,shopify_product_id:b,shopify_variant_id:v,has_queued_charges:d,is_prepaid:m,is_skippable:w,is_swappable:C,max_retries_reached:k,next_charge_scheduled_at:T,order_day_of_month:G,order_day_of_week:P,order_interval_frequency:he,order_interval_unit:K,presentment_currency:Y,price:Ai,product_title:Di,properties:Ti,quantity:Oi,sku:Fi,sku_override:Ri,status:Ni,updated_at:Bi,variant_title:Mi}=t;return{id:e,address_id:r,customer_id:n,analytics_data:i,cancellation_reason:s,cancellation_reason_comments:o,cancelled_at:u,charge_interval_frequency:parseInt(h,10),created_at:_,expire_after_specific_number_of_charges:f,external_product_id:{ecommerce:`${b}`},external_variant_id:{ecommerce:`${v}`},has_queued_charges:je(d),is_prepaid:m,is_skippable:w,is_swappable:C,max_retries_reached:je(k),next_charge_scheduled_at:T,order_day_of_month:G,order_day_of_week:P,order_interval_frequency:parseInt(he,10),order_interval_unit:K,presentment_currency:Y,price:`${Ai}`,product_title:Di??"",properties:Ti,quantity:Oi,sku:Fi,sku_override:Ri,status:Ni.toLowerCase(),updated_at:Bi,variant_title:Mi}}async function pi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("get","/subscriptions",{id:e,query:{include:r?.include}},a(t,"getSubscription"));return n}function _i(t,e){return c("get","/subscriptions",{query:e},a(t,"listSubscriptions"))}function hi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");return c("get",`/subscriptions/${p(e)}/addons`,{query:r},a(t,"listSubscriptionAddons"))}async function mi(t,e,r){const{subscription:n}=await c("post","/subscriptions",{data:e,query:r},a(t,"createSubscription"));return n}async function fi(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("put","/subscriptions",{id:e,data:r,query:n},a(t,"updateSubscription"));return i}async function gi(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("post",`/subscriptions/${p(e)}/set_next_charge_date`,{data:{date:r},query:n},a(t,"updateSubscriptionChargeDate"));return i}async function wi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/change_address`,{data:{address_id:r}},a(t,"updateSubscriptionAddress"));return n}async function yi(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("post",`/subscriptions/${p(e)}/cancel`,{data:r,query:n},a(t,"cancelSubscription"));return i}async function bi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/activate`,{query:r},a(t,"activateSubscription"));return n}async function vi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/subscriptions/${p(e)}/charges/skip`,{data:{date:r,subscription_id:`${e}`}},a(t,"skipSubscriptionCharge"));return n}async function Si(t,e,r={}){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/pricing_preview`,{data:r},a(t,"getSubscriptionPricingPreview"));return n}async function $i(t,e,r){if(e===void 0||e.length===0)throw new Error("Subscription IDs are required");const{onetimes:n}=await c("post","/purchase_items/skip_gift",{data:{purchase_item_ids:e.map(Number),recipient_address:r}},a(t,"skipGiftSubscriptionCharge"));return n}async function Ii(t,e,r){const n=e.length;if(n<1||n>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:i}=t;if(!i)throw new Error("No customerId in session.");const s=e[0].address_id;if(!e.every(_=>_.address_id===s))throw new Error("All subscriptions must have the same address_id.");const o=e.map(_=>ui(i,_));let u;r?.allow_onetimes!==void 0&&(u={allow_onetimes:r.allow_onetimes});const{subscriptions:h}=await c("post",`/addresses/${p(s)}/subscriptions-bulk`,{data:{subscriptions:o,commit_update:!!r?.commit},headers:{"X-Recharge-Version":"2021-01"},query:u},a(t,"createSubscriptions"));return h.map(rt)}async function qi(t,e,r,n){if(e===void 0||e==="")throw new Error("Address ID is required");const i=r.length;if(i<1||i>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:s}=t;if(!s)throw new Error("No customerId in session.");const o=!!n?.force_update,u=r.map(f=>li(o,f));let h;n?.allow_onetimes!==void 0&&(h={allow_onetimes:n.allow_onetimes});const{subscriptions:_}=await c("put",`/addresses/${p(e)}/subscriptions-bulk`,{data:{subscriptions:u,commit_update:!!n?.commit},headers:{"X-Recharge-Version":"2021-01"},query:h},a(t,"updateSubscriptions"));return _.map(rt)}async function Ei(t,e,r,n){if(e===void 0||e==="")throw new Error("Address ID is required");const i=r.length;if(i<1||i>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:s}=t;if(!s)throw new Error("No customerId in session.");let o;n?.allow_onetimes!==void 0&&(o={allow_onetimes:n.allow_onetimes}),await c("delete",`/addresses/${p(e)}/subscriptions-bulk`,{data:{subscriptions:r,send_email:!!n?.send_email,commit_update:!!n?.commit},headers:{"X-Recharge-Version":"2021-01"},query:o},a(t,"deleteSubscriptions"))}var Ci=Object.freeze({__proto__:null,activateSubscription:bi,cancelSubscription:yi,createSubscription:mi,createSubscriptions:Ii,deleteSubscriptions:Ei,getSubscription:pi,getSubscriptionPricingPreview:Si,listSubscriptionAddons:hi,listSubscriptions:_i,skipGiftSubscriptionCharge:$i,skipSubscriptionCharge:vi,updateSubscription:fi,updateSubscriptionAddress:wi,updateSubscriptionChargeDate:gi,updateSubscriptions:qi});const ki={get(t,e){return I("get",t,e)},post(t,e){return I("post",t,e)},put(t,e){return I("put",t,e)},delete(t,e){return I("delete",t,e)}};function xi(t){if(t)return t;if(window?.Shopify?.shop)return window.Shopify.shop;let e=window?.domain;if(!e){const r=location?.href.match(/(?:http[s]*:\/\/)*(.*?)\.(?=admin\.rechargeapps\.com)/i)?.[1].replace(/-sp$/,"");r&&(e=`${r}.myshopify.com`)}if(e)return e;throw new Error("No storeIdentifier was passed into init.")}function Pi(t={}){const e=t,{storefrontAccessToken:r}=t;if(r&&!r.startsWith("strfnt"))throw new Error("Incorrect storefront access token used. See https://storefront.rechargepayments.com/client/docs/getting_started/package_setup/#initialization-- for more information.");it({storeIdentifier:xi(t.storeIdentifier),loginRetryFn:t.loginRetryFn,__unstable_twoFactorRetryFn:t.__unstable_twoFactorRetryFn,storefrontAccessToken:r,appName:t.appName,appVersion:t.appVersion,environment:e.environment?e.environment:"prod",environmentUri:e.environmentUri,customerHash:e.customerHash}),He()}const nt={init:Pi,api:ki,address:bt,auth:At,bundle:$r,bundleData:Dr,charge:Kr,cdn:jr,collection:en,credit:_n,customer:dn,customerSurveys:gn,flow:yn,gift:Sn,tieredDiscount:En,membership:Dn,membershipProgram:Fn,metafield:Mn,onetime:Xn,order:Kn,paymentMethod:ni,plan:oi,product:Yr,store:di,subscription:Ci};try{nt.init()}catch{}return nt}));
|