@salesforce/commerce-sdk-react 1.0.0-preview.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.
Files changed (143) hide show
  1. package/.eslintrc.js +10 -0
  2. package/CHANGELOG.md +35 -0
  3. package/LICENSE +14 -0
  4. package/README.md +327 -0
  5. package/auth/index.d.ts +220 -0
  6. package/auth/index.js +472 -0
  7. package/auth/storage.d.ts +48 -0
  8. package/auth/storage.js +122 -0
  9. package/components/ShopperExperience/Component/index.d.ts +17 -0
  10. package/components/ShopperExperience/Component/index.js +49 -0
  11. package/components/ShopperExperience/Page/index.d.ts +28 -0
  12. package/components/ShopperExperience/Page/index.js +97 -0
  13. package/components/ShopperExperience/Region/index.d.ts +41 -0
  14. package/components/ShopperExperience/Region/index.js +64 -0
  15. package/components/ShopperExperience/index.d.ts +5 -0
  16. package/components/ShopperExperience/index.js +49 -0
  17. package/components/ShopperExperience/prop-types.d.ts +39 -0
  18. package/components/ShopperExperience/prop-types.js +46 -0
  19. package/components/ShopperExperience/types.d.ts +8 -0
  20. package/components/ShopperExperience/types.js +5 -0
  21. package/components/index.d.ts +2 -0
  22. package/components/index.js +16 -0
  23. package/hooks/ShopperBaskets/cache.d.ts +5 -0
  24. package/hooks/ShopperBaskets/cache.js +351 -0
  25. package/hooks/ShopperBaskets/index.d.ts +3 -0
  26. package/hooks/ShopperBaskets/index.js +27 -0
  27. package/hooks/ShopperBaskets/mutation.d.ts +381 -0
  28. package/hooks/ShopperBaskets/mutation.js +380 -0
  29. package/hooks/ShopperBaskets/query.d.ts +55 -0
  30. package/hooks/ShopperBaskets/query.js +215 -0
  31. package/hooks/ShopperBaskets/queryKeyHelpers.d.ts +72 -0
  32. package/hooks/ShopperBaskets/queryKeyHelpers.js +49 -0
  33. package/hooks/ShopperContexts/cache.d.ts +5 -0
  34. package/hooks/ShopperContexts/cache.js +45 -0
  35. package/hooks/ShopperContexts/index.d.ts +3 -0
  36. package/hooks/ShopperContexts/index.js +27 -0
  37. package/hooks/ShopperContexts/mutation.d.ts +35 -0
  38. package/hooks/ShopperContexts/mutation.js +68 -0
  39. package/hooks/ShopperContexts/query.d.ts +15 -0
  40. package/hooks/ShopperContexts/query.js +59 -0
  41. package/hooks/ShopperContexts/queryKeyHelpers.d.ts +30 -0
  42. package/hooks/ShopperContexts/queryKeyHelpers.js +25 -0
  43. package/hooks/ShopperCustomers/cache.d.ts +5 -0
  44. package/hooks/ShopperCustomers/cache.js +387 -0
  45. package/hooks/ShopperCustomers/index.d.ts +3 -0
  46. package/hooks/ShopperCustomers/index.js +27 -0
  47. package/hooks/ShopperCustomers/mutation.d.ts +163 -0
  48. package/hooks/ShopperCustomers/mutation.js +203 -0
  49. package/hooks/ShopperCustomers/query.d.ts +115 -0
  50. package/hooks/ShopperCustomers/query.js +489 -0
  51. package/hooks/ShopperCustomers/queryKeyHelpers.d.ts +142 -0
  52. package/hooks/ShopperCustomers/queryKeyHelpers.js +91 -0
  53. package/hooks/ShopperExperience/index.d.ts +2 -0
  54. package/hooks/ShopperExperience/index.js +16 -0
  55. package/hooks/ShopperExperience/query.d.ts +31 -0
  56. package/hooks/ShopperExperience/query.js +104 -0
  57. package/hooks/ShopperExperience/queryKeyHelpers.d.ts +38 -0
  58. package/hooks/ShopperExperience/queryKeyHelpers.js +31 -0
  59. package/hooks/ShopperGiftCertificates/index.d.ts +2 -0
  60. package/hooks/ShopperGiftCertificates/index.js +16 -0
  61. package/hooks/ShopperGiftCertificates/query.d.ts +15 -0
  62. package/hooks/ShopperGiftCertificates/query.js +70 -0
  63. package/hooks/ShopperGiftCertificates/queryKeyHelpers.d.ts +29 -0
  64. package/hooks/ShopperGiftCertificates/queryKeyHelpers.js +25 -0
  65. package/hooks/ShopperLogin/cache.d.ts +3 -0
  66. package/hooks/ShopperLogin/cache.js +33 -0
  67. package/hooks/ShopperLogin/index.d.ts +3 -0
  68. package/hooks/ShopperLogin/index.js +27 -0
  69. package/hooks/ShopperLogin/mutation.d.ts +119 -0
  70. package/hooks/ShopperLogin/mutation.js +138 -0
  71. package/hooks/ShopperLogin/query.d.ts +45 -0
  72. package/hooks/ShopperLogin/query.js +176 -0
  73. package/hooks/ShopperLogin/queryKeyHelpers.d.ts +53 -0
  74. package/hooks/ShopperLogin/queryKeyHelpers.js +43 -0
  75. package/hooks/ShopperOrders/cache.d.ts +5 -0
  76. package/hooks/ShopperOrders/cache.js +54 -0
  77. package/hooks/ShopperOrders/index.d.ts +3 -0
  78. package/hooks/ShopperOrders/index.js +27 -0
  79. package/hooks/ShopperOrders/mutation.d.ts +54 -0
  80. package/hooks/ShopperOrders/mutation.js +83 -0
  81. package/hooks/ShopperOrders/query.d.ts +37 -0
  82. package/hooks/ShopperOrders/query.js +139 -0
  83. package/hooks/ShopperOrders/queryKeyHelpers.d.ts +50 -0
  84. package/hooks/ShopperOrders/queryKeyHelpers.js +37 -0
  85. package/hooks/ShopperProducts/index.d.ts +2 -0
  86. package/hooks/ShopperProducts/index.js +16 -0
  87. package/hooks/ShopperProducts/query.d.ts +47 -0
  88. package/hooks/ShopperProducts/query.js +178 -0
  89. package/hooks/ShopperProducts/queryKeyHelpers.d.ts +55 -0
  90. package/hooks/ShopperProducts/queryKeyHelpers.js +43 -0
  91. package/hooks/ShopperPromotions/index.d.ts +2 -0
  92. package/hooks/ShopperPromotions/index.js +16 -0
  93. package/hooks/ShopperPromotions/query.d.ts +29 -0
  94. package/hooks/ShopperPromotions/query.js +102 -0
  95. package/hooks/ShopperPromotions/queryKeyHelpers.d.ts +38 -0
  96. package/hooks/ShopperPromotions/queryKeyHelpers.js +31 -0
  97. package/hooks/ShopperSearch/index.d.ts +2 -0
  98. package/hooks/ShopperSearch/index.js +16 -0
  99. package/hooks/ShopperSearch/query.d.ts +26 -0
  100. package/hooks/ShopperSearch/query.js +99 -0
  101. package/hooks/ShopperSearch/queryKeyHelpers.d.ts +37 -0
  102. package/hooks/ShopperSearch/queryKeyHelpers.js +31 -0
  103. package/hooks/index.d.ts +18 -0
  104. package/hooks/index.js +188 -0
  105. package/hooks/types.d.ts +128 -0
  106. package/hooks/types.js +5 -0
  107. package/hooks/useAccessToken.d.ts +11 -0
  108. package/hooks/useAccessToken.js +43 -0
  109. package/hooks/useAuthContext.d.ts +9 -0
  110. package/hooks/useAuthContext.js +30 -0
  111. package/hooks/useAuthHelper.d.ts +23 -0
  112. package/hooks/useAuthHelper.js +66 -0
  113. package/hooks/useAuthorizationHeader.d.ts +9 -0
  114. package/hooks/useAuthorizationHeader.js +45 -0
  115. package/hooks/useCommerceApi.d.ts +9 -0
  116. package/hooks/useCommerceApi.js +26 -0
  117. package/hooks/useConfig.d.ts +7 -0
  118. package/hooks/useConfig.js +24 -0
  119. package/hooks/useCustomerId.d.ts +7 -0
  120. package/hooks/useCustomerId.js +38 -0
  121. package/hooks/useCustomerType.d.ts +21 -0
  122. package/hooks/useCustomerType.js +43 -0
  123. package/hooks/useEncUserId.d.ts +9 -0
  124. package/hooks/useEncUserId.js +36 -0
  125. package/hooks/useLocalStorage.d.ts +8 -0
  126. package/hooks/useLocalStorage.js +40 -0
  127. package/hooks/useMutation.d.ts +12 -0
  128. package/hooks/useMutation.js +38 -0
  129. package/hooks/useQuery.d.ts +15 -0
  130. package/hooks/useQuery.js +57 -0
  131. package/hooks/useUsid.d.ts +7 -0
  132. package/hooks/useUsid.js +34 -0
  133. package/hooks/utils.d.ts +32 -0
  134. package/hooks/utils.js +125 -0
  135. package/index.d.ts +5 -0
  136. package/index.js +40 -0
  137. package/package.json +88 -0
  138. package/provider.d.ts +36 -0
  139. package/provider.js +124 -0
  140. package/scripts/build-and-release-docs.js +48 -0
  141. package/scripts/version.js +22 -0
  142. package/utils.d.ts +5 -0
  143. package/utils.js +18 -0
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.AuthHelpers = void 0;
7
+ exports.useAuthHelper = useAuthHelper;
8
+ var _reactQuery = require("@tanstack/react-query");
9
+ var _useAuthContext = _interopRequireDefault(require("./useAuthContext"));
10
+ var _utils = require("./utils");
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
+ /*
13
+ * Copyright (c) 2023, Salesforce, Inc.
14
+ * All rights reserved.
15
+ * SPDX-License-Identifier: BSD-3-Clause
16
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
17
+ */
18
+
19
+ const AuthHelpers = {
20
+ LoginGuestUser: 'loginGuestUser',
21
+ LoginRegisteredUserB2C: 'loginRegisteredUserB2C',
22
+ Logout: 'logout',
23
+ Register: 'register'
24
+ };
25
+ exports.AuthHelpers = AuthHelpers;
26
+ const noop = () => ({});
27
+ /**
28
+ * A hook for Public Client OAuth helpers.
29
+ * The hook calls the SLAS helpers imported from commerce-sdk-isomorphic.
30
+ * For more, see https://github.com/SalesforceCommerceCloud/commerce-sdk-isomorphic/#public-client-shopper-login-helpers
31
+ *
32
+ * Avaliable helpers:
33
+ * - loginRegisteredUserB2C
34
+ * - loginGuestUser
35
+ * - logout
36
+ * - register
37
+ */
38
+ function useAuthHelper(mutation) {
39
+ const auth = (0, _useAuthContext.default)();
40
+ if (!auth[mutation]) throw new Error(`Unknown login helper mutation: ${mutation}`);
41
+ const queryClient = (0, _reactQuery.useQueryClient)();
42
+ // I'm not sure if there's a way to avoid this type assertion, but, I'm fairly confident that
43
+ // it is safe to do, as it seems to be simply re-asserting what we already know.
44
+ const method = auth[mutation].bind(auth);
45
+ return (0, _reactQuery.useMutation)(auth.whenReady(method), {
46
+ onSuccess(data, options) {
47
+ const getCacheUpdates = cacheUpdateMatrix[mutation];
48
+ if (getCacheUpdates) {
49
+ const cacheUpdates = getCacheUpdates(options, data);
50
+ (0, _utils.updateCache)(queryClient, cacheUpdates, data);
51
+ }
52
+ }
53
+ });
54
+ }
55
+ const cacheUpdateMatrix = {
56
+ loginRegisteredUserB2C: noop,
57
+ loginGuestUser: noop,
58
+ logout() {
59
+ return {
60
+ remove: [{
61
+ queryKey: ['/commerce-sdk-react']
62
+ }]
63
+ };
64
+ },
65
+ register: noop
66
+ };
@@ -0,0 +1,9 @@
1
+ import { ApiOptions, ApiMethod } from './types';
2
+ /**
3
+ * Creates a method that waits for authentication to complete and automatically includes an
4
+ * Authorization header when making requests.
5
+ * @param method Bound API method
6
+ * @internal
7
+ */
8
+ export declare const useAuthorizationHeader: <Options extends ApiOptions<Record<string, unknown>, unknown[] | Record<string, unknown> | undefined, Record<string, string>>, Data>(method: ApiMethod<Options, Data>) => ApiMethod<Options, Data>;
9
+ //# sourceMappingURL=useAuthorizationHeader.d.ts.map
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useAuthorizationHeader = void 0;
7
+ var _useAuthContext = _interopRequireDefault(require("./useAuthContext"));
8
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
10
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
11
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
13
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
14
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
15
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } /*
16
+ * Copyright (c) 2023, Salesforce, Inc.
17
+ * All rights reserved.
18
+ * SPDX-License-Identifier: BSD-3-Clause
19
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
20
+ */
21
+ /**
22
+ * Creates a method that waits for authentication to complete and automatically includes an
23
+ * Authorization header when making requests.
24
+ * @param method Bound API method
25
+ * @internal
26
+ */
27
+ const useAuthorizationHeader = method => {
28
+ const auth = (0, _useAuthContext.default)();
29
+ return /*#__PURE__*/function () {
30
+ var _ref = _asyncToGenerator(function* (options) {
31
+ const {
32
+ access_token
33
+ } = yield auth.ready();
34
+ return yield method(_objectSpread(_objectSpread({}, options), {}, {
35
+ headers: _objectSpread({
36
+ Authorization: `Bearer ${access_token}`
37
+ }, options.headers)
38
+ }));
39
+ });
40
+ return function (_x) {
41
+ return _ref.apply(this, arguments);
42
+ };
43
+ }();
44
+ };
45
+ exports.useAuthorizationHeader = useAuthorizationHeader;
@@ -0,0 +1,9 @@
1
+ import { ApiClients } from './types';
2
+ /**
3
+ * Access a set of initialized Commerce API clients, which are initialized using the configurations passed to the CommerceApiProvider.
4
+ *
5
+ * @returns Commerce API clients
6
+ */
7
+ declare const useCommerceApi: () => ApiClients;
8
+ export default useCommerceApi;
9
+ //# sourceMappingURL=useCommerceApi.d.ts.map
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _react = _interopRequireDefault(require("react"));
8
+ var _provider = require("../provider");
9
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10
+ /*
11
+ * Copyright (c) 2022, salesforce.com, inc.
12
+ * All rights reserved.
13
+ * SPDX-License-Identifier: BSD-3-Clause
14
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
15
+ */
16
+
17
+ /**
18
+ * Access a set of initialized Commerce API clients, which are initialized using the configurations passed to the CommerceApiProvider.
19
+ *
20
+ * @returns Commerce API clients
21
+ */
22
+ const useCommerceApi = () => {
23
+ return _react.default.useContext(_provider.CommerceApiContext);
24
+ };
25
+ var _default = useCommerceApi;
26
+ exports.default = _default;
@@ -0,0 +1,7 @@
1
+ import { CommerceApiProviderProps } from '../provider';
2
+ /**
3
+ * @Internal
4
+ */
5
+ declare const useConfig: () => Omit<CommerceApiProviderProps, 'children'>;
6
+ export default useConfig;
7
+ //# sourceMappingURL=useConfig.d.ts.map
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _react = _interopRequireDefault(require("react"));
8
+ var _provider = require("../provider");
9
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10
+ /*
11
+ * Copyright (c) 2022, salesforce.com, inc.
12
+ * All rights reserved.
13
+ * SPDX-License-Identifier: BSD-3-Clause
14
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
15
+ */
16
+
17
+ /**
18
+ * @Internal
19
+ */
20
+ const useConfig = () => {
21
+ return _react.default.useContext(_provider.ConfigContext);
22
+ };
23
+ var _default = useConfig;
24
+ exports.default = _default;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Hook that returns the customer ID.
3
+ *
4
+ */
5
+ declare const useCustomerId: () => string | null;
6
+ export default useCustomerId;
7
+ //# sourceMappingURL=useCustomerId.d.ts.map
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _useAuthContext = _interopRequireDefault(require("./useAuthContext"));
8
+ var _useLocalStorage = _interopRequireDefault(require("./useLocalStorage"));
9
+ var _useConfig = _interopRequireDefault(require("./useConfig"));
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+ /*
12
+ * Copyright (c) 2022, salesforce.com, inc.
13
+ * All rights reserved.
14
+ * SPDX-License-Identifier: BSD-3-Clause
15
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
16
+ */
17
+
18
+ const onClient = typeof window !== 'undefined';
19
+
20
+ /**
21
+ * Hook that returns the customer ID.
22
+ *
23
+ */
24
+ const useCustomerId = () => {
25
+ if (onClient) {
26
+ // `onClient` is a constant, so the hooks will always have the same execution order,
27
+ // despite technically being inside a conditional.
28
+ // eslint-disable-next-line react-hooks/rules-of-hooks
29
+ const config = (0, _useConfig.default)();
30
+ // eslint-disable-next-line react-hooks/rules-of-hooks
31
+ return (0, _useLocalStorage.default)(`customer_id_${config.siteId}`);
32
+ }
33
+ // eslint-disable-next-line react-hooks/rules-of-hooks
34
+ const auth = (0, _useAuthContext.default)();
35
+ return auth.get('customer_id');
36
+ };
37
+ var _default = useCustomerId;
38
+ exports.default = _default;
@@ -0,0 +1,21 @@
1
+ export declare type CustomerType = null | 'guest' | 'registered';
2
+ declare type useCustomerType = {
3
+ customerType: CustomerType;
4
+ isGuest: boolean;
5
+ isRegistered: boolean;
6
+ };
7
+ /**
8
+ * A hook to return customer auth type.
9
+ *
10
+ * Customer type can have 3 values:
11
+ * - null
12
+ * - guest
13
+ * - registered
14
+ *
15
+ * During initialization, type is null. And it is possible that
16
+ * isGuest and isRegistered to both be false.
17
+ *
18
+ */
19
+ declare const useCustomerType: () => useCustomerType;
20
+ export default useCustomerType;
21
+ //# sourceMappingURL=useCustomerType.d.ts.map
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _useAuthContext = _interopRequireDefault(require("./useAuthContext"));
8
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
+ /*
10
+ * Copyright (c) 2023, salesforce.com, inc.
11
+ * All rights reserved.
12
+ * SPDX-License-Identifier: BSD-3-Clause
13
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
14
+ */
15
+
16
+ /**
17
+ * A hook to return customer auth type.
18
+ *
19
+ * Customer type can have 3 values:
20
+ * - null
21
+ * - guest
22
+ * - registered
23
+ *
24
+ * During initialization, type is null. And it is possible that
25
+ * isGuest and isRegistered to both be false.
26
+ *
27
+ */
28
+ const useCustomerType = () => {
29
+ const auth = (0, _useAuthContext.default)();
30
+ let customerType = auth.get('customer_type');
31
+ const isGuest = customerType === 'guest';
32
+ const isRegistered = customerType === 'registered';
33
+ if (customerType !== null && customerType !== 'guest' && customerType !== 'registered') {
34
+ customerType = null;
35
+ }
36
+ return {
37
+ customerType,
38
+ isGuest,
39
+ isRegistered
40
+ };
41
+ };
42
+ var _default = useCustomerType;
43
+ exports.default = _default;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Hook that returns the ecom user ID.
3
+ *
4
+ * This is sometimes used as the user ID for Einstein.
5
+ *
6
+ */
7
+ declare const useEncUserId: () => string | null;
8
+ export default useEncUserId;
9
+ //# sourceMappingURL=useEncUserId.d.ts.map
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _useAuthContext = _interopRequireDefault(require("./useAuthContext"));
8
+ var _useLocalStorage = _interopRequireDefault(require("./useLocalStorage"));
9
+ var _useConfig = _interopRequireDefault(require("./useConfig"));
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+ /*
12
+ * Copyright (c) 2022, salesforce.com, inc.
13
+ * All rights reserved.
14
+ * SPDX-License-Identifier: BSD-3-Clause
15
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
16
+ */
17
+
18
+ const onClient = typeof window !== 'undefined';
19
+
20
+ /**
21
+ * Hook that returns the ecom user ID.
22
+ *
23
+ * This is sometimes used as the user ID for Einstein.
24
+ *
25
+ */
26
+ const useEncUserId = () => {
27
+ const config = (0, _useConfig.default)();
28
+ const auth = (0, _useAuthContext.default)();
29
+ return onClient ?
30
+ // This conditional is a constant value based on the environment, so the same path will
31
+ // always be followed., and the "rule of hooks" is not violated.
32
+ // eslint-disable-next-line react-hooks/rules-of-hooks
33
+ (0, _useLocalStorage.default)(`$enc_user_id_${config.siteId}`) : auth.get('enc_user_id');
34
+ };
35
+ var _default = useEncUserId;
36
+ exports.default = _default;
@@ -0,0 +1,8 @@
1
+ declare type Value = string | null;
2
+ /**
3
+ * @internal
4
+ *
5
+ */
6
+ declare function useLocalStorage(key: string): Value;
7
+ export default useLocalStorage;
8
+ //# sourceMappingURL=useLocalStorage.d.ts.map
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _react = require("react");
8
+ /*
9
+ * Copyright (c) 2022, Salesforce, Inc.
10
+ * All rights reserved.
11
+ * SPDX-License-Identifier: BSD-3-Clause
12
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
13
+ */
14
+
15
+ /**
16
+ * @internal
17
+ *
18
+ */
19
+ function useLocalStorage(key) {
20
+ const readValue = () => {
21
+ if (typeof window === 'undefined') {
22
+ return null;
23
+ }
24
+ return window.localStorage.getItem(key);
25
+ };
26
+ const [storedValue, setStoredValue] = (0, _react.useState)(readValue);
27
+ const handleStorageChange = event => {
28
+ if (event.key !== key) {
29
+ return;
30
+ }
31
+ setStoredValue(readValue());
32
+ };
33
+ (0, _react.useEffect)(() => {
34
+ window.addEventListener('storage', handleStorageChange);
35
+ return () => window.removeEventListener('storage', handleStorageChange);
36
+ }, []);
37
+ return storedValue;
38
+ }
39
+ var _default = useLocalStorage;
40
+ exports.default = _default;
@@ -0,0 +1,12 @@
1
+ import { CacheUpdateGetter, ApiOptions, ApiMethod, ApiClient, MergedOptions } from './types';
2
+ /**
3
+ * Helper for mutation hooks, contains most of the logic in order to keep individual hooks small.
4
+ * @param hookConfig - Config values that vary per API endpoint
5
+ * @internal
6
+ */
7
+ export declare const useMutation: <Client extends ApiClient, Options extends ApiOptions<Record<string, unknown>, unknown[] | Record<string, unknown> | undefined, Record<string, string>>, Data>(hookConfig: {
8
+ client: Client;
9
+ method: ApiMethod<Options, Data>;
10
+ getCacheUpdates: CacheUpdateGetter<Required<ApiOptions<NonNullable<Client["clientConfig"]["parameters"] & Options["parameters"]>, unknown extends Options["body"] ? never : Options["body"], NonNullable<Client["clientConfig"]["headers"] & Options["headers"]>>>, Data>;
11
+ }) => import("@tanstack/react-query").UseMutationResult<Data, unknown, Options, unknown>;
12
+ //# sourceMappingURL=useMutation.d.ts.map
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useMutation = void 0;
7
+ var _reactQuery = require("@tanstack/react-query");
8
+ var _useAuthorizationHeader = require("./useAuthorizationHeader");
9
+ var _useCustomerId = _interopRequireDefault(require("./useCustomerId"));
10
+ var _utils = require("./utils");
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
+ /*
13
+ * Copyright (c) 2023, Salesforce, Inc.
14
+ * All rights reserved.
15
+ * SPDX-License-Identifier: BSD-3-Clause
16
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
17
+ */
18
+
19
+ /**
20
+ * Helper for mutation hooks, contains most of the logic in order to keep individual hooks small.
21
+ * @param hookConfig - Config values that vary per API endpoint
22
+ * @internal
23
+ */
24
+ const useMutation = hookConfig => {
25
+ const queryClient = (0, _reactQuery.useQueryClient)();
26
+ const customerId = (0, _useCustomerId.default)();
27
+ const authenticatedMethod = (0, _useAuthorizationHeader.useAuthorizationHeader)(hookConfig.method);
28
+ return (0, _reactQuery.useMutation)(authenticatedMethod, {
29
+ onSuccess(data, options) {
30
+ // commerce-sdk-isomorphic merges `clientConfig` and `options` under the hood,
31
+ // so we also need to do that to get the "net" options that are actually sent to SCAPI.
32
+ const netOptions = (0, _utils.mergeOptions)(hookConfig.client, options);
33
+ const cacheUpdates = hookConfig.getCacheUpdates(customerId, netOptions, data);
34
+ (0, _utils.updateCache)(queryClient, cacheUpdates, data);
35
+ }
36
+ });
37
+ };
38
+ exports.useMutation = useMutation;
@@ -0,0 +1,15 @@
1
+ import { ApiClient, ApiMethod, ApiOptions, ApiQueryKey, ApiQueryOptions, MergedOptions, NullableParameters, OmitNullableParameters } from './types';
2
+ /**
3
+ * Helper for query hooks, contains most of the logic in order to keep individual hooks small.
4
+ * @param apiOptions - Options passed through to commerce-sdk-isomorphic
5
+ * @param queryOptions - Options passed through to @tanstack/react-query
6
+ * @param hookConfig - Config values that vary per API endpoint
7
+ * @internal
8
+ */
9
+ export declare const useQuery: <Client extends ApiClient, Options extends ApiOptions<Record<string, unknown>, unknown[] | Record<string, unknown> | undefined, Record<string, string>>, Data>(apiOptions: OmitNullableParameters<NullableParameters<Required<ApiOptions<NonNullable<Client["clientConfig"]["parameters"] & Options["parameters"]>, unknown extends Options["body"] ? never : Options["body"], NonNullable<Client["clientConfig"]["headers"] & Options["headers"]>>>>>, queryOptions: ApiQueryOptions<ApiMethod<Options, Data>>, hookConfig: {
10
+ method: ApiMethod<Options, Data>;
11
+ queryKey: ApiQueryKey<Partial<Options["parameters"]>>;
12
+ requiredParameters: readonly (keyof NonNullable<Options["parameters"]>)[];
13
+ enabled?: boolean | undefined;
14
+ }) => import("@tanstack/react-query").UseQueryResult<Data, unknown>;
15
+ //# sourceMappingURL=useQuery.d.ts.map
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useQuery = void 0;
7
+ var _reactQuery = require("@tanstack/react-query");
8
+ var _useAuthorizationHeader = require("./useAuthorizationHeader");
9
+ var _utils = require("./utils");
10
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
11
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
12
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
13
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
14
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
15
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
16
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } /*
17
+ * Copyright (c) 2023, Salesforce, Inc.
18
+ * All rights reserved.
19
+ * SPDX-License-Identifier: BSD-3-Clause
20
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
21
+ */
22
+ /**
23
+ * Helper for query hooks, contains most of the logic in order to keep individual hooks small.
24
+ * @param apiOptions - Options passed through to commerce-sdk-isomorphic
25
+ * @param queryOptions - Options passed through to @tanstack/react-query
26
+ * @param hookConfig - Config values that vary per API endpoint
27
+ * @internal
28
+ */
29
+ const useQuery = (apiOptions, queryOptions, hookConfig) => {
30
+ const authenticatedMethod = (0, _useAuthorizationHeader.useAuthorizationHeader)(hookConfig.method);
31
+ // This type assertion is NOT safe in all cases. However, we know that `requiredParameters` is
32
+ // the list of parameters required by `Options`, and we know that in the default case (when
33
+ // `queryOptions.enabled` is not set), we only execute the hook when `apiOptions` has all
34
+ // required parameters. Therefore, we know that `apiOptions` satisfies `Options` in the default
35
+ // case, so the type assertion is safe in the default case. We explicitly do NOT guarantee type
36
+ // safety when `queryOptions.enabled` is set; when it is `true`, the callback may be called with
37
+ // missing parameters. This will result in a runtime error. I think that this is an acceptable
38
+ // trade-off, as the behavior is opt-in by the end user, and it feels like adding type safety
39
+ // for this case would add significantly more complexity.
40
+ const wrappedMethod = /*#__PURE__*/function () {
41
+ var _ref = _asyncToGenerator(function* () {
42
+ return yield authenticatedMethod(apiOptions);
43
+ });
44
+ return function wrappedMethod() {
45
+ return _ref.apply(this, arguments);
46
+ };
47
+ }();
48
+ return (0, _reactQuery.useQuery)(hookConfig.queryKey, wrappedMethod, _objectSpread({
49
+ enabled:
50
+ // Individual hooks can provide `enabled` checks that are done in ADDITION to
51
+ // the required parameter check
52
+ hookConfig.enabled !== false &&
53
+ // The default `enabled` is "has all required parameters"
54
+ (0, _utils.hasAllKeys)(apiOptions.parameters, hookConfig.requiredParameters)
55
+ }, queryOptions));
56
+ };
57
+ exports.useQuery = useQuery;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Hook that returns the usid associated with the current access token.
3
+ *
4
+ */
5
+ declare const useUsid: () => string | null;
6
+ export default useUsid;
7
+ //# sourceMappingURL=useUsid.d.ts.map
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _useAuthContext = _interopRequireDefault(require("./useAuthContext"));
8
+ var _useLocalStorage = _interopRequireDefault(require("./useLocalStorage"));
9
+ var _useConfig = _interopRequireDefault(require("./useConfig"));
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+ /*
12
+ * Copyright (c) 2022, salesforce.com, inc.
13
+ * All rights reserved.
14
+ * SPDX-License-Identifier: BSD-3-Clause
15
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
16
+ */
17
+
18
+ const onClient = typeof window !== 'undefined';
19
+
20
+ /**
21
+ * Hook that returns the usid associated with the current access token.
22
+ *
23
+ */
24
+ const useUsid = () => {
25
+ const config = (0, _useConfig.default)();
26
+ const auth = (0, _useAuthContext.default)();
27
+ return onClient ?
28
+ // This conditional is a constant value based on the environment, so the same path will
29
+ // always be followed., and the "rule of hooks" is not violated.
30
+ // eslint-disable-next-line react-hooks/rules-of-hooks
31
+ (0, _useLocalStorage.default)(`usid_${config.siteId}`) : auth.get('usid');
32
+ };
33
+ var _default = useUsid;
34
+ exports.default = _default;
@@ -0,0 +1,32 @@
1
+ import { Query, QueryClient } from '@tanstack/react-query';
2
+ import { ApiClient, ApiOptions, CacheUpdate, MergedOptions, NullToOptional, OmitNullableParameters } from './types';
3
+ /** Applies the set of cache updates to the query client. */
4
+ export declare const updateCache: (queryClient: QueryClient, cacheUpdates: CacheUpdate, data: unknown) => void;
5
+ /** Error thrown when a method is not implemented. */
6
+ export declare class NotImplementedError extends Error {
7
+ constructor(method?: string);
8
+ }
9
+ /** Determines whether a value is an object. */
10
+ export declare const isObject: (obj: unknown) => obj is Record<string, unknown>;
11
+ /** Determines whether a value has all of the given keys. */
12
+ export declare const hasAllKeys: <T>(object: T, keys: readonly (keyof T)[]) => boolean;
13
+ /** Creates a query predicate that determines whether a query key starts with the given path segments. */
14
+ export declare const pathStartsWith: (search: readonly (string | undefined)[]) => ({ queryKey }: Query) => boolean;
15
+ /** Creates a query predicate that returns true if all of the given predicates return true. */
16
+ export declare const and: <Args extends unknown[]>(...funcs: ((...args: Args) => boolean)[]) => (...args: Args) => boolean;
17
+ /**
18
+ * Merges headers and parameters from client config into the options, mimicking the behavior
19
+ * of commerce-sdk-isomorphic.
20
+ */
21
+ export declare const mergeOptions: <Client extends ApiClient, Options extends ApiOptions<Record<string, unknown>, unknown[] | Record<string, unknown> | undefined, Record<string, string>>>(client: Client, options: Options) => Required<ApiOptions<NonNullable<Client["clientConfig"]["parameters"] & Options["parameters"]>, unknown extends Options["body"] ? never : Options["body"], NonNullable<Client["clientConfig"]["headers"] & Options["headers"]>>>;
22
+ /** Constructs a subset of the given object containing only the given keys. */
23
+ export declare const pick: <T extends object, K extends keyof T>(obj: T, keys: readonly K[]) => Pick<T, K>;
24
+ /** Removes keys with `null` or `undefined` values from the given object. */
25
+ export declare const omitNullable: <T extends object>(obj: T) => NullToOptional<T>;
26
+ /** Removes keys with `null` or `undefined` values from the `parameters` of the given object. */
27
+ export declare const omitNullableParameters: <T extends {
28
+ parameters: object;
29
+ }>(obj: T) => OmitNullableParameters<T>;
30
+ /** Simple deep clone utility */
31
+ export declare const clone: <T>(val: T) => T;
32
+ //# sourceMappingURL=utils.d.ts.map