@rechargeapps/storefront-client 0.26.0 → 0.28.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Storefront client
1
+ # Recharge JS-SDK
2
2
 
3
- Recharge Storefront client
3
+ Recharge JavaScript SDK
4
4
 
5
5
  ## Install
6
6
 
@@ -24,45 +24,6 @@ npm install @rechargeapps/storefront-client
24
24
  yarn add @rechargeapps/storefront-client
25
25
  ```
26
26
 
27
- ## Init
27
+ ## Docs & examples
28
28
 
29
- ```js
30
- recharge.init({ storeIdentifier: 'storeIdentifier' });
31
- ```
32
-
33
- ## Testing with Shopify App Proxy
34
-
35
- - Build UMD locally
36
- - run `npx http-server ./packages/storefront/client/dist`
37
- - login to storefront
38
- - run script from `test.html` in the dev tools
39
-
40
- ## Running e2e tests
41
-
42
- You will need to set up 3 environment variables to a store to run locally. You will need to set `SHOPIFY_URL`, `SHOPIFY_USERNAME`, and `SHOPIFY_PASSWORD`. These should be to a store that you have a user associated with. This allows the e2e tests to test authenticated calls.
43
-
44
- You can run the e2e tests 2 ways.
45
-
46
- 1. You can run via `yarn test:e2e --filter @rechargeapps/storefront-client` which will automatically start up the server needed and run through the tests on the command line.
47
- 2. Run `yarn build --filter @rechargeapps/storefront-client` to make sure you are using the latest build. You then need to host those files locally in a window via `yarn workspace @rechargeapps/storefront-client serve`. Then run `yarn workspace @rechargeapps/storefront-client cypress open` in another to get the GUI for cypress and run the tests.
48
-
49
- ## Deploys
50
-
51
- - Not deployed to a stage environment
52
- - Deployed via NPM, Gitlab, and CDN. All are versioned.
53
- - No rollbacks needed, just fix the bug and release a new version.
54
-
55
- ## Naming Types
56
-
57
- Due to possible naming conflicts we recommend name spacing anything that is not part of the Recharge Storefront API to reduce that chance of collisions later on.
58
-
59
- Example:
60
-
61
- CDN: `CDNBundleSettings`
62
- AppProxy: `BundleAppProxy`
63
-
64
- ## V2 ideas
65
-
66
- List of possible ideas around the SDK when moving towards a V2
67
-
68
- - separate packages based on API (api, cdn, appProxy, etc.)
29
+ See our public documentation [here](https://storefront.rechargepayments.com/client/)
@@ -16,14 +16,19 @@ async function loginShopifyAppProxy() {
16
16
  return { apiToken: response.api_token, customerId: response.customer_id };
17
17
  }
18
18
  async function loginShopifyApi(shopifyStorefrontToken, shopifyCustomerAccessToken) {
19
- const { environment, storeIdentifier } = options.getOptions();
19
+ const { environment, storefrontAccessToken, storeIdentifier } = options.getOptions();
20
20
  const rechargeBaseUrl = api.RECHARGE_ADMIN_URL(environment);
21
+ const headers = {};
22
+ if (storefrontAccessToken) {
23
+ headers["X-Recharge-Storefront-Access-Token"] = storefrontAccessToken;
24
+ }
21
25
  const response = await request.request("post", `${rechargeBaseUrl}/shopify_storefront_access`, {
22
26
  data: {
23
27
  customer_token: shopifyCustomerAccessToken,
24
28
  storefront_token: shopifyStorefrontToken,
25
29
  shop_url: storeIdentifier
26
- }
30
+ },
31
+ headers
27
32
  });
28
33
  return response.api_token ? { apiToken: response.api_token, customerId: response.customer_id } : null;
29
34
  }
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { LoginResponse, PasswordlessCodeResponse, PasswordlessValidateResponse } from '../types/auth';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RequestHeaders } from '../types';\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 };\n}\n\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { environment, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return response.api_token ? { apiToken: response.api_token, customerId: response.customer_id } : null;\n}\n\nexport async function sendPasswordlessCode(email: string): Promise<string> {\n const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\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 sendPasswordlessCodeAppProxy(email: string): Promise<string> {\n const { storefrontAccessToken, storeIdentifier } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\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 const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\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\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n const { storefrontAccessToken, storeIdentifier } = 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 shop: storeIdentifier,\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"],"names":["getOptions","shopifyAppProxyRequest","RECHARGE_ADMIN_URL","baseRequest"],"mappings":";;;;;;;;AAGO,eAAe,oBAAoB,GAAG;AAC7C,EAAE,MAAM,EAAE,qBAAqB,EAAE,GAAGA,kBAAU,EAAE,CAAC;AACjD,EAAE,MAAM,OAAO,GAAG,EAAE,CAAC;AACrB,EAAE,IAAI,qBAAqB,EAAE;AAC7B,IAAI,OAAO,CAAC,oCAAoC,CAAC,GAAG,qBAAqB,CAAC;AAC1E,GAAG;AACH,EAAE,MAAM,QAAQ,GAAG,MAAMC,8BAAsB,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAC/E,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;AAC5E,CAAC;AACM,eAAe,eAAe,CAAC,sBAAsB,EAAE,0BAA0B,EAAE;AAC1F,EAAE,MAAM,EAAE,WAAW,EAAE,eAAe,EAAE,GAAGD,kBAAU,EAAE,CAAC;AACxD,EAAE,MAAM,eAAe,GAAGE,sBAAkB,CAAC,WAAW,CAAC,CAAC;AAC1D,EAAE,MAAM,QAAQ,GAAG,MAAMC,eAAW,CAAC,MAAM,EAAE,CAAC,EAAE,eAAe,CAAC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AG;AACH,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;AAC5E,CAAC;AACM,eAAe,gCAAgC,CAAC,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE;AACnF,EAAE,MAAM,EAAE,qBAAqB,EAAE,eAAe,EAAE,GAAGH,kBAAU,EAAE,CAAC;AAClE,EAAE,MAAM,OAAO,GAAG,EAAE,CAAC;AACrB,EAAE,IAAI,qBAAqB,EAAE;AAC7B,IAAI,OAAO,CAAC,oCAAoC,CAAC,GAAG,qBAAqB,CAAC;AAC1E,GAAG;AACH,EAAE,MAAM,QAAQ,GAAG,MAAMC,8BAAsB,CAAC,MAAM,EAAE,iBAAiB,EAAE;AAC3E,IAAI,IAAI,EAAE;AACV,MAAM,IAAI;AACV,MAAM,KAAK;AACX,MAAM,aAAa;AACnB,MAAM,IAAI,EAAE,eAAe;AAC3B,KAAK;AACL,IAAI,OAAO;AACX,GAAG,CAAC,CAAC;AACL,EAAE,IAAI,QAAQ,CAAC,MAAM,EAAE;AACvB,IAAI,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACrC,GAAG;AACH,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;AAC5E;;;;;;;;;"}
1
+ {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { LoginResponse, PasswordlessCodeResponse, PasswordlessValidateResponse } from '../types/auth';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RequestHeaders } from '../types';\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 };\n}\n\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return response.api_token ? { apiToken: response.api_token, customerId: response.customer_id } : null;\n}\n\nexport async function sendPasswordlessCode(email: string): Promise<string> {\n const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\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 sendPasswordlessCodeAppProxy(email: string): Promise<string> {\n const { storefrontAccessToken, storeIdentifier } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\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 const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\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\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n const { storefrontAccessToken, storeIdentifier } = 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 shop: storeIdentifier,\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"],"names":["getOptions","shopifyAppProxyRequest","RECHARGE_ADMIN_URL","baseRequest"],"mappings":";;;;;;;;AAGO,eAAe,oBAAoB,GAAG;AAC7C,EAAE,MAAM,EAAE,qBAAqB,EAAE,GAAGA,kBAAU,EAAE,CAAC;AACjD,EAAE,MAAM,OAAO,GAAG,EAAE,CAAC;AACrB,EAAE,IAAI,qBAAqB,EAAE;AAC7B,IAAI,OAAO,CAAC,oCAAoC,CAAC,GAAG,qBAAqB,CAAC;AAC1E,GAAG;AACH,EAAE,MAAM,QAAQ,GAAG,MAAMC,8BAAsB,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAC/E,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,E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AC;AACrC,GAAG;AACH,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;AAC5E;;;;;;;;;"}
@@ -2,11 +2,11 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var bundlingData = require('@rechargeapps/bundling-data');
6
5
  var nanoid = require('nanoid');
7
6
  var request = require('../utils/request.js');
8
7
  var options = require('../utils/options.js');
9
8
  var cdn = require('./cdn.js');
9
+ var bundle = require('../utils/bundle.js');
10
10
 
11
11
  const STORE_FRONT_MANAGER_URL = "/bundling-storefront-manager";
12
12
  function getTimestampSecondsFromClient() {
@@ -23,17 +23,17 @@ async function getTimestampSecondsFromServer() {
23
23
  return getTimestampSecondsFromClient();
24
24
  }
25
25
  }
26
- async function getBundleId(bundle) {
26
+ async function getBundleId(bundle$1) {
27
27
  const opts = options.getOptions();
28
- const isValid = await validateBundle(bundle);
28
+ const isValid = await validateBundle(bundle$1);
29
29
  if (isValid !== true) {
30
30
  throw new Error(isValid);
31
31
  }
32
32
  const timestampSeconds = await getTimestampSecondsFromServer();
33
- const bundleData = bundlingData.toLineItemProperty({
34
- variantId: bundle.externalVariantId,
33
+ const bundleData = bundle.toLineItemProperty({
34
+ variantId: bundle$1.externalVariantId,
35
35
  version: timestampSeconds,
36
- items: bundle.selections.map((item) => {
36
+ items: bundle$1.selections.map((item) => {
37
37
  return {
38
38
  collectionId: item.collectionId,
39
39
  productId: item.externalProductId,
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { toLineItemProperty } from '@rechargeapps/bundling-data';\nimport { nanoid } from 'nanoid';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n} from '../types';\nimport { rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getCDNBundleSettings } from './cdn';\n\nconst STORE_FRONT_MANAGER_URL = '/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n try {\n const { timestamp } = await shopifyAppProxyRequest<{ timestamp: number }>('get', `${STORE_FRONT_MANAGER_URL}/t`, {\n headers: { 'X-Recharge-App': 'storefront-client' },\n });\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport async function getBundleId(bundle: BundleAppProxy): Promise<string> {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\n }\n const timestampSeconds = await getTimestampSecondsFromServer();\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const payload = await shopifyAppProxyRequest<{ id: string; code: number; message: string }>(\n 'post',\n `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`,\n {\n data: {\n bundle: bundleData,\n },\n headers: {\n Origin: `https://${opts.storeIdentifier}`,\n },\n }\n );\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n}\n\nexport function getDynamicBundleItems(bundle: BundleAppProxy, shopifyProductHandle: string) {\n const isValid = validateDynamicBundle(bundle);\n if (isValid !== true) {\n throw new Error(`Dynamic Bundle is invalid. ${isValid}`);\n }\n // generate unique id for dynamic bundle\n const bundleId = `${nanoid(9)}:${bundle.externalProductId}`;\n return bundle.selections.map(item => {\n const itemData: DynamicBundleItemAppProxy = {\n id: item.externalVariantId,\n quantity: item.quantity,\n properties: {\n _rc_bundle: bundleId,\n _rc_bundle_variant: bundle.externalVariantId,\n _rc_bundle_parent: shopifyProductHandle,\n _rc_bundle_collection_id: item.collectionId,\n },\n };\n\n if (item.sellingPlan) {\n // this is used by SCI stores\n itemData.selling_plan = item.sellingPlan;\n } else if (item.shippingIntervalFrequency) {\n // this is used by RCS stores\n itemData.properties.shipping_interval_frequency = item.shippingIntervalFrequency;\n itemData.properties.shipping_interval_unit_type = item.shippingIntervalUnitType;\n itemData.id = `${item.discountedVariantId}`;\n }\n\n return itemData;\n });\n}\n\nexport async function validateBundle(bundle: BundleAppProxy): Promise<true | string> {\n try {\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n if (!bundle) {\n return 'Bundle is not defined';\n }\n const bundleSettings = await getCDNBundleSettings(bundle.externalProductId);\n if (!bundleSettings) {\n return 'Bundle settings do not exist for the given product';\n }\n return true;\n } catch (e) {\n return `Error fetching bundle settings: ${e}`;\n }\n}\n\nconst intervalUnitGroups = {\n day: ['day', 'days', 'Days'],\n days: ['day', 'days', 'Days'],\n Days: ['day', 'days', 'Days'],\n week: ['week', 'weeks', 'Weeks'],\n weeks: ['week', 'weeks', 'Weeks'],\n Weeks: ['week', 'weeks', 'Weeks'],\n month: ['month', 'months', 'Months'],\n months: ['month', 'months', 'Months'],\n Months: ['month', 'months', 'Months'],\n};\n\n/**\n * Validates a dynamic bundle\n *\n * @param bundle Dynamic Bundle being validated\n * @returns true or error message\n */\nexport function validateDynamicBundle(bundle: BundleAppProxy): true | string {\n if (!bundle) {\n return 'No bundle defined.';\n }\n if (bundle.selections.length === 0) {\n return 'No selections defined.';\n }\n // validation for RCS onetimes\n const { shippingIntervalFrequency, shippingIntervalUnitType } =\n bundle.selections.find(selection => selection.shippingIntervalFrequency || selection.shippingIntervalUnitType) ||\n {};\n if (shippingIntervalFrequency || shippingIntervalUnitType) {\n // if we have shipping intervals then we should have both defined\n if (!shippingIntervalFrequency || !shippingIntervalUnitType) {\n return 'Shipping intervals do not match on selections.';\n } else {\n // if we have shipping intervals then any that are defined should match\n const shippingIntervalUnitGroup = intervalUnitGroups[shippingIntervalUnitType];\n for (let x = 0; x < bundle.selections.length; x++) {\n const { shippingIntervalFrequency: frequency, shippingIntervalUnitType: unitType } = bundle.selections[x];\n if (\n (frequency && frequency !== shippingIntervalFrequency) ||\n (unitType && !shippingIntervalUnitGroup.includes(unitType))\n ) {\n return 'Shipping intervals do not match on selections.';\n }\n }\n }\n }\n return true;\n}\n\nexport async function getBundleSelection(session: Session, id: string | number): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'get',\n `/bundle_selections`,\n {\n id,\n },\n session\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>('get', `/bundle_selections`, { query }, session);\n}\n\nexport async function createBundleSelection(\n session: Session,\n createRequest: CreateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'post',\n `/bundle_selections`,\n {\n data: createRequest,\n },\n session\n );\n return bundle_selection;\n}\n\nexport async function updateBundleSelection(\n session: Session,\n id: string | number,\n updateRequest: UpdateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'put',\n `/bundle_selections`,\n {\n id,\n data: updateRequest,\n },\n session\n );\n return bundle_selection;\n}\n\nexport function deleteBundleSelection(session: Session, id: string | number): Promise<void> {\n return rechargeApiRequest<void>(\n 'delete',\n `/bundle_selections`,\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AE,EAAE,OAAO,CAAC,CAAC;AAC7E,CAAC;AACM,eAAe,qBAAqB,CAAC,OAAO,EAAE,aAAa,EAAE;AACpE,EAAE,MAAM,EAAE,gBAAgB,EAAE,GAAG,MAAMA,0BAAkB,CAAC,MAAM,EAAE,CAAC,kBAAkB,CAAC,EAAE;AACtF,IAAI,IAAI,EAAE,aAAa;AACvB,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AACM,eAAe,qBAAqB,CAAC,OAAO,EAAE,EAAE,EAAE,aAAa,EAAE;AACxE,EAAE,MAAM,EAAE,gBAAgB,EAAE,GAAG,MAAMA,0BAAkB,CAAC,KAAK,EAAE,CAAC,kBAAkB,CAAC,EAAE;AACrF,IAAI,EAAE;AACN,IAAI,IAAI,EAAE,aAAa;AACvB,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AACM,SAAS,qBAAqB,CAAC,OAAO,EAAE,EAAE,EAAE;AACnD,EAAE,OAAOA,0BAAkB,CAAC,QAAQ,EAAE,CAAC,kBAAkB,CAAC,EAAE;AAC5D,IAAI,EAAE;AACN,GAAG,EAAE,OAAO,CAAC,CAAC;AACd;;;;;;;;;;;;"}
1
+ {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n} from '../types';\nimport { rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getCDNBundleSettings } from './cdn';\nimport { toLineItemProperty } from '../utils/bundle';\n\nconst STORE_FRONT_MANAGER_URL = '/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n try {\n const { timestamp } = await shopifyAppProxyRequest<{ timestamp: number }>('get', `${STORE_FRONT_MANAGER_URL}/t`, {\n headers: { 'X-Recharge-App': 'storefront-client' },\n });\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport async function getBundleId(bundle: BundleAppProxy): Promise<string> {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\n }\n const timestampSeconds = await getTimestampSecondsFromServer();\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const payload = await shopifyAppProxyRequest<{ id: string; code: number; message: string }>(\n 'post',\n `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`,\n {\n data: {\n bundle: bundleData,\n },\n headers: {\n Origin: `https://${opts.storeIdentifier}`,\n },\n }\n );\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n}\n\nexport function getDynamicBundleItems(bundle: BundleAppProxy, shopifyProductHandle: string) {\n const isValid = validateDynamicBundle(bundle);\n if (isValid !== true) {\n throw new Error(`Dynamic Bundle is invalid. ${isValid}`);\n }\n // generate unique id for dynamic bundle\n const bundleId = `${nanoid(9)}:${bundle.externalProductId}`;\n return bundle.selections.map(item => {\n const itemData: DynamicBundleItemAppProxy = {\n id: item.externalVariantId,\n quantity: item.quantity,\n properties: {\n _rc_bundle: bundleId,\n _rc_bundle_variant: bundle.externalVariantId,\n _rc_bundle_parent: shopifyProductHandle,\n _rc_bundle_collection_id: item.collectionId,\n },\n };\n\n if (item.sellingPlan) {\n // this is used by SCI stores\n itemData.selling_plan = item.sellingPlan;\n } else if (item.shippingIntervalFrequency) {\n // this is used by RCS stores\n itemData.properties.shipping_interval_frequency = item.shippingIntervalFrequency;\n itemData.properties.shipping_interval_unit_type = item.shippingIntervalUnitType;\n itemData.id = `${item.discountedVariantId}`;\n }\n\n return itemData;\n });\n}\n\nexport async function validateBundle(bundle: BundleAppProxy): Promise<true | string> {\n try {\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n if (!bundle) {\n return 'Bundle is not defined';\n }\n const bundleSettings = await getCDNBundleSettings(bundle.externalProductId);\n if (!bundleSettings) {\n return 'Bundle settings do not exist for the given product';\n }\n return true;\n } catch (e) {\n return `Error fetching bundle settings: ${e}`;\n }\n}\n\nconst intervalUnitGroups = {\n day: ['day', 'days', 'Days'],\n days: ['day', 'days', 'Days'],\n Days: ['day', 'days', 'Days'],\n week: ['week', 'weeks', 'Weeks'],\n weeks: ['week', 'weeks', 'Weeks'],\n Weeks: ['week', 'weeks', 'Weeks'],\n month: ['month', 'months', 'Months'],\n months: ['month', 'months', 'Months'],\n Months: ['month', 'months', 'Months'],\n};\n\n/**\n * Validates a dynamic bundle\n *\n * @param bundle Dynamic Bundle being validated\n * @returns true or error message\n */\nexport function validateDynamicBundle(bundle: BundleAppProxy): true | string {\n if (!bundle) {\n return 'No bundle defined.';\n }\n if (bundle.selections.length === 0) {\n return 'No selections defined.';\n }\n // validation for RCS onetimes\n const { shippingIntervalFrequency, shippingIntervalUnitType } =\n bundle.selections.find(selection => selection.shippingIntervalFrequency || selection.shippingIntervalUnitType) ||\n {};\n if (shippingIntervalFrequency || shippingIntervalUnitType) {\n // if we have shipping intervals then we should have both defined\n if (!shippingIntervalFrequency || !shippingIntervalUnitType) {\n return 'Shipping intervals do not match on selections.';\n } else {\n // if we have shipping intervals then any that are defined should match\n const shippingIntervalUnitGroup = intervalUnitGroups[shippingIntervalUnitType];\n for (let x = 0; x < bundle.selections.length; x++) {\n const { shippingIntervalFrequency: frequency, shippingIntervalUnitType: unitType } = bundle.selections[x];\n if (\n (frequency && frequency !== shippingIntervalFrequency) ||\n (unitType && !shippingIntervalUnitGroup.includes(unitType))\n ) {\n return 'Shipping intervals do not match on selections.';\n }\n }\n }\n }\n return true;\n}\n\nexport async function getBundleSelection(session: Session, id: string | number): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'get',\n `/bundle_selections`,\n {\n id,\n },\n session\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>('get', `/bundle_selections`, { query }, session);\n}\n\nexport async function createBundleSelection(\n session: Session,\n createRequest: CreateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'post',\n `/bundle_selections`,\n {\n data: createRequest,\n },\n session\n );\n return bundle_selection;\n}\n\nexport async function updateBundleSelection(\n session: Session,\n id: string | number,\n updateRequest: UpdateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'put',\n `/bundle_selections`,\n {\n id,\n data: updateRequest,\n },\n session\n );\n return bundle_selection;\n}\n\nexport function deleteBundleSelection(session: Session, id: string | number): Promise<void> {\n return rechargeApiRequest<void>(\n 'delete',\n `/bundle_selections`,\n {\n id,\n },\n session\n );\n}\n"],"names":["shopifyAppProxyRequest","bundle","getOptions","toLineItemProperty","nanoid","getCDNBundleSettings","rechargeApiRequest"],"mappings":";;;;;;;;;;AAKA,MAAM,uBAAuB,GAAG,8BAA8B,CAAC;AAC/D,SAAS,6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,CAAC,kBAAkB,CAAC,EAAE;AACtF,IAAI,IAAI,EAAE,aAAa;AACvB,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AACM,eAAe,qBAAqB,CAAC,OAAO,EAAE,EAAE,EAAE,aAAa,EAAE;AACxE,EAAE,MAAM,EAAE,gBAAgB,EAAE,GAAG,MAAMA,0BAAkB,CAAC,KAAK,EAAE,CAAC,kBAAkB,CAAC,EAAE;AACrF,IAAI,EAAE;AACN,IAAI,IAAI,EAAE,aAAa;AACvB,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AACM,SAAS,qBAAqB,CAAC,OAAO,EAAE,EAAE,EAAE;AACnD,EAAE,OAAOA,0BAAkB,CAAC,QAAQ,EAAE,CAAC,kBAAkB,CAAC,EAAE;AAC5D,IAAI,EAAE;AACN,GAAG,EAAE,OAAO,CAAC,CAAC;AACd;;;;;;;;;;;;"}
@@ -14,9 +14,10 @@ async function getSubscription(session, id, options) {
14
14
  function listSubscriptions(session, query) {
15
15
  return request.rechargeApiRequest("get", `/subscriptions`, { query }, session);
16
16
  }
17
- async function createSubscription(session, createRequest) {
17
+ async function createSubscription(session, createRequest, query) {
18
18
  const { subscription } = await request.rechargeApiRequest("post", `/subscriptions`, {
19
- data: createRequest
19
+ data: createRequest,
20
+ query
20
21
  }, session);
21
22
  return subscription;
22
23
  }
@@ -28,9 +29,10 @@ async function updateSubscription(session, id, updateRequest, query) {
28
29
  }, session);
29
30
  return subscription;
30
31
  }
