@scayle/storefront-core 8.33.1 → 8.34.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/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # @scayle/storefront-core
2
2
 
3
+ ## 8.34.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Added export of `Pagination` type.
8
+ - **Breaking:** Improved type safety of the `mergeBaskets` RPC method. The method now returns the correct type `Promise<BasketResponse<Product, Variant> | AddManyItemsBasketResponse<Product, Variant> | undefined>` instead of `any`.
9
+
10
+ ### Patch Changes
11
+
12
+ **Dependencies**
13
+
14
+ - Updated dependency to @scayle/storefront-api@18.9.0
15
+ - Updated dependency to @scayle/unstorage-scayle-kv-driver@1.0.2
16
+
17
+ ## 8.33.2
18
+
19
+ ### Patch Changes
20
+
21
+ - Updated dependency `@scayle/storefront-api@18.9.0` to `@scayle/storefront-api@workspace:*`
22
+ - Updated dependency `@scayle/unstorage-scayle-kv-driver@1.0.2` to `@scayle/unstorage-scayle-kv-driver@workspace:*`
23
+
3
24
  ## 8.33.1
4
25
 
5
26
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -68,4 +68,4 @@ export type RpcMethodParameters<N extends RpcMethodName> = Parameters<RpcMethod<
68
68
  */
69
69
  export type RpcMethodReturnType<N extends RpcMethodName> = ReturnType<RpcMethod<N>>;
70
70
  export type RpcMethodCall = <N extends RpcMethodName, P extends RpcMethodParameters<N>, TResult extends Exclude<Awaited<RpcMethodReturnType<N>>, Response>>(...args: P extends RpcContext ? [N] : [N, P]) => Promise<TResult>;
71
- export { ExistingItemHandling, AddToBasketFailureKind, UpdateBasketItemFailureKind, AddToWishlistFailureKind, PromotionEffectType, FilterTypes, APISortOption, APISortOrder, type ProductSortConfig, type ShopCountryCustomData, } from '@scayle/storefront-api';
71
+ export { ExistingItemHandling, AddToBasketFailureKind, UpdateBasketItemFailureKind, AddToWishlistFailureKind, PromotionEffectType, FilterTypes, APISortOption, APISortOrder, Pagination, type ProductSortConfig, type ShopCountryCustomData, } from '@scayle/storefront-api';
package/dist/index.mjs CHANGED
@@ -14,5 +14,6 @@ export {
14
14
  PromotionEffectType,
15
15
  FilterTypes,
16
16
  APISortOption,
17
- APISortOrder
17
+ APISortOrder,
18
+ Pagination
18
19
  } from "@scayle/storefront-api";
@@ -1,6 +1,7 @@
1
1
  import { ExistingItemHandling } from '@scayle/storefront-api';
2
2
  import type { AddOrUpdateItemError, UpdateBasketItemQuantity, GetApplicablePromotionsByCodeParameters } from '@scayle/storefront-api';
3
- import type { AddOrUpdateItemType, BasketResponseData, BasketWithOptions, Product, RpcHandler, ParamRpcHandler, Variant } from '../../../types';
3
+ import type { AddOrUpdateItemType, BasketResponseData, BasketWithOptions, Product, RpcHandler, Variant } from '../../../types';
4
+ import { mergeBaskets as mergeBasketFunction } from '../../../utils/user';
4
5
  /**
5
6
  * Adds an item to the basket.
6
7
  *
@@ -104,12 +105,12 @@ export declare const clearBasket: RpcHandler<boolean>;
104
105
  *
105
106
  * @returns The new merged basket as result of the merge operation.
106
107
  */
107
- export declare const mergeBaskets: ParamRpcHandler<{
108
+ export declare const mergeBaskets: RpcHandler<{
108
109
  fromBasketKey: string;
109
110
  toBasketKey: string;
110
111
  with?: BasketWithOptions;
111
112
  orderCustomData?: Record<string, unknown>;
112
- }, any>;
113
+ }, Awaited<ReturnType<typeof mergeBasketFunction>>>;
113
114
  /**
114
115
  * Type defining an object containing properties of a basket item than should be
115
116
  * applied to the basket item during the update.
@@ -8,13 +8,13 @@ import {
8
8
  } from "../../../constants/index.mjs";
9
9
  import { mergeBaskets as mergeBasketFunction } from "../../../utils/user.mjs";
10
10
  import { unwrap } from "../../../utils/response.mjs";
11
- import { wasAddedWithReducedQuantity } from "../../../utils/index.mjs";
11
+ import { defineRpcHandler, wasAddedWithReducedQuantity } from "../../../utils/index.mjs";
12
12
  import { mapSAPIFetchErrorToResponse } from "../../../utils/sapi.mjs";
13
13
  const SAPI_ERROR_NAME = "SAPI ERROR";
14
14
  function getWithParams(params, context) {
15
15
  return params.with ?? context.withParams?.basket ?? MIN_WITH_PARAMS_BASKET;
16
16
  }
17
- export const addItemToBasket = async function addItemToBasket2({
17
+ export const addItemToBasket = defineRpcHandler(async ({
18
18
  variantId,
19
19
  promotionId,
20
20
  quantity,
@@ -24,7 +24,7 @@ export const addItemToBasket = async function addItemToBasket2({
24
24
  itemGroup,
25
25
  with: _with,
26
26
  orderCustomData
27
- }, context) {
27
+ }, context) => {
28
28
  if (!hasSession(context)) {
29
29
  return new ErrorResponse(
30
30
  HttpStatusCode.BAD_REQUEST,
@@ -84,8 +84,8 @@ export const addItemToBasket = async function addItemToBasket2({
84
84
  }
85
85
  );
86
86
  }
87
- };
88
- export const addItemsToBasket = async function addItemsToBasket2(params, context) {
87
+ });
88
+ export const addItemsToBasket = defineRpcHandler(async (params, context) => {
89
89
  if (!hasSession(context)) {
90
90
  return new ErrorResponse(
91
91
  HttpStatusCode.BAD_REQUEST,
@@ -145,8 +145,8 @@ export const addItemsToBasket = async function addItemsToBasket2(params, context
145
145
  }
146
146
  );
147
147
  }
148
- };
149
- export const getBasket = async function getBasket2(options, context) {
148
+ });
149
+ export const getBasket = defineRpcHandler(async (options, context) => {
150
150
  if (!hasSession(context)) {
151
151
  return new ErrorResponse(
152
152
  HttpStatusCode.BAD_REQUEST,
@@ -178,8 +178,8 @@ export const getBasket = async function getBasket2(options, context) {
178
178
  );
179
179
  }
180
180
  return { basket: response.basket };
181
- };
182
- export const removeItemFromBasket = async function removeItemFromBasket2(options, context) {
181
+ });
182
+ export const removeItemFromBasket = defineRpcHandler(async (options, context) => {
183
183
  if (!hasSession(context)) {
184
184
  return new ErrorResponse(
185
185
  HttpStatusCode.BAD_REQUEST,
@@ -201,22 +201,24 @@ export const removeItemFromBasket = async function removeItemFromBasket2(options
201
201
  }
202
202
  );
203
203
  return { basket };
204
- };
205
- export const clearBasket = async function clearBasket2(context) {
206
- const getBasketResponse = await getBasket({}, context);
207
- if (getBasketResponse instanceof ErrorResponse) {
208
- return getBasketResponse;
204
+ });
205
+ export const clearBasket = defineRpcHandler(
206
+ async (context) => {
207
+ const getBasketResponse = await getBasket({}, context);
208
+ if (getBasketResponse instanceof ErrorResponse) {
209
+ return getBasketResponse;
210
+ }
211
+ const { basket } = await unwrap(getBasketResponse);
212
+ await Promise.all(
213
+ basket.items.map(async (item) => {
214
+ await removeItemFromBasket({ itemKey: item.key }, context);
215
+ })
216
+ );
217
+ context.log.debug("The basket has been cleared");
218
+ return true;
209
219
  }
210
- const { basket } = await unwrap(getBasketResponse);
211
- await Promise.all(
212
- basket.items.map(async (item) => {
213
- await removeItemFromBasket({ itemKey: item.key }, context);
214
- })
215
- );
216
- context.log.debug("The basket has been cleared");
217
- return true;
218
- };
219
- export const mergeBaskets = async function mergeBaskets2({ fromBasketKey, toBasketKey, with: _with, orderCustomData }, context) {
220
+ );
221
+ export const mergeBaskets = defineRpcHandler(async ({ fromBasketKey, toBasketKey, with: _with, orderCustomData }, context) => {
220
222
  const resolvedWith = getWithParams(
221
223
  { with: _with },
222
224
  context
@@ -227,8 +229,8 @@ export const mergeBaskets = async function mergeBaskets2({ fromBasketKey, toBask
227
229
  { ...resolvedWith, orderCustomData },
228
230
  context
229
231
  );
230
- };
231
- export const updateBasketItem = async function updateBasketItem2({ basketItemKey, update, with: _with }, context) {
232
+ });
233
+ export const updateBasketItem = defineRpcHandler(async ({ basketItemKey, update, with: _with }, context) => {
232
234
  if (!hasSession(context)) {
233
235
  return new ErrorResponse(
234
236
  HttpStatusCode.BAD_REQUEST,
@@ -267,8 +269,8 @@ export const updateBasketItem = async function updateBasketItem2({ basketItemKey
267
269
  }
268
270
  );
269
271
  }
270
- };
271
- export const getApplicablePromotionsByCode = async function getApplicablePromotionsByCode2({ promotionCode, with: _with }, context) {
272
+ });
273
+ export const getApplicablePromotionsByCode = defineRpcHandler(async ({ promotionCode, with: _with }, context) => {
272
274
  if (!hasSession(context)) {
273
275
  return new ErrorResponse(
274
276
  HttpStatusCode.BAD_REQUEST,
@@ -302,7 +304,7 @@ export const getApplicablePromotionsByCode = async function getApplicablePromoti
302
304
  } else {
303
305
  return { basket: result.basket };
304
306
  }
305
- };
307
+ });
306
308
  function parseBasketError(response) {
307
309
  const parsedError = {
308
310
  message: "",
@@ -1,6 +1,7 @@
1
1
  import { mapSAPIFetchErrorToResponse } from "../../utils/sapi.mjs";
2
+ import { defineRpcHandler } from "../../utils/index.mjs";
2
3
  const MAX_PER_PAGE = 100;
3
- export const getBrands = async function getBrands2({ pagination }, context) {
4
+ export const getBrands = defineRpcHandler(async ({ pagination }, context) => {
4
5
  const { sapiClient, cached } = context;
5
6
  return await cached(mapSAPIFetchErrorToResponse(sapiClient.brands.get), {
6
7
  cacheKeyPrefix: "getBrands"
@@ -10,8 +11,8 @@ export const getBrands = async function getBrands2({ pagination }, context) {
10
11
  perPage: pagination?.perPage ? Math.min(pagination.perPage, MAX_PER_PAGE) : void 0
11
12
  }
12
13
  });
13
- };
14
- export const getBrandById = async function getBrandById2({ brandId }, context) {
14
+ });
15
+ export const getBrandById = defineRpcHandler(async ({ brandId }, context) => {
15
16
  const { sapiClient, cached } = context;
16
17
  return await cached(
17
18
  mapSAPIFetchErrorToResponse(sapiClient.brands.getById),
@@ -19,4 +20,4 @@ export const getBrandById = async function getBrandById2({ brandId }, context) {
19
20
  cacheKeyPrefix: `getBrandById-${brandId}`
20
21
  }
21
22
  )(brandId);
22
- };
23
+ });
@@ -1,4 +1,4 @@
1
- import type { RpcContext } from '../../types';
1
+ import type { RpcHandler } from '../../types';
2
2
  /**
3
3
  * Retrieves the active campaign key.
4
4
  *
@@ -14,4 +14,4 @@ import type { RpcContext } from '../../types';
14
14
  * @param context The RPC Context
15
15
  * @returns The current active campaign key.
16
16
  */