31
- async function updateSubscriptionChargeDate(session, id, date) {
32
+ async function updateSubscriptionChargeDate(session, id, date, query) {
32
33
  const { subscription } = await request.rechargeApiRequest("post", `/subscriptions/${id}/set_next_charge_date`, {
33
- data: { date }
34
+ data: { date },
35
+ query
34
36
  }, session);
35
37
  return subscription;
36
38
  }
@@ -40,14 +42,15 @@ async function updateSubscriptionAddress(session, id, address_id) {
40
42
  }, session);
41
43
  return subscription;
42
44
  }
43
- async function cancelSubscription(session, id, cancelRequest) {
45
+ async function cancelSubscription(session, id, cancelRequest, query) {
44
46
  const { subscription } = await request.rechargeApiRequest("post", `/subscriptions/${id}/cancel`, {
45
- data: cancelRequest
47
+ data: cancelRequest,
48
+ query
46
49
  }, session);
47
50
  return subscription;
48
51
  }
49
- async function activateSubscription(session, id) {
50
- const { subscription } = await request.rechargeApiRequest("post", `/subscriptions/${id}/activate`, {}, session);
52
+ async function activateSubscription(session, id, query) {
53
+ const { subscription } = await request.rechargeApiRequest("post", `/subscriptions/${id}/activate`, { query }, session);
51
54
  return subscription;
52
55
  }
53
56
  async function skipSubscriptionCharge(session, id, date) {
@@ -1 +1 @@
1
- {"version":3,"file":"subscription.js","sources":["../../../src/api/subscription.ts"],"sourcesContent":["import { rechargeApiRequest } from '../utils/request';\nimport {\n CancelSubscriptionRequest,\n CreateSubscriptionRequest,\n Subscription,\n SubscriptionsResponse,\n SubscriptionListParams,\n UpdateSubscriptionRequest,\n UpdateSubscriptionParams,\n GetSubscriptionOptions,\n} from '../types/subscription';\nimport { IsoDateString } from '../types/common';\nimport { Session } from '../types/session';\nimport { ChargeResponse } from '../types';\n\nexport async function getSubscription(\n session: Session,\n id: string | number,\n options?: GetSubscriptionOptions\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'get',\n `/subscriptions`,\n {\n id,\n query: { include: options?.include },\n },\n session\n );\n return subscription;\n}\n\nexport function listSubscriptions(session: Session, query?: SubscriptionListParams): Promise<SubscriptionsResponse> {\n return rechargeApiRequest<SubscriptionsResponse>('get', `/subscriptions`, { query }, session);\n}\n\n/**\n * When creating a subscription via API, order_interval_frequency and charge_interval_frequency values do not necessarily\n * need to match the values set in the respective Plans. The product, however, does need to have at least one Plan in order\n * to be added to a subscription.\n */\nexport async function createSubscription(\n session: Session,\n createRequest: CreateSubscriptionRequest\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions`,\n {\n data: createRequest,\n },\n session\n );\n return subscription;\n}\n\n/**\n * Updating parameters like frequency, charge_interval_frequency, order_interval_frequency, order_interval_unit will cause our algorithm to automatically recalculate the next charge date (next_charge_scheduled_at).\n * WARNING: This update will remove skipped and manually changed charges.\n * If you want to change the next charge date (next_charge_scheduled_at) we recommend you to update these parameters first.\n * When updating order_interval_unit OR order_interval_frequency OR charge_interval_frequency all three parameters are required.\n */\nexport async function updateSubscription(\n session: Session,\n id: string | number,\n updateRequest: UpdateSubscriptionRequest,\n query?: UpdateSubscriptionParams\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'put',\n `/subscriptions`,\n {\n id,\n data: updateRequest,\n query,\n },\n session\n );\n return subscription;\n}\n\n/**\n * If there are two active subscriptions with the same address_id, and you update their\n * next_charge_date parameters to match, their charges will get merged into a new charge\n * with a new id\n */\nexport async function updateSubscriptionChargeDate(\n session: Session,\n id: string | number,\n date: IsoDateString\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions/${id}/set_next_charge_date`,\n {\n data: { date },\n },\n session\n );\n return subscription;\n}\n\nexport async function updateSubscriptionAddress(\n session: Session,\n id: string | number,\n address_id: string | number\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions/${id}/change_address`,\n {\n data: { address_id },\n },\n session\n );\n return subscription;\n}\n\n/**\n * An involuntary subscription cancelled due to max retries reached will trigger the\n * charge/max_retries_reached webhook. If this leads to the subscription being cancelled,\n * the subscription/cancelled webhook will trigger.\n */\nexport async function cancelSubscription(\n session: Session,\n id: string | number,\n cancelRequest: CancelSubscriptionRequest\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions/${id}/cancel`,\n {\n data: cancelRequest,\n },\n session\n );\n return subscription;\n}\n\n/**\n * When activating subscription, following attributes will be set to null: cancelled_at, cancellation_reason\n * and cancellation_reason_comments.\n */\nexport async function activateSubscription(session: Session, id: string | number): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions/${id}/activate`,\n {},\n session\n );\n return subscription;\n}\n\n/* Skip charge associated with a subscription. */\nexport async function skipSubscriptionCharge(session: Session, id: number | string, date: IsoDateString) {\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/subscriptions/${id}/charges/skip`,\n {\n data: {\n date,\n subscription_id: `${id}`,\n },\n },\n session\n );\n return charge;\n}\n"],"names":["rechargeApiRequest"],"mappings":";;;;;;AACO,eAAe,eAAe,CAAC,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE;AAC5D,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAMA,0BAAkB,CAAC,KAAK,EAAE,CAAC,cAAc,CAAC,EAAE;AAC7E,IAAI,EAAE;AACN,IAAI,KAAK,EAAE,EAAE,OAAO,EAAE,OAAO,IAAI,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE;AAClE,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,YAAY,CAAC;AACtB,CAAC;AACM,SAAS,iBAAiB,CAAC,OAAO,EAAE,KAAK,EAAE;AAClD,EAAE,OAAOA,0BAAkB,CAAC,KAAK,EAAE,CAAC,cAAc,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC;AACzE,CAAC;AACM,eAAe,kBAAkB,CAAC,OAAO,EAAE,aAAa,EAAE;AACjE,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAMA,0BAAkB,CAAC,MAAM,EAAE,CAAC,cAAc,CAAC,EAAE;AAC9E,IAAI,IAAI,EAAE,aAAa;AACvB,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,YAAY,CAAC;AACtB,CAAC;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oBAAoB,CAAC,OAAO,EAAE,EAAE,EAAE;AACxD,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAMA,0BAAkB,CAAC,MAAM,EAAE,CAAC,eAAe,EAAE,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,OAAO,CAAC,CAAC;AAC1G,EAAE,OAAO,YAAY,CAAC;AACtB,CAAC;AACM,eAAe,sBAAsB,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE;AAChE,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,MAAMA,0BAAkB,CAAC,MAAM,EAAE,CAAC,eAAe,EAAE,EAAE,CAAC,aAAa,CAAC,EAAE;AAC3F,IAAI,IAAI,EAAE;AACV,MAAM,IAAI;AACV,MAAM,eAAe,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;AAC9B,KAAK;AACL,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,MAAM,CAAC;AAChB;;;;;;;;;;;;"}
1
+ {"version":3,"file":"subscription.js","sources":["../../../src/api/subscription.ts"],"sourcesContent":["import { rechargeApiRequest } from '../utils/request';\nimport {\n CancelSubscriptionRequest,\n CreateSubscriptionRequest,\n Subscription,\n SubscriptionsResponse,\n SubscriptionListParams,\n UpdateSubscriptionRequest,\n UpdateSubscriptionParams,\n GetSubscriptionOptions,\n BasicSubscriptionParams,\n} from '../types/subscription';\nimport { IsoDateString } from '../types/common';\nimport { Session } from '../types/session';\nimport { ChargeResponse } from '../types';\n\nexport async function getSubscription(\n session: Session,\n id: string | number,\n options?: GetSubscriptionOptions\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'get',\n `/subscriptions`,\n {\n id,\n query: { include: options?.include },\n },\n session\n );\n return subscription;\n}\n\nexport function listSubscriptions(session: Session, query?: SubscriptionListParams): Promise<SubscriptionsResponse> {\n return rechargeApiRequest<SubscriptionsResponse>('get', `/subscriptions`, { query }, session);\n}\n\n/**\n * When creating a subscription via API, order_interval_frequency and charge_interval_frequency values do not necessarily\n * need to match the values set in the respective Plans. The product, however, does need to have at least one Plan in order\n * to be added to a subscription.\n */\nexport async function createSubscription(\n session: Session,\n createRequest: CreateSubscriptionRequest,\n query?: BasicSubscriptionParams\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions`,\n {\n data: createRequest,\n query,\n },\n session\n );\n return subscription;\n}\n\n/**\n * Updating parameters like frequency, charge_interval_frequency, order_interval_frequency, order_interval_unit will cause our algorithm to automatically recalculate the next charge date (next_charge_scheduled_at).\n * WARNING: This update will remove skipped and manually changed charges.\n * If you want to change the next charge date (next_charge_scheduled_at) we recommend you to update these parameters first.\n * When updating order_interval_unit OR order_interval_frequency OR charge_interval_frequency all three parameters are required.\n */\nexport async function updateSubscription(\n session: Session,\n id: string | number,\n updateRequest: UpdateSubscriptionRequest,\n query?: UpdateSubscriptionParams\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'put',\n `/subscriptions`,\n {\n id,\n data: updateRequest,\n query,\n },\n session\n );\n return subscription;\n}\n\n/**\n * If there are two active subscriptions with the same address_id, and you update their\n * next_charge_date parameters to match, their charges will get merged into a new charge\n * with a new id\n */\nexport async function updateSubscriptionChargeDate(\n session: Session,\n id: string | number,\n date: IsoDateString,\n query?: BasicSubscriptionParams\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions/${id}/set_next_charge_date`,\n {\n data: { date },\n query,\n },\n session\n );\n return subscription;\n}\n\nexport async function updateSubscriptionAddress(\n session: Session,\n id: string | number,\n address_id: string | number\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions/${id}/change_address`,\n {\n data: { address_id },\n },\n session\n );\n return subscription;\n}\n\n/**\n * An involuntary subscription cancelled due to max retries reached will trigger the\n * charge/max_retries_reached webhook. If this leads to the subscription being cancelled,\n * the subscription/cancelled webhook will trigger.\n */\nexport async function cancelSubscription(\n session: Session,\n id: string | number,\n cancelRequest: CancelSubscriptionRequest,\n query?: BasicSubscriptionParams\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions/${id}/cancel`,\n {\n data: cancelRequest,\n query,\n },\n session\n );\n return subscription;\n}\n\n/**\n * When activating subscription, following attributes will be set to null: cancelled_at, cancellation_reason\n * and cancellation_reason_comments.\n */\nexport async function activateSubscription(\n session: Session,\n id: string | number,\n query?: BasicSubscriptionParams\n): Promise<Subscription> {\n const { subscription } = await rechargeApiRequest<{ subscription: Subscription }>(\n 'post',\n `/subscriptions/${id}/activate`,\n { query },\n session\n );\n return subscription;\n}\n\n/* Skip charge associated with a subscription. */\nexport async function skipSubscriptionCharge(session: Session, id: number | string, date: IsoDateString) {\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/subscriptions/${id}/charges/skip`,\n {\n data: {\n date,\n subscription_id: `${id}`,\n },\n },\n session\n );\n return charge;\n}\n"],"names":["rechargeApiRequest"],"mappings":";;;;;;AACO,eAAe,eAAe,CAAC,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE;AAC5D,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAMA,0BAAkB,CAAC,KAAK,EAAE,CAAC,cAAc,CAAC,EAAE;AAC7E,IAAI,EAAE;AACN,IAAI,KAAK,EAAE,EAAE,OAAO,EAAE,OAAO,IAAI,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE;AAClE,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,YAAY,CAAC;AACtB,CAAC;AACM,SAAS,iBAAiB,CAAC,OAAO,EAAE,KAAK,EAAE;AAClD,EAAE,OAAOA,0BAAkB,CAAC,KAAK,EAAE,CAAC,cAAc,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,OAAO,C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AAE,OAAO,YAAY,CAAC;AACtB,CAAC;AACM,eAAe,kBAAkB,CAAC,OAAO,EAAE,EAAE,EAAE,aAAa,EAAE,KAAK,EAAE;AAC5E,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAMA,0BAAkB,CAAC,MAAM,EAAE,CAAC,eAAe,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE;AAC3F,IAAI,IAAI,EAAE,aAAa;AACvB,IAAI,KAAK;AACT,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,YAAY,CAAC;AACtB,CAAC;AACM,eAAe,oBAAoB,CAAC,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE;AAC/D,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAMA,0BAAkB,CAAC,MAAM,EAAE,CAAC,eAAe,EAAE,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC;AACjH,EAAE,OAAO,YAAY,CAAC;AACtB,CAAC;AACM,eAAe,sBAAsB,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE;AAChE,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,MAAMA,0BAAkB,CAAC,MAAM,EAAE,CAAC,eAAe,EAAE,EAAE,CAAC,aAAa,CAAC,EAAE;AAC3F,IAAI,IAAI,EAAE;AACV,MAAM,IAAI;AACV,MAAM,eAAe,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;AAC9B,KAAK;AACL,GAAG,EAAE,OAAO,CAAC,CAAC;AACd,EAAE,OAAO,MAAM,CAAC;AAChB;;;;;;;;;;;;"}
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var jsXdr = require('js-xdr');
6
+
7
+ function toLineItemProperty(bundle) {
8
+ const opts = {
9
+ variantId: xdr.Uint64.fromString(bundle.variantId.toString()),
10
+ version: bundle.version || Math.floor(Date.now() / 1e3),
11
+ items: bundle.items.map((item) => {
12
+ return new xdr.BundleItem({
13
+ collectionId: xdr.Uint64.fromString(item.collectionId.toString()),
14
+ productId: xdr.Uint64.fromString(item.productId.toString()),
15
+ variantId: xdr.Uint64.fromString(item.variantId.toString()),
16
+ sku: item.sku || "",
17
+ quantity: item.quantity,
18
+ ext: new xdr.BundleItemExt(0)
19
+ });
20
+ }),
21
+ ext: new xdr.BundleExt(0)
22
+ };
23
+ const xdrBundle = new xdr.Bundle(opts);
24
+ return xdr.BundleEnvelope.envelopeTypeBundle(xdrBundle).toXDR("base64");
25
+ }
26
+ const xdr = jsXdr.config((xdr2) => {
27
+ xdr2.enum("EnvelopeType", {
28
+ envelopeTypeBundle: 0
29
+ });
30
+ xdr2.typedef("Uint32", xdr2.uint());
31
+ xdr2.typedef("Uint64", xdr2.uhyper());
32
+ xdr2.union("BundleItemExt", {
33
+ switchOn: xdr2.int(),
34
+ switchName: "v",
35
+ switches: [[0, xdr2.void()]],
36
+ arms: {}
37
+ });
38
+ xdr2.struct("BundleItem", [
39
+ ["collectionId", xdr2.lookup("Uint64")],
40
+ ["productId", xdr2.lookup("Uint64")],
41
+ ["variantId", xdr2.lookup("Uint64")],
42
+ ["sku", xdr2.string()],
43
+ ["quantity", xdr2.lookup("Uint32")],
44
+ ["ext", xdr2.lookup("BundleItemExt")]
45
+ ]);
46
+ xdr2.union("BundleExt", {
47
+ switchOn: xdr2.int(),
48
+ switchName: "v",
49
+ switches: [[0, xdr2.void()]],
50
+ arms: {}
51
+ });
52
+ xdr2.struct("Bundle", [
53
+ ["variantId", xdr2.lookup("Uint64")],
54
+ ["items", xdr2.varArray(xdr2.lookup("BundleItem"), 500)],
55
+ ["version", xdr2.lookup("Uint32")],
56
+ ["ext", xdr2.lookup("BundleExt")]
57
+ ]);
58
+ xdr2.union("BundleEnvelope", {
59
+ switchOn: xdr2.lookup("EnvelopeType"),
60
+ switchName: "type",
61
+ switches: [["envelopeTypeBundle", "v1"]],
62
+ arms: {
63
+ v1: xdr2.lookup("Bundle")
64
+ }
65
+ });
66
+ });
67
+
68
+ exports.toLineItemProperty = toLineItemProperty;
69
+ //# sourceMappingURL=bundle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundle.js","sources":["../../../src/utils/bundle.ts"],"sourcesContent":["import { config } from 'js-xdr';\n\nexport function toLineItemProperty(bundle: { variantId: string; version: number; items: any[] }) {\n const opts = {\n variantId: xdr.Uint64.fromString(bundle.variantId.toString()),\n version: bundle.version || Math.floor(Date.now() / 1000),\n items: bundle.items.map(item => {\n return new xdr.BundleItem({\n collectionId: xdr.Uint64.fromString(item.collectionId.toString()),\n productId: xdr.Uint64.fromString(item.productId.toString()),\n variantId: xdr.Uint64.fromString(item.variantId.toString()),\n sku: item.sku || '',\n quantity: item.quantity,\n ext: new xdr.BundleItemExt(0),\n });\n }),\n ext: new xdr.BundleExt(0),\n };\n\n const xdrBundle = new xdr.Bundle(opts);\n return xdr.BundleEnvelope.envelopeTypeBundle(xdrBundle).toXDR('base64');\n}\n\nconst xdr = config(\n (xdr: {\n enum: (arg0: string, arg1: { envelopeTypeBundle: number }) => void;\n typedef: (arg0: string, arg1: any) => void;\n uint: () => any;\n uhyper: () => any;\n union: (\n arg0: string,\n arg1: {\n switchOn: any;\n switchName: string;\n switches: any[][] | string[][];\n // eslint-disable-next-line @typescript-eslint/ban-types\n arms: {} | {} | { v1: any };\n }\n ) => void;\n int: () => any;\n void: () => any;\n struct: (arg0: string, arg1: any[][]) => void;\n lookup: (arg0: string) => any;\n string: () => any;\n varArray: (arg0: any, arg1: number) => any;\n }) => {\n xdr.enum('EnvelopeType', {\n envelopeTypeBundle: 0,\n });\n xdr.typedef('Uint32', xdr.uint());\n xdr.typedef('Uint64', xdr.uhyper());\n xdr.union('BundleItemExt', {\n switchOn: xdr.int(),\n switchName: 'v',\n switches: [[0, xdr.void()]],\n arms: {},\n });\n xdr.struct('BundleItem', [\n ['collectionId', xdr.lookup('Uint64')],\n ['productId', xdr.lookup('Uint64')],\n ['variantId', xdr.lookup('Uint64')],\n ['sku', xdr.string()],\n ['quantity', xdr.lookup('Uint32')],\n ['ext', xdr.lookup('BundleItemExt')],\n ]);\n xdr.union('BundleExt', {\n switchOn: xdr.int(),\n switchName: 'v',\n switches: [[0, xdr.void()]],\n arms: {},\n });\n xdr.struct('Bundle', [\n ['variantId', xdr.lookup('Uint64')],\n ['items', xdr.varArray(xdr.lookup('BundleItem'), 500)],\n ['version', xdr.lookup('Uint32')],\n ['ext', xdr.lookup('BundleExt')],\n ]);\n xdr.union('BundleEnvelope', {\n switchOn: xdr.lookup('EnvelopeType'),\n switchName: 'type',\n switches: [['envelopeTypeBundle', 'v1']],\n arms: {\n v1: xdr.lookup('Bundle'),\n },\n });\n }\n);\n"],"names":["config"],"mappings":";;;;;;AACO,SAAS,kBAAkB,CAAC,MAAM,EAAE;AAC3C,EAAE,MAAM,IAAI,GAAG;AACf,IAAI,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;AACjE,IAAI,OAAO,EAAE,MAAM,CAAC,OAAO,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC;AAC3D,IAAI,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK;AACtC,MAAM,OAAO,IAAI,GAAG,CAAC,UAAU,CAAC;AAChC,QAAQ,YAAY,EAAE,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,CAAC;AACzE,QAAQ,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;AACnE,QAAQ,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;AACnE,QAAQ,GAA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AC5C,IAAI,IAAI,EAAE;AACV,MAAM,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC;AAC/B,KAAK;AACL,GAAG,CAAC,CAAC;AACL,CAAC,CAAC;;;;"}
@@ -3,11 +3,15 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  require('isomorphic-fetch');
6
- var qs = require('qs');
6
+ var stringify = require('qs/lib/stringify');
7
7
  var options = require('./options.js');
8
8
  var api = require('../constants/api.js');
9
9
  var error = require('./error.js');
10
10
 
11
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
12
+
13
+ var stringify__default = /*#__PURE__*/_interopDefaultLegacy(stringify);
14
+
11
15
  var __defProp = Object.defineProperty;
12
16
  var __defProps = Object.defineProperties;
13
17
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
@@ -28,7 +32,7 @@ var __spreadValues = (a, b) => {
28
32
  };
29
33
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
30
34
  function stringifyQuery(str) {
31
- return qs.stringify(str, {
35
+ return stringify__default["default"](str, {
32
36
  encode: false,
33
37
  indices: false,
34
38
  arrayFormat: "comma"
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import 'isomorphic-fetch';\n\nimport { stringify } from 'qs';\n\nimport { Method, RequestHeaders, RequestOptions } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RechargeRequestError } from './error';\n\nfunction stringifyQuery(str: unknown): string {\n return stringify(str, {\n encode: false,\n indices: false,\n arrayFormat: 'comma',\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: Session\n): Promise<T> {\n const { environment, storeIdentifier, loginRetryFn } = getOptions();\n const token = session.apiToken;\n const rechargeBaseUrl = RECHARGE_API_URL(environment);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n ...(headers ? headers : {}),\n };\n\n const localQuery = {\n shop_url: storeIdentifier,\n ...(query as any),\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 if (loginRetryFn && error instanceof RechargeRequestError && error.status === 401) {\n // call loginRetryFn and retry request on 401\n return loginRetryFn().then(session => {\n if (session) {\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': session.apiToken,\n },\n });\n }\n throw error;\n });\n }\n throw error;\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 reqUrl = [reqUrl, `${id}`.trim()].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query)].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 mode: 'cors',\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 (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":["stringify","getOptions","RECHARGE_CDN_URL","RECHARGE_API_URL","error","RechargeRequestError","SHOPIFY_APP_PROXY_URL"],"mappings":";;;;;;;;;;AAAA,IAAI,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC;AACtC,IAAI,UAAU,GAAG,MAAM,CAAC,gBAAgB,CAAC;AACzC,IAAI,iBAAiB,GAAG,MAAM,CAAC,yBAAyB,CAAC;AACzD,IAAI,mBAAmB,GAAG,MAAM,CAAC,qBAAqB,CAAC;AACvD,IAAI,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC;AACnD,IAAI,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,oBAAoB,CAAC;AACzD,IAAI,eAAe,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,KAAK,GAAG,IAAI,GAAG,GAAG,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAChK,IAAI,cAAc,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK;AAC/B,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;AAChC,IAAI,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,CAAC;AAClC,MAAM,eAAe,CAAC,CAAC,EAAE,IAAI,EAAE,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AAU,GAAG,cAAc,CAAC;AACpC,IAAI,MAAM,EAAE,kBAAkB;AAC9B,IAAI,cAAc,EAAE,kBAAkB;AACtC,IAAI,gBAAgB,EAAE,mBAAmB;AACzC,GAAG,EAAE,OAAO,GAAG,OAAO,GAAG,EAAE,CAAC,CAAC;AAC7B,EAAE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,MAAM,EAAE;AACvC,IAAI,MAAM;AACV,IAAI,OAAO,EAAE,UAAU;AACvB,IAAI,IAAI,EAAE,OAAO;AACjB,IAAI,IAAI,EAAE,MAAM;AAChB,GAAG,CAAC,CAAC;AACL,EAAE,IAAI,MAAM,CAAC;AACb,EAAE,IAAI;AACN,IAAI,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;AACnC,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,GAAG;AACH,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;AACpB,IAAI,IAAI,MAAM,IAAI,MAAM,CAAC,KAAK,EAAE;AAChC,MAAM,MAAM,IAAID,0BAAoB,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;AACpE,KAAK,MAAM,IAAI,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE;AACxC,MAAM,MAAM,IAAIA,0BAAoB,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;AACrF,KAAK,MAAM;AACX,MAAM,MAAM,IAAIA,0BAAoB,CAAC,sDAAsD,CAAC,CAAC;AAC7F,KAAK;AACL,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB;;;;;;;"}
1
+ {"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import 'isomorphic-fetch';\n\nimport stringify from 'qs/lib/stringify';\n\nimport { Method, RequestHeaders, RequestOptions } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RechargeRequestError } from './error';\n\nfunction stringifyQuery(str: unknown): string {\n return stringify(str, {\n encode: false,\n indices: false,\n arrayFormat: 'comma',\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: Session\n): Promise<T> {\n const { environment, storeIdentifier, loginRetryFn } = getOptions();\n const token = session.apiToken;\n const rechargeBaseUrl = RECHARGE_API_URL(environment);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n ...(headers ? headers : {}),\n };\n\n const localQuery = {\n shop_url: storeIdentifier,\n ...(query as any),\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 if (loginRetryFn && error instanceof RechargeRequestError && error.status === 401) {\n // call loginRetryFn and retry request on 401\n return loginRetryFn().then(session => {\n if (session) {\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': session.apiToken,\n },\n });\n }\n throw error;\n });\n }\n throw error;\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 reqUrl = [reqUrl, `${id}`.trim()].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query)].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 mode: 'cors',\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 (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":["stringify","getOptions","RECHARGE_CDN_URL","RECHARGE_API_URL","error","RechargeRequestError","SHOPIFY_APP_PROXY_URL"],"mappings":";;;;;;;;;;;;;;AAAA,IAAI,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC;AACtC,IAAI,UAAU,GAAG,MAAM,CAAC,gBAAgB,CAAC;AACzC,IAAI,iBAAiB,GAAG,MAAM,CAAC,yBAAyB,CAAC;AACzD,IAAI,mBAAmB,GAAG,MAAM,CAAC,qBAAqB,CAAC;AACvD,IAAI,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC;AACnD,IAAI,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,oBAAoB,CAAC;AACzD,IAAI,eAAe,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,KAAK,GAAG,IAAI,GAAG,GAAG,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK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M;AACX,MAAM,MAAM,IAAIA,0BAAoB,CAAC,sDAAsD,CAAC,CAAC;AAC7F,KAAK;AACL,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB;;;;;;;"}
@@ -12,14 +12,19 @@ async function loginShopifyAppProxy() {
12
12
  return { apiToken: response.api_token, customerId: response.customer_id };
13
13
  }
14
14
  async function loginShopifyApi(shopifyStorefrontToken, shopifyCustomerAccessToken) {
15
- const { environment, storeIdentifier } = getOptions();
15
+ const { environment, storefrontAccessToken, storeIdentifier } = getOptions();
16
16
  const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);
17
+ const headers = {};
18
+ if (storefrontAccessToken) {
19
+ headers["X-Recharge-Storefront-Access-Token"] = storefrontAccessToken;
20
+ }
17
21
  const response = await request("post", `${rechargeBaseUrl}/shopify_storefront_access`, {
18
22
  data: {
19
23
  customer_token: shopifyCustomerAccessToken,
20
24
  storefront_token: shopifyStorefrontToken,
21
25
  shop_url: storeIdentifier
22
- }
26
+ },
27
+ headers
23
28
  });
24
29
  return response.api_token ? { apiToken: response.api_token, customerId: response.customer_id } : null;
25
30
  }
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { LoginResponse, PasswordlessCodeResponse, PasswordlessValidateResponse } from '../types/auth';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RequestHeaders } from '../types';\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 };\n}\n\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { environment, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return response.api_token ? { apiToken: response.api_token, customerId: response.customer_id } : null;\n}\n\nexport async function sendPasswordlessCode(email: string): Promise<string> {\n const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\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 sendPasswordlessCodeAppProxy(email: string): Promise<string> {\n const { storefrontAccessToken, storeIdentifier } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\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 const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\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\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n const { storefrontAccessToken, storeIdentifier } = 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 shop: storeIdentifier,\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"],"names":["baseRequest"],"mappings":";;;;AAGO,eAAe,oBAAoB,GAAG;AAC7C,EAAE,MAAM,EAAE,qBAAqB,EAAE,GAAG,UAAU,EAAE,CAAC;AACjD,EAAE,MAAM,OAAO,GAAG,EAAE,CAAC;AACrB,EAAE,IAAI,qBAAqB,EAAE;AAC7B,IAAI,OAAO,CAAC,oCAAoC,CAAC,GAAG,qBAAqB,CAAC;AAC1E,GAAG;AACH,EAAE,MAAM,QAAQ,GAAG,MAAM,sBAAsB,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAC/E,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;AAC5E,CAAC;AACM,eAAe,eAAe,CAAC,sBAAsB,EAAE,0BAA0B,EAAE;AAC1F,EAAE,MAAM,EAAE,WAAW,EAAE,eAAe,EAAE,GAAG,UAAU,EAAE,CAAC;AACxD,EAAE,MAAM,eAAe,GAAG,kBAAkB,CAAC,WAAW,CAAC,CAAC;AAC1D,EAAE,MAAM,QAAQ,GAAG,MAAMA,OAAW,CAAC,MAAM,EAAE,CAAC,EAAE,eAAe,CAAC,0BAA0B,CAAC,EAAE;AAC7F,IAAI,I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CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;AAC5E,CAAC;AACM,eAAe,gCAAgC,CAAC,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE;AACnF,EAAE,MAAM,EAAE,qBAAqB,EAAE,eAAe,EAAE,GAAG,UAAU,EAAE,CAAC;AAClE,EAAE,MAAM,OAAO,GAAG,EAAE,CAAC;AACrB,EAAE,IAAI,qBAAqB,EAAE;AAC7B,IAAI,OAAO,CAAC,oCAAoC,CAAC,GAAG,qBAAqB,CAAC;AAC1E,GAAG;AACH,EAAE,MAAM,QAAQ,GAAG,MAAM,sBAAsB,CAAC,MAAM,EAAE,iBAAiB,EAAE;AAC3E,IAAI,IAAI,EAAE;AACV,MAAM,IAAI;AACV,MAAM,KAAK;AACX,MAAM,aAAa;AACnB,MAAM,IAAI,EAAE,eAAe;AAC3B,KAAK;AACL,IAAI,OAAO;AACX,GAAG,CAAC,CAAC;AACL,EAAE,IAAI,QAAQ,CAAC,MAAM,EAAE;AACvB,IAAI,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACrC,GAAG;AACH,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;AAC5E;;;;"}
1
+ {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { LoginResponse, PasswordlessCodeResponse, PasswordlessValidateResponse } from '../types/auth';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RequestHeaders } from '../types';\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 };\n}\n\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return response.api_token ? { apiToken: response.api_token, customerId: response.customer_id } : null;\n}\n\nexport async function sendPasswordlessCode(email: string): Promise<string> {\n const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\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 sendPasswordlessCodeAppProxy(email: string): Promise<string> {\n const { storefrontAccessToken, storeIdentifier } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\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 const { environment, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\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\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n const { storefrontAccessToken, storeIdentifier } = 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 shop: storeIdentifier,\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"],"names":["baseRequest"],"mappings":";;;;AAGO,eAAe,oBAAoB,GAAG;AAC7C,EAAE,MAAM,EAAE,qBAAqB,EAAE,GAAG,UAAU,EAAE,CAAC;AACjD,EAAE,MAAM,OAAO,GAAG,EAAE,CAAC;AACrB,EAAE,IAAI,qBAAqB,EAAE;AAC7B,IAAI,OAAO,CAAC,oCAAoC,CAAC,GAAG,qBAAqB,CAAC;AAC1E,GAAG;AACH,EAAE,MAAM,QAAQ,GAAG,MAAM,sBAAsB,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAC/E,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;AAC5E,CAAC;AACM,eAAe,eAAe,CAAC,sBAAsB,EAAE,0BAA0B,EAAE;AAC1F,EAAE,MAAM,EAAE,WAAW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5E;;;;"}
@@ -1,8 +1,8 @@
1
- import { toLineItemProperty } from '@rechargeapps/bundling-data';
2
1
  import { nanoid } from 'nanoid';
3
2
  import { shopifyAppProxyRequest, rechargeApiRequest } from '../utils/request.js';
4
3
  import { getOptions } from '../utils/options.js';
5
4
  import { getCDNBundleSettings } from './cdn.js';
5
+ import { toLineItemProperty } from '../utils/bundle.js';
6
6
 
7
7
  const STORE_FRONT_MANAGER_URL = "/bundling-storefront-manager";
8
8
  function getTimestampSecondsFromClient() {