17
- export declare const getCampaignKey: (context: RpcContext) => Promise<string | undefined>;
17
+ export declare const getCampaignKey: RpcHandler<string | undefined>;
@@ -3,7 +3,8 @@ import {
3
3
  sortCampaignsByDateAscending,
4
4
  isCampaignActive
5
5
  } from "../../utils/campaign.mjs";
6
- export const getCampaignKey = async function getCampaignKey2(context) {
6
+ import { defineRpcHandler } from "../../utils/index.mjs";
7
+ export const getCampaignKey = defineRpcHandler(async (context) => {
7
8
  if (context.campaignKey) {
8
9
  return context.campaignKey;
9
10
  }
@@ -20,4 +21,4 @@ export const getCampaignKey = async function getCampaignKey2(context) {
20
21
  ttl: 5 * 60
21
22
  })();
22
23
  return campaigns.find(isCampaignActive)?.key;
23
- };
24
+ });
@@ -1,6 +1,7 @@
1
1
  import { splitAndRemoveEmpty } from "../../helpers/index.mjs";
2
2
  import { mapSAPIFetchErrorToResponse } from "../../utils/sapi.mjs";
3
- export const getRootCategories = async function getRootCategories2({ children = 1, includeHidden, properties, includeProductSorting }, context) {
3
+ import { defineRpcHandler } from "../../utils/index.mjs";
4
+ export const getRootCategories = defineRpcHandler(async ({ children = 1, includeHidden, properties, includeProductSorting }, context) => {
4
5
  const { cached, sapiClient } = context;
5
6
  const result = await cached(sapiClient.categories.getRoots, {
6
7
  cacheKeyPrefix: "root-categories"
@@ -12,8 +13,8 @@ export const getRootCategories = async function getRootCategories2({ children =
12
13
  categories: result,
13
14
  activeNode: void 0
14
15
  };
15
- };
16
- export const getCategoryByPath = async function getCategoryByPath2({ path, children = 1, includeHidden, properties, includeProductSorting }, context) {
16
+ });
17
+ export const getCategoryByPath = defineRpcHandler(async ({ path, children = 1, includeHidden, properties, includeProductSorting }, context) => {
17
18
  const { cached, sapiClient } = context;
18
19
  const sanitizedPath = splitAndRemoveEmpty(path);
19
20
  return await cached(
@@ -25,8 +26,8 @@ export const getCategoryByPath = async function getCategoryByPath2({ path, child
25
26
  with: { children, properties, includeProductSorting },
26
27
  includeHidden
27
28
  });
28
- };
29
- export const getCategoriesByPath = async function getCategoriesByPath2({ path, children = 1, includeHidden, properties, includeProductSorting }, context) {
29
+ });
30
+ export const getCategoriesByPath = defineRpcHandler(async ({ path, children = 1, includeHidden, properties, includeProductSorting }, context) => {
30
31
  const { cached, sapiClient } = context;
31
32
  if (path === "/") {
32
33
  return getRootCategories(
@@ -78,8 +79,8 @@ export const getCategoriesByPath = async function getCategoriesByPath2({ path, c
78
79
  lastNode = rootPath[i];
79
80
  }
80
81
  return { categories: tree, activeNode: result };
81
- };
82
- export const getCategoryById = async function getCategoryById2({ id, children = 1, includeHidden, properties, includeProductSorting }, context) {
82
+ });
83
+ export const getCategoryById = defineRpcHandler(async ({ id, children = 1, includeHidden, properties, includeProductSorting }, context) => {
83
84
  const { cached, sapiClient } = context;
84
85
  return await cached(
85
86
  mapSAPIFetchErrorToResponse(sapiClient.categories.getById),
@@ -95,14 +96,14 @@ export const getCategoryById = async function getCategoryById2({ id, children =
95
96
  },
96
97
  includeHidden
97
98
  });
98
- };
99
- export const getCategoryTree = async function getCategoryTree2({
99
+ });
100
+ export const getCategoryTree = defineRpcHandler(async ({
100
101
  children,
101
102
  includeHidden,
102
103
  properties,
103
104
  hideEmptyCategories,
104
105
  includeProductSorting
105
- }, context) {
106
+ }, context) => {
106
107
  const { cached, sapiClient, callRpc } = context;
107
108
  const categoryTree = await cached(sapiClient.categories.getRoots, {
108
109
  cacheKeyPrefix: "root-categories"
@@ -142,4 +143,4 @@ export const getCategoryTree = async function getCategoryTree2({
142
143
  return categoryTree.filter(
143
144
  (category) => categoryProductCountTable[category.id] > 0
144
145
  );
145
- };
146
+ });
@@ -1,7 +1,8 @@
1
1
  import { HttpStatusCode, HttpStatusMessage } from "../../constants/index.mjs";
2
2
  import { ErrorResponse } from "../../errors/index.mjs";
3
+ import { defineRpcHandler } from "../../utils/index.mjs";
3
4
  import { encodeBase64, verifyOrderSuccessToken } from "../../utils/hash.mjs";
4
- export const getOrderDataByCbd = async function getOrderDataByCbd2({ cbdToken }, context) {
5
+ export const getOrderDataByCbd = defineRpcHandler(async ({ cbdToken }, context) => {
5
6
  const payload = await verifyOrderSuccessToken(
6
7
  cbdToken,
7
8
  context.checkout.secret
@@ -52,4 +53,4 @@ export const getOrderDataByCbd = async function getOrderDataByCbd2({ cbdToken },
52
53
  detail: `Fetching order failed with status code ${response.status}`
53
54
  }
54
55
  );
55
- };
56
+ });
@@ -3,7 +3,8 @@ import { hasSession } from "../../../types/index.mjs";
3
3
  import { ErrorResponse } from "../../../errors/index.mjs";
4
4
  import { HttpStatusCode, HttpStatusMessage } from "../../../constants/index.mjs";
5
5
  import { getAccessToken } from "../user.mjs";
6
- export const getCheckoutToken = async function getCheckoutToken2(jwtPayload = {}, context) {
6
+ import { defineRpcHandler } from "../../../utils/rpc.mjs";
7
+ export const getCheckoutToken = defineRpcHandler(async (jwtPayload = {}, context) => {
7
8
  if (!hasSession(context)) {
8
9
  return new ErrorResponse(
9
10
  HttpStatusCode.BAD_REQUEST,
@@ -36,9 +37,9 @@ export const getCheckoutToken = async function getCheckoutToken2(jwtPayload = {}
36
37
  carrier,
37
38
  basketId: context.basketKey,
38
39
  campaignKey
39
- }).setIssuedAt(now).setNotBefore(now).setExpirationTime("1h").setIssuer(`${"@scayle/storefront-core"}@${"8.33.1"}`).setProtectedHeader({ alg: "HS256", typ: "JWT" }).sign(secret);
40
+ }).setIssuedAt(now).setNotBefore(now).setExpirationTime("1h").setIssuer(`${"@scayle/storefront-core"}@${"8.34.0"}`).setProtectedHeader({ alg: "HS256", typ: "JWT" }).sign(secret);
40
41
  return {
41
42
  accessToken: refreshedAccessToken,
42
43
  checkoutJwt
43
44
  };
44
- };
45
+ });
@@ -5,7 +5,8 @@ import {
5
5
  HttpStatusCode,
6
6
  HttpStatusMessage
7
7
  } from "../../../constants/httpStatus.mjs";
8
- export const getOrderById = async function getOrderById2({ orderId }, context) {
8
+ import { defineRpcHandler } from "../../../utils/index.mjs";
9
+ export const getOrderById = defineRpcHandler(async ({ orderId }, context) => {
9
10
  const accessToken = context.accessToken;
10
11
  if (!orderId || isNaN(orderId)) {
11
12
  return new ErrorResponse(
@@ -49,4 +50,4 @@ export const getOrderById = async function getOrderById2({ orderId }, context) {
49
50
  "Unknown error"
50
51
  );
51
52
  }
52
- };
53
+ });
@@ -6,7 +6,8 @@ import {
6
6
  HttpStatusCode,
7
7
  HttpStatusMessage
8
8
  } from "../../../constants/httpStatus.mjs";
9
- export const updateShopUser = async function updateShopUser2(payload, context) {
9
+ import { defineRpcHandler } from "../../../utils/index.mjs";
10
+ export const updateShopUser = defineRpcHandler(async (payload, context) => {
10
11
  const shopId = context.shopId;
11
12
  const updatedUser = {
12
13
  email: payload.email,
@@ -55,8 +56,8 @@ export const updateShopUser = async function updateShopUser2(payload, context) {
55
56
  "Error while updating user information"
56
57
  );
57
58
  }
58
- };
59
- export const updatePassword = async function updatePassword2({ oldPassword, newPassword }, context) {
59
+ });
60
+ export const updatePassword = defineRpcHandler(async ({ oldPassword, newPassword }, context) => {
60
61
  const shopUser = context.user;
61
62
  const oauthEnabled = context.oauth?.apiHost && context.oauth?.clientId && context.oauth?.clientSecret;
62
63
  try {
@@ -120,4 +121,4 @@ export const updatePassword = async function updatePassword2({ oldPassword, newP
120
121
  }
121
122
  }
122
123
  return { user: shopUser };
123
- };
124
+ });
@@ -1,7 +1,10 @@
1
1
  import { CustomerAPIClient } from "../../../api/customer.mjs";
2
- const getShopUserAddresses = async function getShopUserAddresses2(context) {
3
- const shopId = context.shopId;
4
- const client = new CustomerAPIClient(context);
5
- return (await client.getAddresses(shopId)).entities;
6
- };
2
+ import { defineRpcHandler } from "../../../utils/index.mjs";
3
+ const getShopUserAddresses = defineRpcHandler(
4
+ async (context) => {
5
+ const shopId = context.shopId;
6
+ const client = new CustomerAPIClient(context);
7
+ return (await client.getAddresses(shopId)).entities;
8
+ }
9
+ );
7
10
  export { getShopUserAddresses };
@@ -1,18 +1,19 @@
1
1
  import { ErrorResponse } from "../../errors/index.mjs";
2
2
  import { HttpStatusCode, HttpStatusMessage } from "../../constants/index.mjs";
3
- export const fetchAllNavigationTrees = async function fetchAllNavigationTrees2({ params }, context) {
3
+ import { defineRpcHandler } from "../../utils/index.mjs";
4
+ export const fetchAllNavigationTrees = defineRpcHandler(async ({ params }, context) => {
4
5
  const { sapiClient: { navigation }, cached } = context;
5
6
  return await cached(navigation.getAll, {
6
7
  cacheKeyPrefix: "getAll-navigation-trees"
7
8
  })(params);
8
- };
9
- export const fetchNavigationTreeById = async function fetchNavigationTreeById2({ treeId, params }, context) {
9
+ });
10
+ export const fetchNavigationTreeById = defineRpcHandler(async ({ treeId, params }, context) => {
10
11
  const { sapiClient: { navigation }, cached } = context;
11
12
  return await cached(navigation.getById, {
12
13
  cacheKeyPrefix: `getById-navigation-trees-${treeId}`
13
14
  })(treeId, params);
14
- };
15
- export const fetchNavigationTreeByName = async function fetchNavigationTreeByName2({ treeName, params }, context) {
15
+ });
16
+ export const fetchNavigationTreeByName = defineRpcHandler(async ({ treeName, params }, context) => {
16
17
  const { sapiClient: { navigation }, cached } = context;
17
18
  return await cached(
18
19
  async (name, params2) => {
@@ -33,4 +34,4 @@ export const fetchNavigationTreeByName = async function fetchNavigationTreeByNam
33
34
  cacheKeyPrefix: `getByName-navigation-trees-${treeName}`
34
35
  }
35
36
  )(treeName, params);
36
- };
37
+ });
@@ -4,7 +4,8 @@ import { HttpStatusCode, HttpStatusMessage } from "../../../constants/index.mjs"
4
4
  import { hasSession } from "../../../types/index.mjs";
5
5
  import { getOAuthClient } from "../../../api/oauth.mjs";
6
6
  import { postLogin } from "../session.mjs";
7
- export const getExternalIdpRedirect = async function getExternalIdpRedirect2({ queryParams, authUrlParameters }, context) {
7
+ import { defineRpcHandler } from "../../../utils/index.mjs";
8
+ export const getExternalIdpRedirect = defineRpcHandler(async ({ queryParams, authUrlParameters }, context) => {
8
9
  if (!context.idp?.enabled) {
9
10
  return {};
10
11
  }
@@ -45,8 +46,8 @@ export const getExternalIdpRedirect = async function getExternalIdpRedirect2({ q
45
46
  })
46
47
  );
47
48
  return Object.fromEntries(results);
48
- };
49
- export const handleIDPLoginCallback = async function handleIDPLoginCallback2(payload, context) {
49
+ });
50
+ export const handleIDPLoginCallback = defineRpcHandler(async (payload, context) => {
50
51
  if (!hasSession(context)) {
51
52
  return new ErrorResponse(
52
53
  HttpStatusCode.BAD_REQUEST,
@@ -60,4 +61,4 @@ export const handleIDPLoginCallback = async function handleIDPLoginCallback2(pay
60
61
  return {
61
62
  message: "success"
62
63
  };
63
- };
64
+ });
@@ -3,13 +3,14 @@ import {
3
3
  PROMOTION_PER_PAGE_DEFAULT
4
4
  } from "../../constants/index.mjs";
5
5
  import { mapSAPIFetchErrorToResponse } from "../../utils/sapi.mjs";
6
+ import { defineRpcHandler } from "../../utils/index.mjs";
6
7
  const setPaginationDefault = (pagination) => {
7
8
  return {
8
9
  page: pagination?.page || PROMOTION_PAGE_DEFAULT,
9
10
  perPage: pagination?.perPage || PROMOTION_PER_PAGE_DEFAULT
10
11
  };
11
12
  };
12
- export const getPromotions = async function getPromotions2(params = {}, context) {
13
+ export const getPromotions = defineRpcHandler(async (params = {}, context) => {
13
14
  const { sapiClient, cached } = context;
14
15
  return await cached(mapSAPIFetchErrorToResponse(sapiClient.promotions.get), {
15
16
  cacheKeyPrefix: "getPromotions"
@@ -17,8 +18,8 @@ export const getPromotions = async function getPromotions2(params = {}, context)
17
18
  ...params,
18
19
  pagination: setPaginationDefault(params.pagination)
19
20
  });
20
- };
21
- export const getCurrentPromotions = async function getCurrentPromotions2(params = {}, context) {
21
+ });
22
+ export const getCurrentPromotions = defineRpcHandler(async (params = {}, context) => {
22
23
  const { sapiClient, cached } = context;
23
24
  const now = /* @__PURE__ */ new Date();
24
25
  now.setSeconds(0, 0);
@@ -30,8 +31,8 @@ export const getCurrentPromotions = async function getCurrentPromotions2(params
30
31
  activeAt,
31
32
  pagination: setPaginationDefault(params.pagination)
32
33
  });
33
- };
34
- export const getPromotionsByIds = async function getPromotionsByIds2(ids, context) {
34
+ });
35
+ export const getPromotionsByIds = defineRpcHandler(async (ids, context) => {
35
36
  const { sapiClient, cached } = context;
36
37
  return await cached(
37
38
  mapSAPIFetchErrorToResponse(sapiClient.promotions.getByIds),
@@ -39,4 +40,4 @@ export const getPromotionsByIds = async function getPromotionsByIds2(ids, contex
39
40
  cacheKeyPrefix: "getByIds-promotions"
40
41
  }
41
42
  )(ids);
42
- };
43
+ });
@@ -27,4 +27,4 @@ export declare const getSearchSuggestions: RpcHandler<SearchV2SuggestionsEndpoin
27
27
  *
28
28
  * @returns A promise that resolves to the resolved entity or null if no entity is found.
29
29
  */
30
- export declare const resolveSearch: RpcHandler<SearchV2ResolveEndpointParameters, Promise<SearchV2ResolveEndpointResponseData | null>>;
30
+ export declare const resolveSearch: RpcHandler<SearchV2ResolveEndpointParameters, SearchV2ResolveEndpointResponseData | null>;
@@ -1,5 +1,6 @@
1
1
  import { mapSAPIFetchErrorToResponse } from "../../utils/sapi.mjs";
2
- export const getSearchSuggestions = async function getSearchSuggestions2({ term, with: _with, categoryId }, context) {
2
+ import { defineRpcHandler } from "../../utils/index.mjs";
3
+ export const getSearchSuggestions = defineRpcHandler(async ({ term, with: _with, categoryId }, context) => {
3
4
  const { sapiClient, withParams } = context;
4
5
  return await mapSAPIFetchErrorToResponse(sapiClient.searchv2.suggestions)(
5
6
  term,
@@ -8,8 +9,8 @@ export const getSearchSuggestions = async function getSearchSuggestions2({ term,
8
9
  with: _with ?? withParams?.searchV2
9
10
  }
10
11
  );
11
- };
12
- export const resolveSearch = async function resolveSearch2({ term, with: _with, categoryId }, context) {
12
+ });
13
+ export const resolveSearch = defineRpcHandler(async ({ term, with: _with, categoryId }, context) => {
13
14
  const { cached, sapiClient, withParams } = context;
14
15
  const resolvedEntity = await cached(sapiClient.searchv2.resolve, {
15
16
  cacheKeyPrefix: `resolve-${term}`
@@ -21,4 +22,4 @@ export const resolveSearch = async function resolveSearch2({ term, with: _with,
21
22
  return null;
22
23
  }
23
24
  return resolvedEntity;
24
- };
25
+ });
@@ -11,6 +11,7 @@ import { fetchUser } from "../../rpc/methods/user.mjs";
11
11
  import { unwrap } from "../../utils/response.mjs";
12
12
  import { getOAuthClient } from "../../api/oauth.mjs";
13
13
  import { ErrorResponse } from "../../errors/index.mjs";
14
+ import { defineRpcHandler } from "../../utils/index.mjs";
14
15
  const convertErrorForRpcCall = (error, httpStatuses) => {
15
16
  if (error instanceof FetchError && httpStatuses.includes(error.response.status)) {
16
17
  return new ErrorResponse(
@@ -57,7 +58,7 @@ export async function postLogin(context, tokens) {
57
58
  accessToken: tokens.access_token
58
59
  }, context);
59
60
  }
60
- export const oauthLogin = async (login, context) => {
61
+ export const oauthLogin = defineRpcHandler(async (login, context) => {
61
62
  if (!hasSession(context)) {
62
63
  return new ErrorResponse(
63
64
  HttpStatusCode.BAD_REQUEST,
@@ -92,8 +93,8 @@ export const oauthLogin = async (login, context) => {
92
93
  "Login failed"
93
94
  );
94
95
  }
95
- };
96
- export const oauthRegister = async (register, context) => {
96
+ });
97
+ export const oauthRegister = defineRpcHandler(async (register, context) => {
97
98
  if (!hasSession(context)) {
98
99
  return new ErrorResponse(
99
100
  HttpStatusCode.BAD_REQUEST,
@@ -125,8 +126,8 @@ export const oauthRegister = async (register, context) => {
125
126
  "Register failed"
126
127
  );
127
128
  }
128
- };
129
- export const oauthGuestLogin = async (guest, context) => {
129
+ });
130
+ export const oauthGuestLogin = defineRpcHandler(async (guest, context) => {
130
131
  if (!hasSession(context)) {
131
132
  return new ErrorResponse(
132
133
  HttpStatusCode.BAD_REQUEST,
@@ -157,8 +158,8 @@ export const oauthGuestLogin = async (guest, context) => {
157
158
  "Guest login failed"
158
159
  );
159
160
  }
160
- };
161
- export const refreshAccessToken = async (context) => {
161
+ });
162
+ export const refreshAccessToken = defineRpcHandler(async (context) => {
162
163
  if (!hasSession(context)) {
163
164
  return new ErrorResponse(
164
165
  HttpStatusCode.BAD_REQUEST,
@@ -205,8 +206,8 @@ export const refreshAccessToken = async (context) => {
205
206
  }
206
207
  return { success: false };
207
208
  }
208
- };
209
- export const oauthRevokeToken = async (context) => {
209
+ });
210
+ export const oauthRevokeToken = defineRpcHandler(async (context) => {
210
211
  if (!hasSession(context)) {
211
212
  return new ErrorResponse(
212
213
  HttpStatusCode.BAD_REQUEST,
@@ -244,8 +245,8 @@ export const oauthRevokeToken = async (context) => {
244
245
  }
245
246
  return { result: false };
246
247
  }
247
- };
248
- export const oauthForgetPassword = async ({ email }, context) => {
248
+ });
249
+ export const oauthForgetPassword = defineRpcHandler(async ({ email }, context) => {
249
250
  if (!hasSession(context)) {
250
251
  return new ErrorResponse(
251
252
  HttpStatusCode.BAD_REQUEST,
@@ -287,8 +288,8 @@ export const oauthForgetPassword = async ({ email }, context) => {
287
288
  }
288
289
  return { success: false };
289
290
  }
290
- };
291
- export const updatePasswordByHash = async (passwordHash, context) => {
291
+ });
292
+ export const updatePasswordByHash = defineRpcHandler(async (passwordHash, context) => {
292
293
  if (!hasSession(context)) {
293
294
  return new ErrorResponse(
294
295
  HttpStatusCode.BAD_REQUEST,
@@ -324,4 +325,4 @@ export const updatePasswordByHash = async (passwordHash, context) => {
324
325
  );
325
326
  }
326
327
  return new Response(null, { status: HttpStatusCode.NO_CONTENT });
327
- };
328
+ });
@@ -1,5 +1,6 @@
1
1
  import { mapSAPIFetchErrorToResponse } from "../../utils/sapi.mjs";
2
- const getShopConfiguration = async function getShopConfiguration2(context) {
2
+ import { defineRpcHandler } from "../../utils/index.mjs";
3
+ const getShopConfiguration = defineRpcHandler(async (context) => {
3
4
  const { cached, sapiClient } = context;
4
5
  return await cached(
5
6
  mapSAPIFetchErrorToResponse(sapiClient.shopConfiguration.get),
@@ -7,5 +8,5 @@ const getShopConfiguration = async function getShopConfiguration2(context) {
7
8
  cacheKeyPrefix: "get-shopConfigurations"
8
9
  }
9
10
  )();
10
- };
11
+ });
11
12
  export { getShopConfiguration };
@@ -1,4 +1,4 @@
1
- import type { RpcContext, RpcHandler, ShopUser } from '../../types';
1
+ import type { RpcHandler, ShopUser } from '../../types';
2
2
  /**
3
3
  * Retrieves the user from the context.
4
4
  *
@@ -19,9 +19,9 @@ declare const getUser: RpcHandler<{
19
19
  * @returns The fetched user data. It will return an `ErrorResponse` alternatively
20
20
  * if an error occurs during the API call.
21
21
  */
22
- declare const fetchUser: ({ accessToken }: {
22
+ declare const fetchUser: RpcHandler<{
23
23
  accessToken?: string;
24
- }, context: RpcContext) => Promise<ShopUser>;
24
+ }, ShopUser>;
25
25
  /**
26
26
  * Refreshes the user session and data.
27
27
  * If the user is no longer logged in, the session is destroyed.
@@ -4,18 +4,21 @@ import { getOAuthClient } from "../../api/oauth.mjs";
4
4
  import { HttpStatusCode, HttpStatusMessage } from "../../constants/index.mjs";
5
5
  import { ErrorResponse } from "../../errors/index.mjs";
6
6
  import { FetchError } from "../../utils/fetch.mjs";
7
- const getUser = function getUser2(context) {
8
- const { user } = context;
9
- if (user) {
10
- user.authentication = user.authentication ?? {
11
- type: "idp"
7
+ import { defineRpcHandler } from "../../utils/rpc.mjs";
8
+ const getUser = defineRpcHandler(
9
+ (context) => {
10
+ const { user } = context;
11
+ if (user) {
12
+ user.authentication = user.authentication ?? {
13
+ type: "idp"
14
+ };
15
+ }
16
+ return {
17
+ user
12
18
  };
13
19
  }
14
- return {
15
- user
16
- };
17
- };
18
- const fetchUser = async function fetchUser2({ accessToken }, context) {
20
+ );
21
+ const fetchUser = defineRpcHandler(async ({ accessToken }, context) => {
19
22
  const { shopId } = context;
20
23
  const client = new CustomerAPIClient(context);
21
24
  const user = await client.getMe(shopId, accessToken);
@@ -28,8 +31,8 @@ const fetchUser = async function fetchUser2({ accessToken }, context) {
28
31
  ({ shopId: shopId2 }) => shopId2 === context.shopId
29
32
  );
30
33
  return user;
31
- };
32
- const refreshUser = async function refreshUser2(context) {
34
+ });
35
+ const refreshUser = defineRpcHandler(async (context) => {
33
36
  if (!hasSession(context)) {
34
37
  return new ErrorResponse(
35
38
  HttpStatusCode.BAD_REQUEST,
@@ -52,8 +55,8 @@ const refreshUser = async function refreshUser2(context) {
52
55
  await context.destroySession();
53
56
  return { user: void 0 };
54
57
  }
55
- };
56
- const getAccessToken = async function getAccessToken2({ forceTokenRefresh = false } = { forceTokenRefresh: false }, context) {
58
+ });
59
+ const getAccessToken = defineRpcHandler(async ({ forceTokenRefresh = false } = { forceTokenRefresh: false }, context) => {
57
60
  if (!hasSession(context)) {
58
61
  return new ErrorResponse(
59
62
  HttpStatusCode.BAD_REQUEST,
@@ -100,5 +103,5 @@ const getAccessToken = async function getAccessToken2({ forceTokenRefresh = fals
100
103
  }
101
104
  }
102
105
  return context.accessToken;
103
- };
106
+ });
104
107
  export { getUser, fetchUser, refreshUser, getAccessToken };
@@ -1,8 +1,9 @@
1
1
  import { mapSAPIFetchErrorToResponse } from "../../utils/sapi.mjs";
2
+ import { defineRpcHandler } from "../../utils/rpc.mjs";
2
3
  const defaultWith = {
3
4
  attributes: "all"
4
5
  };
5
- export const getVariantById = async function getVariantById2({ ids, include = defaultWith, pricePromotionKey = "default" }, context) {
6
+ export const getVariantById = defineRpcHandler(async ({ ids, include = defaultWith, pricePromotionKey = "default" }, context) => {
6
7
  const { sapiClient, cached, withParams } = context;
7
8
  const campaignKey = await context.callRpc?.("getCampaignKey");
8
9
  const resolvedWith = include ?? withParams?.variant ?? defaultWith;
@@ -15,4 +16,4 @@ export const getVariantById = async function getVariantById2({ ids, include = de
15
16
  ids,
16
17
  include ? { with: resolvedWith, campaignKey, pricePromotionKey } : void 0
17
18
  );
18
- };
19
+ });
@@ -7,32 +7,35 @@ import {
7
7
  import { unwrap } from "../../utils/response.mjs";
8
8
  import { ErrorResponse } from "../../errors/index.mjs";
9
9
  import { mapSAPIFetchErrorToResponse } from "../../utils/sapi.mjs";
10
+ import { defineRpcHandler } from "../../utils/index.mjs";
10
11
  function getWithParams(params, context) {
11
12
  return params.with ?? context.withParams?.wishlist ?? MIN_WITH_PARAMS_WISHLIST;
12
13
  }
13
- export const getWishlist = async function getWishlist2(options, context) {
14
- if (!hasSession(context)) {
15
- return new ErrorResponse(
16
- HttpStatusCode.BAD_REQUEST,
17
- HttpStatusMessage.BAD_REQUEST,
18
- "No Session found"
14
+ export const getWishlist = defineRpcHandler(
15
+ async (options, context) => {
16
+ if (!hasSession(context)) {
17
+ return new ErrorResponse(
18
+ HttpStatusCode.BAD_REQUEST,
19
+ HttpStatusMessage.BAD_REQUEST,
20
+ "No Session found"
21
+ );
22
+ }
23
+ const { sapiClient, wishlistKey } = context;
24
+ const campaignKey = await context.callRpc?.("getCampaignKey");
25
+ const { pricePromotionKey, ...resolvedWith } = getWithParams({
26
+ with: options
27
+ }, context);
28
+ return await mapSAPIFetchErrorToResponse(sapiClient.wishlist.get)(
29
+ wishlistKey,
30
+ {
31
+ with: resolvedWith,
32
+ campaignKey,
33
+ pricePromotionKey: pricePromotionKey ?? ""
34
+ }
19
35
  );
20
36
  }
21
- const { sapiClient, wishlistKey } = context;
22
- const campaignKey = await context.callRpc?.("getCampaignKey");
23
- const { pricePromotionKey, ...resolvedWith } = getWithParams({
24
- with: options
25
- }, context);
26
- return await mapSAPIFetchErrorToResponse(sapiClient.wishlist.get)(
27
- wishlistKey,
28
- {
29
- with: resolvedWith,
30
- campaignKey,
31
- pricePromotionKey: pricePromotionKey ?? ""
32
- }
33
- );
34
- };
35
- export const addItemToWishlist = async function addItemToWishlist2(options, context) {
37
+ );
38
+ export const addItemToWishlist = defineRpcHandler(async (options, context) => {
36
39
  if (!hasSession(context)) {
37
40
  return new ErrorResponse(
38
41
  HttpStatusCode.BAD_REQUEST,
@@ -67,8 +70,8 @@ export const addItemToWishlist = async function addItemToWishlist2(options, cont
67
70
  context.log.error("Adding to wishlist failed", result.wishlist);
68
71
  return new Response(JSON.stringify({ kind, type }), { status: code });
69
72
  }
70
- };
71
- export const removeItemFromWishlist = async function removeItemFromWishlist2(options, context) {
73
+ });
74
+ export const removeItemFromWishlist = defineRpcHandler(async (options, context) => {
72
75
  if (!hasSession(context)) {
73
76
  return new ErrorResponse(
74
77
  HttpStatusCode.BAD_REQUEST,
@@ -88,17 +91,19 @@ export const removeItemFromWishlist = async function removeItemFromWishlist2(opt
88
91
  pricePromotionKey: pricePromotionKey ?? ""
89
92
  }
90
93
  );
91
- };
92
- export const clearWishlist = async function clearWishlist2(context) {
93
- const wishlistResponse = await getWishlist({}, context);
94
- if (wishlistResponse instanceof ErrorResponse) {
95
- return wishlistResponse;
94
+ });
95
+ export const clearWishlist = defineRpcHandler(
96
+ async (context) => {
97
+ const wishlistResponse = await getWishlist({}, context);
98
+ if (wishlistResponse instanceof ErrorResponse) {
99
+ return wishlistResponse;
100
+ }
101
+ const wishlist = await unwrap(wishlistResponse);
102
+ await Promise.all(
103
+ wishlist.items.map(async (item) => {
104
+ await removeItemFromWishlist({ itemKey: item.key }, context);
105
+ })
106
+ );
107
+ return await getWishlist({}, context);
96
108
  }
97
- const wishlist = await unwrap(wishlistResponse);
98
- await Promise.all(
99
- wishlist.items.map(async (item) => {
100
- await removeItemFromWishlist({ itemKey: item.key }, context);
101
- })
102
- );
103
- return await getWishlist({}, context);
104
- };
109
+ );
@@ -7,14 +7,14 @@ type RpcType = 'NoParam' | 'WithParam';
7
7
  * @param handler - The RPC handler function.
8
8
  * @returns The handler itself, with correct types enforced and internal properties set.
9
9
  */
10
- export declare function defineRpcHandler<Params extends Record<string, unknown>, Result = unknown>(handler: (params: Params, context: RpcContext) => Result | Promise<Result>): RpcHandler<Params, Result>;
10
+ export declare function defineRpcHandler<Params extends Record<string, any> | undefined, Result>(handler: (params: Params, context: RpcContext) => Result | Response | Promise<Result | Response>): RpcHandler<Params, Result>;
11
11
  /**
12
12
  * Defines an RPC method handler.
13
13
  *
14
14
  * @param handler - The RPC handler function.
15
15
  * @returns The handler itself, with correct types enforced and internal properties set.
16
16
  */
17
- export declare function defineRpcHandler<Result = unknown>(handler: (context: RpcContext) => Result | Promise<Result>): RpcHandler<Result>;
17
+ export declare function defineRpcHandler<Result>(handler: (context: RpcContext) => Result | Response | Promise<Result | Response>): RpcHandler<Result>;
18
18
  /**
19
19
  * Defines an RPC method handler.
20
20
  *
@@ -1,8 +1,7 @@
1
1
  import { ExistingItemHandling } from "@scayle/storefront-api";
2
- import { getCampaignKey } from "../rpc/methods/index.mjs";
3
2
  export const mergeBaskets = async (fromBasketKey, toBasketKey, withOptions, context) => {
4
3
  const { sapiClient } = context;
5
- const campaignKey = await getCampaignKey(context);
4
+ const campaignKey = await context.callRpc?.("getCampaignKey");
6
5
  const fromOriginBasket = await sapiClient.basket.get(fromBasketKey, {
7
6
  with: withOptions,
8
7
  campaignKey,
@@ -46,7 +45,7 @@ export const mergeBaskets = async (fromBasketKey, toBasketKey, withOptions, cont
46
45
  };
47
46
  export const mergeWishlists = async (fromWishlistKey, toWishlistKey, withOptions, context) => {
48
47
  const { sapiClient } = context;
49
- const campaignKey = await getCampaignKey(context);
48
+ const campaignKey = await context.callRpc?.("getCampaignKey");
50
49
  const oldWishlist = await sapiClient.wishlist.get(fromWishlistKey, {
51
50
  with: withOptions,
52
51
  campaignKey
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scayle/storefront-core",
3
- "version": "8.33.1",
3
+ "version": "8.34.0",
4
4
  "description": "Collection of essential utilities to work with the Storefront API",
5
5
  "author": "SCAYLE Commerce Engine",
6
6
  "license": "MIT",
@@ -61,7 +61,7 @@
61
61
  },
62
62
  "devDependencies": {
63
63
  "@types/crypto-js": "4.2.2",
64
- "@types/node": "22.16.0",
64
+ "@types/node": "22.16.3",
65
65
  "@types/webpack-env": "1.18.8",
66
66
  "@vitest/coverage-v8": "3.2.4",
67
67
  "dprint": "0.50.1",
@@ -74,7 +74,7 @@
74
74
  "unbuild": "3.5.0",
75
75
  "unstorage": "1.16.0",
76
76
  "vitest": "3.2.4",
77
- "@scayle/eslint-config-storefront": "4.5.12"
77
+ "@scayle/eslint-config-storefront": "4.5.13"
78
78
  },
79
79
  "volta": {
80
80
  "node": "22.17.0"