@labdigital/commercetools-mock 2.60.0 → 2.61.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 (222) hide show
  1. package/dist/{index.d.ts → index.d.mts} +154 -275
  2. package/dist/{index.js → index.mjs} +241 -349
  3. package/dist/index.mjs.map +1 -0
  4. package/package.json +30 -18
  5. package/src/config.ts +1 -1
  6. package/src/ctMock.test.ts +1 -1
  7. package/src/ctMock.ts +22 -21
  8. package/src/index.test.ts +1 -1
  9. package/src/index.ts +3 -3
  10. package/src/lib/haversine.test.ts +2 -2
  11. package/src/lib/masking.ts +1 -1
  12. package/src/lib/parser.ts +2 -2
  13. package/src/lib/password.ts +1 -1
  14. package/src/lib/predicateParser.test.ts +1 -1
  15. package/src/lib/predicateParser.ts +4 -4
  16. package/src/lib/product-review-statistics.test.ts +4 -8
  17. package/src/lib/productSearchFilter.test.ts +3 -3
  18. package/src/lib/productSearchFilter.ts +6 -6
  19. package/src/lib/projectionSearchFilter.test.ts +3 -3
  20. package/src/lib/projectionSearchFilter.ts +4 -4
  21. package/src/lib/review-statistics.ts +1 -1
  22. package/src/lib/searchQueryTypeChecker.test.ts +3 -3
  23. package/src/lib/searchQueryTypeChecker.ts +8 -4
  24. package/src/lib/tax.test.ts +3 -3
  25. package/src/lib/tax.ts +3 -3
  26. package/src/oauth/server.test.ts +7 -7
  27. package/src/oauth/server.ts +7 -7
  28. package/src/priceSelector.test.ts +1 -1
  29. package/src/priceSelector.ts +2 -2
  30. package/src/product-projection-search.ts +10 -12
  31. package/src/product-search-availability.test.ts +1 -1
  32. package/src/product-search.ts +6 -7
  33. package/src/projectAPI.test.ts +1 -1
  34. package/src/projectAPI.ts +7 -7
  35. package/src/repositories/abstract.ts +8 -10
  36. package/src/repositories/as-associate.test.ts +4 -4
  37. package/src/repositories/as-associate.ts +3 -3
  38. package/src/repositories/associate-role.ts +7 -9
  39. package/src/repositories/attribute-group.test.ts +3 -3
  40. package/src/repositories/attribute-group.ts +5 -5
  41. package/src/repositories/business-unit.test.ts +6 -6
  42. package/src/repositories/business-unit.ts +21 -23
  43. package/src/repositories/cart/actions.ts +12 -15
  44. package/src/repositories/cart/helpers.ts +5 -5
  45. package/src/repositories/cart/index.test.ts +5 -10
  46. package/src/repositories/cart/index.ts +13 -18
  47. package/src/repositories/cart-discount/actions.ts +5 -6
  48. package/src/repositories/cart-discount/index.ts +5 -5
  49. package/src/repositories/category/actions.ts +4 -4
  50. package/src/repositories/category/index.test.ts +3 -3
  51. package/src/repositories/category/index.ts +8 -8
  52. package/src/repositories/channel.test.ts +4 -4
  53. package/src/repositories/channel.ts +6 -6
  54. package/src/repositories/custom-object.ts +11 -8
  55. package/src/repositories/customer/actions.ts +9 -9
  56. package/src/repositories/customer/index.test.ts +3 -3
  57. package/src/repositories/customer/index.ts +12 -9
  58. package/src/repositories/customer-group.test.ts +4 -4
  59. package/src/repositories/customer-group.ts +6 -6
  60. package/src/repositories/discount-code/actions.ts +4 -4
  61. package/src/repositories/discount-code/index.ts +5 -5
  62. package/src/repositories/discount-group/actions.ts +3 -4
  63. package/src/repositories/discount-group/index.ts +4 -4
  64. package/src/repositories/errors.ts +1 -1
  65. package/src/repositories/extension.test.ts +3 -3
  66. package/src/repositories/extension.ts +6 -6
  67. package/src/repositories/helpers.ts +9 -12
  68. package/src/repositories/index.test.ts +3 -3
  69. package/src/repositories/index.ts +43 -43
  70. package/src/repositories/inventory-entry/actions.ts +15 -3
  71. package/src/repositories/inventory-entry/index.ts +5 -5
  72. package/src/repositories/my-customer.ts +5 -5
  73. package/src/repositories/my-order.ts +2 -2
  74. package/src/repositories/my-quote-request.ts +1 -1
  75. package/src/repositories/order/actions.ts +8 -9
  76. package/src/repositories/order/index.test.ts +8 -9
  77. package/src/repositories/order/index.ts +16 -17
  78. package/src/repositories/order-edit.ts +4 -4
  79. package/src/repositories/payment/actions.ts +6 -6
  80. package/src/repositories/payment/helpers.ts +3 -3
  81. package/src/repositories/payment/index.ts +7 -7
  82. package/src/repositories/product/actions.ts +7 -7
  83. package/src/repositories/product/helpers.ts +4 -4
  84. package/src/repositories/product/index.ts +13 -13
  85. package/src/repositories/product-discount.ts +9 -6
  86. package/src/repositories/product-projection.ts +7 -7
  87. package/src/repositories/product-selection.ts +9 -6
  88. package/src/repositories/product-tailoring.ts +6 -3
  89. package/src/repositories/product-type.ts +8 -5
  90. package/src/repositories/project.ts +5 -5
  91. package/src/repositories/quote/actions.ts +6 -6
  92. package/src/repositories/quote/index.ts +5 -5
  93. package/src/repositories/quote-request/actions.ts +6 -6
  94. package/src/repositories/quote-request/index.test.ts +3 -3
  95. package/src/repositories/quote-request/index.ts +5 -5
  96. package/src/repositories/quote-staged/actions.ts +6 -6
  97. package/src/repositories/quote-staged/index.ts +5 -5
  98. package/src/repositories/recurrence-policy/actions.ts +3 -3
  99. package/src/repositories/recurrence-policy/index.ts +4 -8
  100. package/src/repositories/recurring-order/actions.ts +3 -3
  101. package/src/repositories/recurring-order/index.ts +5 -5
  102. package/src/repositories/review.test.ts +5 -5
  103. package/src/repositories/review.ts +10 -9
  104. package/src/repositories/shipping-method/actions.ts +7 -9
  105. package/src/repositories/shipping-method/helpers.ts +1 -1
  106. package/src/repositories/shipping-method/index.ts +8 -8
  107. package/src/repositories/shopping-list/actions.ts +5 -5
  108. package/src/repositories/shopping-list/index.ts +7 -7
  109. package/src/repositories/standalone-price.ts +9 -6
  110. package/src/repositories/state.ts +9 -6
  111. package/src/repositories/store.ts +10 -7
  112. package/src/repositories/subscription.test.ts +3 -3
  113. package/src/repositories/subscription.ts +9 -6
  114. package/src/repositories/tax-category/actions.ts +4 -4
  115. package/src/repositories/tax-category/index.ts +6 -6
  116. package/src/repositories/type/actions.ts +4 -4
  117. package/src/repositories/type/index.ts +5 -5
  118. package/src/repositories/zone.test.ts +3 -3
  119. package/src/repositories/zone.ts +8 -5
  120. package/src/server.ts +4 -3
  121. package/src/services/abstract.ts +5 -5
  122. package/src/services/as-associate-cart.test.ts +1 -1
  123. package/src/services/as-associate-cart.ts +2 -2
  124. package/src/services/as-associate-order.test.ts +1 -1
  125. package/src/services/as-associate-order.ts +2 -2
  126. package/src/services/as-associate-quote-request.ts +2 -3
  127. package/src/services/as-associate.test.ts +1 -1
  128. package/src/services/as-associate.ts +4 -4
  129. package/src/services/associate-roles.test.ts +1 -1
  130. package/src/services/associate-roles.ts +2 -2
  131. package/src/services/attribute-group.test.ts +1 -1
  132. package/src/services/attribute-group.ts +2 -2
  133. package/src/services/business-units.test.ts +5 -5
  134. package/src/services/business-units.ts +2 -2
  135. package/src/services/cart-discount.ts +2 -2
  136. package/src/services/cart.test.ts +2 -2
  137. package/src/services/cart.ts +4 -5
  138. package/src/services/category.test.ts +1 -1
  139. package/src/services/category.ts +2 -2
  140. package/src/services/channel.test.ts +1 -1
  141. package/src/services/channel.ts +2 -2
  142. package/src/services/custom-object.test.ts +2 -2
  143. package/src/services/custom-object.ts +3 -3
  144. package/src/services/customer-group.test.ts +1 -1
  145. package/src/services/customer-group.ts +2 -2
  146. package/src/services/customer.test.ts +3 -3
  147. package/src/services/customer.ts +4 -5
  148. package/src/services/discount-code.test.ts +1 -1
  149. package/src/services/discount-code.ts +2 -2
  150. package/src/services/discount-group.test.ts +1 -1
  151. package/src/services/discount-group.ts +2 -2
  152. package/src/services/extension.test.ts +1 -1
  153. package/src/services/extension.ts +2 -2
  154. package/src/services/index.ts +44 -44
  155. package/src/services/inventory-entry.test.ts +16 -1
  156. package/src/services/inventory-entry.ts +2 -2
  157. package/src/services/my-business-unit.test.ts +1 -1
  158. package/src/services/my-business-unit.ts +2 -2
  159. package/src/services/my-cart.test.ts +1 -1
  160. package/src/services/my-cart.ts +2 -2
  161. package/src/services/my-customer.test.ts +2 -2
  162. package/src/services/my-customer.ts +6 -6
  163. package/src/services/my-order.ts +2 -2
  164. package/src/services/my-payment.test.ts +1 -1
  165. package/src/services/my-payment.ts +2 -2
  166. package/src/services/my-shopping-list.ts +2 -2
  167. package/src/services/order.test.ts +4 -11
  168. package/src/services/order.ts +4 -4
  169. package/src/services/payment.test.ts +1 -1
  170. package/src/services/payment.ts +2 -2
  171. package/src/services/product-discount.test.ts +1 -1
  172. package/src/services/product-discount.ts +2 -2
  173. package/src/services/product-projection.test.ts +2 -2
  174. package/src/services/product-projection.ts +4 -4
  175. package/src/services/product-selection.test.ts +1 -1
  176. package/src/services/product-selection.ts +2 -2
  177. package/src/services/product-type.test.ts +1 -1
  178. package/src/services/product-type.ts +2 -2
  179. package/src/services/product.test.ts +1 -1
  180. package/src/services/product.ts +3 -3
  181. package/src/services/project.test.ts +1 -1
  182. package/src/services/project.ts +4 -4
  183. package/src/services/quote-request.test.ts +2 -2
  184. package/src/services/quote-request.ts +2 -2
  185. package/src/services/quote-staged.ts +2 -2
  186. package/src/services/quote.ts +2 -2
  187. package/src/services/recurrence-policy.test.ts +1 -1
  188. package/src/services/recurrence-policy.ts +2 -2
  189. package/src/services/recurring-order.test.ts +1 -1
  190. package/src/services/recurring-order.ts +2 -2
  191. package/src/services/reviews.test.ts +1 -1
  192. package/src/services/reviews.ts +2 -2
  193. package/src/services/shipping-method.test.ts +2 -2
  194. package/src/services/shipping-method.ts +4 -4
  195. package/src/services/shopping-list.test.ts +1 -1
  196. package/src/services/shopping-list.ts +2 -2
  197. package/src/services/standalone-price.test.ts +1 -1
  198. package/src/services/standalone-price.ts +2 -2
  199. package/src/services/state.test.ts +1 -1
  200. package/src/services/state.ts +2 -2
  201. package/src/services/store.test.ts +1 -1
  202. package/src/services/store.ts +2 -2
  203. package/src/services/subscription.test.ts +1 -1
  204. package/src/services/subscription.ts +2 -2
  205. package/src/services/tax-category.test.ts +1 -1
  206. package/src/services/tax-category.ts +2 -2
  207. package/src/services/type.test.ts +1 -1
  208. package/src/services/type.ts +2 -2
  209. package/src/services/zone.test.ts +1 -1
  210. package/src/services/zone.ts +2 -2
  211. package/src/shipping.test.ts +1 -1
  212. package/src/shipping.ts +8 -8
  213. package/src/storage/abstract.ts +1 -1
  214. package/src/storage/in-memory.ts +15 -17
  215. package/src/storage/index.ts +2 -2
  216. package/src/testing/business-unit.ts +1 -2
  217. package/src/testing/customer.ts +1 -1
  218. package/src/testing/type.ts +1 -1
  219. package/src/types.ts +1 -1
  220. package/src/validate.ts +1 -1
  221. package/dist/index.d.ts.map +0 -1
  222. package/dist/index.js.map +0 -1
@@ -36,8 +36,8 @@ var CommercetoolsError = class extends Error {
36
36
  //#region src/helpers.ts
37
37
  const getBaseResourceProperties = () => ({
38
38
  id: v4(),
39
- createdAt: new Date().toISOString(),
40
- lastModifiedAt: new Date().toISOString(),
39
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
40
+ lastModifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
41
41
  version: 0
42
42
  });
43
43
  /**
@@ -50,21 +50,20 @@ const nestedLookup = (obj, path) => {
50
50
  let val = obj;
51
51
  for (let i = 0; i < parts.length; i++) {
52
52
  const part = parts[i];
53
- if (val === void 0) return void 0;
53
+ if (val === void 0) return;
54
54
  val = val[part];
55
55
  }
56
56
  return val;
57
57
  };
58
58
  const queryParamsArray = (input) => {
59
- if (input === void 0) return void 0;
59
+ if (input === void 0) return;
60
60
  const values = Array.isArray(input) ? input : [input];
61
- if (values.length < 1) return void 0;
61
+ if (values.length < 1) return;
62
62
  return values;
63
63
  };
64
64
  const queryParamsValue = (value) => {
65
65
  const values = queryParamsArray(value);
66
66
  if (values && values.length > 0) return values[0];
67
- return void 0;
68
67
  };
69
68
  const cloneObject = (o) => JSON.parse(JSON.stringify(o));
70
69
  const mapHeaderType = (outgoingHttpHeaders) => {
@@ -80,7 +79,7 @@ const generateRandomString = (length) => {
80
79
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
81
80
  let result = "";
82
81
  for (let i = 0; i < length; i++) {
83
- const randomIndex = Math.floor(Math.random() * characters.length);
82
+ const randomIndex = Math.floor(Math.random() * 62);
84
83
  result += characters[randomIndex];
85
84
  }
86
85
  return result;
@@ -108,26 +107,22 @@ const hashPassword = (clearPassword) => Buffer.from(clearPassword).toString("bas
108
107
  const createPasswordResetToken = (customer, expiresAt) => Buffer.from(`${customer.id}:${PWRESET_SECRET}:${expiresAt.getTime()}`).toString("base64");
109
108
  const createEmailVerifyToken = (customer) => Buffer.from(`${customer.id}:${EMAIL_VERIFY_SECRET}:${v4()}`).toString("base64");
110
109
  const validatePasswordResetToken = (token) => {
111
- const items = Buffer.from(token, "base64").toString("utf-8").split(":");
112
- const [customerId, secret, time] = items;
113
- if (secret !== PWRESET_SECRET) return void 0;
114
- if (Number.parseInt(time) < new Date().getTime()) return void 0;
110
+ const [customerId, secret, time] = Buffer.from(token, "base64").toString("utf-8").split(":");
111
+ if (secret !== PWRESET_SECRET) return;
112
+ if (Number.parseInt(time, 10) < Date.now()) return;
115
113
  return customerId;
116
114
  };
117
115
  const validateEmailVerifyToken = (token) => {
118
- const items = Buffer.from(token, "base64").toString("utf-8").split(":");
119
- const [customerId, secret] = items;
120
- if (secret !== EMAIL_VERIFY_SECRET) return void 0;
116
+ const [customerId, secret] = Buffer.from(token, "base64").toString("utf-8").split(":");
117
+ if (secret !== EMAIL_VERIFY_SECRET) return;
121
118
  return customerId;
122
119
  };
123
120
 
124
121
  //#endregion
125
122
  //#region src/oauth/helpers.ts
126
123
  const getBearerToken = (request) => {
127
- const authHeader = request.header("Authorization");
128
- const match = authHeader?.match(/^Bearer\s(?<token>[^\s]+)$/);
124
+ const match = request.header("Authorization")?.match(/^Bearer\s(?<token>[^\s]+)$/);
129
125
  if (match) return match.groups?.token;
130
- return void 0;
131
126
  };
132
127
 
133
128
  //#endregion
@@ -177,7 +172,7 @@ var OAuth2Store = class {
177
172
  }
178
173
  refreshToken(clientId, clientSecret, refreshToken) {
179
174
  const existing = this.tokens.find((t) => t.refresh_token === refreshToken);
180
- if (!existing) return void 0;
175
+ if (!existing) return;
181
176
  const token = {
182
177
  ...existing,
183
178
  access_token: randomBytes(16).toString("base64")
@@ -192,8 +187,7 @@ var OAuth2Store = class {
192
187
  }
193
188
  validateToken(token) {
194
189
  if (!this.validate) return true;
195
- const foundToken = this.tokens.find((t) => t.access_token === token);
196
- if (foundToken) return true;
190
+ if (this.tokens.find((t) => t.access_token === token)) return true;
197
191
  return false;
198
192
  }
199
193
  };
@@ -346,8 +340,7 @@ var OAuth2Server = class {
346
340
  }, 400));
347
341
  if (grantType === "client_credentials") {
348
342
  const scope = request.query.scope?.toString() || request.body?.scope?.toString();
349
- const anonymous_id = void 0;
350
- const token = this.store.getAnonymousToken(projectKey, anonymous_id, scope);
343
+ const token = this.store.getAnonymousToken(projectKey, void 0, scope);
351
344
  response.status(200).send(token);
352
345
  return;
353
346
  }
@@ -372,8 +365,7 @@ var ProjectAPI = class {
372
365
  this.unsafeAdd(typeId, resource);
373
366
  }
374
367
  unsafeAdd(typeId, resource) {
375
- const repository = this._repositories[typeId];
376
- if (repository) this._storage.add(this.projectKey, typeId, {
368
+ if (this._repositories[typeId]) this._storage.add(this.projectKey, typeId, {
377
369
  ...getBaseResourceProperties(),
378
370
  ...resource
379
371
  });
@@ -463,7 +455,7 @@ var AbstractResourceRepository = class extends AbstractRepository {
463
455
  }, 400);
464
456
  checkConcurrentModification(current.version, version, resource.id);
465
457
  if (current.version === resource.version) throw new Error("Internal error: no changes to save");
466
- resource.lastModifiedAt = new Date().toISOString();
458
+ resource.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
467
459
  this._storage.add(context.projectKey, this.getTypeId(), resource);
468
460
  return resource;
469
461
  }
@@ -478,22 +470,16 @@ var AbstractUpdateHandler = class {
478
470
  const updatedResource = cloneObject(resource);
479
471
  const identifier = resource.id ? resource.id : resource.key;
480
472
  for (const action of actions) {
481
- if (this[action.action] === void 0) {
482
- console.info(`No handler for action ${action.action}`);
483
- throw new CommercetoolsError({
473
+ if (this[action.action] === void 0) throw new CommercetoolsError({
474
+ code: "InvalidInput",
475
+ message: `Invalid action ${action.action}`,
476
+ errors: [{
484
477
  code: "InvalidInput",
485
- message: `Invalid action ${action.action}`,
486
- errors: [{
487
- code: "InvalidInput",
488
- message: `Invalid action ${action.action}`
489
- }]
490
- });
491
- }
478
+ message: `Invalid action ${action.action}`
479
+ }]
480
+ });
492
481
  const updateFunc = this[action.action].bind(this);
493
- if (!updateFunc) {
494
- console.error(`No mock implemented for update action ${action.action}`);
495
- throw new Error(`No mock implemented for update action ${action.action}`);
496
- }
482
+ if (!updateFunc) throw new Error(`No mock implemented for update action ${action.action}`);
497
483
  const beforeUpdate = cloneObject(resource);
498
484
  updateFunc(context, updatedResource, action);
499
485
  if (!isDeepStrictEqual(beforeUpdate, updatedResource)) {
@@ -601,17 +587,15 @@ const createCentPrecisionMoney = (value) => {
601
587
  };
602
588
  };
603
589
  const createTypedMoney = (value) => {
604
- const result = createCentPrecisionMoney(value);
605
- return result;
590
+ return createCentPrecisionMoney(value);
606
591
  };
607
592
  const resolveStoreReference = (ref, projectKey, storage) => {
608
593
  if (!ref) return void 0;
609
594
  const resource = storage.getByResourceIdentifier(projectKey, ref);
610
595
  if (!resource) throw new Error("No such store");
611
- const store = resource;
612
596
  return {
613
597
  typeId: "store",
614
- key: store.key
598
+ key: resource.key
615
599
  };
616
600
  };
617
601
  const getReferenceFromResourceIdentifier = (resourceIdentifier, projectKey, storage) => {
@@ -713,7 +697,7 @@ const calculateTaxTotals = (resource) => {
713
697
  let totalNet = 0;
714
698
  let totalGross = 0;
715
699
  let totalTax = 0;
716
- const taxPortionsByRate = new Map();
700
+ const taxPortionsByRate = /* @__PURE__ */ new Map();
717
701
  taxedItemPrices.forEach((price) => {
718
702
  totalNet += price.totalNet.centAmount;
719
703
  totalGross += price.totalGross.centAmount;
@@ -746,7 +730,7 @@ const calculateTaxTotals = (resource) => {
746
730
  };
747
731
  };
748
732
  const buildTaxedPriceFromRate = (amount, currencyCode, taxRate) => {
749
- if (!taxRate) return void 0;
733
+ if (!taxRate) return;
750
734
  const toMoney = (centAmount) => createCentPrecisionMoney({
751
735
  type: "centPrecision",
752
736
  currencyCode,
@@ -777,10 +761,9 @@ const buildTaxedPriceFromRate = (amount, currencyCode, taxRate) => {
777
761
  };
778
762
  const calculateTaxedPriceFromRate = (amount, currencyCode, taxRate) => buildTaxedPriceFromRate(amount, currencyCode, taxRate);
779
763
  const calculateTaxedPrice = (amount, taxCategory, currency, country) => {
780
- if (!taxCategory || !taxCategory.rates.length) return void 0;
781
- const taxRate = taxCategory.rates.find((rate) => !rate.country || rate.country === country) || taxCategory.rates[0];
782
- const taxedItemPrice = buildTaxedPriceFromRate(amount, currency, taxRate);
783
- if (!taxedItemPrice) return void 0;
764
+ if (!taxCategory || !taxCategory.rates.length) return;
765
+ const taxedItemPrice = buildTaxedPriceFromRate(amount, currency, taxCategory.rates.find((rate) => !rate.country || rate.country === country) || taxCategory.rates[0]);
766
+ if (!taxedItemPrice) return;
784
767
  return {
785
768
  totalNet: taxedItemPrice.totalNet,
786
769
  totalGross: taxedItemPrice.totalGross,
@@ -827,11 +810,10 @@ const getShippingMethodsMatchingCart = (context, storage, cart, params = {}) =>
827
810
  code: "InvalidOperation",
828
811
  message: `The cart with ID '${cart.id}' does not have a shipping address set.`
829
812
  });
830
- const zones = storage.query(context.projectKey, "zone", {
813
+ const zoneIds = storage.query(context.projectKey, "zone", {
831
814
  where: [`locations(country="${cart.shippingAddress.country}"))`],
832
815
  limit: 100
833
- });
834
- const zoneIds = zones.results.map((zone) => zone.id);
816
+ }).results.map((zone) => zone.id);
835
817
  const shippingMethods = storage.query(context.projectKey, "shipping-method", {
836
818
  where: ["zoneRates(zone(id in (:zoneIds)))", `zoneRates(shippingRates(price(currencyCode="${cart.totalPrice.currencyCode}")))`],
837
819
  "var.zoneIds": zoneIds,
@@ -891,15 +873,14 @@ const createShippingInfoFromMethod = (context, storage, resource, method) => {
891
873
  centAmount: totalGross.centAmount - totalNet.centAmount
892
874
  }
893
875
  }];
894
- const totalTax = {
895
- ...shippingPrice,
896
- centAmount: taxPortions.reduce((acc, portion) => acc + portion.amount.centAmount, 0)
897
- };
898
876
  const taxedPrice = {
899
877
  totalNet,
900
878
  totalGross,
901
879
  taxPortions,
902
- totalTax
880
+ totalTax: {
881
+ ...shippingPrice,
882
+ centAmount: taxPortions.reduce((acc, portion) => acc + portion.amount.centAmount, 0)
883
+ }
903
884
  };
904
885
  return {
905
886
  shippingMethod: {
@@ -919,7 +900,7 @@ const createShippingInfoFromMethod = (context, storage, resource, method) => {
919
900
  //#endregion
920
901
  //#region src/repositories/cart/helpers.ts
921
902
  const selectPrice = ({ prices, currency, country }) => {
922
- if (!prices) return void 0;
903
+ if (!prices) return;
923
904
  return prices.find((price) => {
924
905
  const countryMatch = !price.country || price.country === country;
925
906
  const currencyMatch = price.value.currencyCode === currency;
@@ -928,17 +909,15 @@ const selectPrice = ({ prices, currency, country }) => {
928
909
  };
929
910
  const calculateLineItemTotalPrice = (lineItem) => lineItem.price?.value.centAmount * lineItem.quantity;
930
911
  const calculateCartTotalPrice = (cart) => {
931
- const lineItemsTotal = cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
932
- const customLineItemsTotal = cart.customLineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
933
- return lineItemsTotal + customLineItemsTotal;
912
+ return cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0) + cart.customLineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
934
913
  };
935
914
  const createCustomLineItemFromDraft = (projectKey, draft, storage, country) => {
936
915
  const quantity = draft.quantity ?? 1;
937
916
  const taxCategoryRef = draft.taxCategory ? getReferenceFromResourceIdentifier(draft.taxCategory, projectKey, storage) : void 0;
938
- let taxCategory = void 0;
917
+ let taxCategory;
939
918
  if (taxCategoryRef) try {
940
919
  taxCategory = storage.get(projectKey, "tax-category", taxCategoryRef.id, {}) || void 0;
941
- } catch (error) {}
920
+ } catch (_error) {}
942
921
  const totalPrice = createCentPrecisionMoney({
943
922
  ...draft.money,
944
923
  centAmount: (draft.money.centAmount ?? 0) * quantity
@@ -997,8 +976,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
997
976
  code: "General",
998
977
  message: sku ? `A variant with SKU '${sku}' for product '${product.id}' not found.` : `A variant with ID '${variantId}' for product '${product.id}' not found.`
999
978
  });
1000
- const alreadyAdded = resource.lineItems.some((x) => x.productId === product?.id && x.variant.id === variant?.id);
1001
- if (alreadyAdded) resource.lineItems.forEach((x) => {
979
+ if (resource.lineItems.some((x) => x.productId === product?.id && x.variant.id === variant?.id)) resource.lineItems.forEach((x) => {
1002
980
  if (x.productId === product?.id && x.variant.id === variant?.id) {
1003
981
  x.quantity += quantity;
1004
982
  x.totalPrice.centAmount = calculateLineItemTotalPrice(x);
@@ -1019,7 +997,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
1019
997
  resource.lineItems.push({
1020
998
  id: v4(),
1021
999
  key,
1022
- addedAt: addedAt ? addedAt : new Date().toISOString(),
1000
+ addedAt: addedAt ? addedAt : (/* @__PURE__ */ new Date()).toISOString(),
1023
1001
  productId: product.id,
1024
1002
  productKey: product.key,
1025
1003
  productSlug: product.masterData.current.slug,
@@ -1084,8 +1062,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
1084
1062
  code: "General",
1085
1063
  message: `A line item with ID '${lineItemId}' not found.`
1086
1064
  });
1087
- const shouldDelete = !quantity || quantity >= lineItem.quantity;
1088
- if (shouldDelete) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
1065
+ if (!quantity || quantity >= lineItem.quantity) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
1089
1066
  else resource.lineItems.forEach((x) => {
1090
1067
  if (x.id === lineItemId && quantity) {
1091
1068
  x.quantity -= quantity;
@@ -1336,7 +1313,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
1336
1313
  resource.shippingAddress = void 0;
1337
1314
  return;
1338
1315
  }
1339
- let custom = void 0;
1316
+ let custom;
1340
1317
  if (address.custom) custom = createCustomFields(address.custom, context.projectKey, this._storage);
1341
1318
  resource.shippingAddress = {
1342
1319
  ...address,
@@ -1395,7 +1372,7 @@ var CartRepository = class extends AbstractResourceRepository {
1395
1372
  typeId: "customer",
1396
1373
  id: draft.customerId
1397
1374
  });
1398
- let storedBusinessUnit = void 0;
1375
+ let storedBusinessUnit;
1399
1376
  if (draft.businessUnit?.id || draft.businessUnit?.key) storedBusinessUnit = this._storage.getByResourceIdentifier(context.projectKey, {
1400
1377
  typeId: "business-unit",
1401
1378
  id: draft.businessUnit.id,
@@ -1457,7 +1434,6 @@ var CartRepository = class extends AbstractResourceRepository {
1457
1434
  getActiveCart(projectKey) {
1458
1435
  const results = this._storage.query(projectKey, this.getTypeId(), { where: [`cartState="Active"`] });
1459
1436
  if (results.count > 0) return results.results[0];
1460
- return;
1461
1437
  }
1462
1438
  draftLineItemtoLineItem = (projectKey, draftLineItem, currency, country) => {
1463
1439
  const { productId, quantity, variantId, sku } = draftLineItem;
@@ -1512,8 +1488,7 @@ var CartRepository = class extends AbstractResourceRepository {
1512
1488
  createShippingInfo(context, resource, shippingMethodRef) {
1513
1489
  if (resource.taxMode === "External") throw new Error("External tax rate is not supported");
1514
1490
  this._storage.getByResourceIdentifier(context.projectKey, shippingMethodRef);
1515
- const shippingMethods = getShippingMethodsMatchingCart(context, this._storage, resource, { expand: ["zoneRates[*].zone"] });
1516
- const method = shippingMethods.results.find((candidate) => shippingMethodRef.id ? candidate.id === shippingMethodRef.id : candidate.key === shippingMethodRef.key);
1491
+ const method = getShippingMethodsMatchingCart(context, this._storage, resource, { expand: ["zoneRates[*].zone"] }).results.find((candidate) => shippingMethodRef.id ? candidate.id === shippingMethodRef.id : candidate.key === shippingMethodRef.key);
1517
1492
  if (!method) throw new CommercetoolsError({
1518
1493
  code: "ShippingMethodDoesNotMatchCart",
1519
1494
  message: `The shipping method with ${shippingMethodRef.id ? `ID '${shippingMethodRef.id}'` : `key '${shippingMethodRef.key}'`} is not allowed for the cart with ID '${resource.id}'.`
@@ -1526,8 +1501,7 @@ var CartRepository = class extends AbstractResourceRepository {
1526
1501
  //#region src/repositories/order/actions.ts
1527
1502
  var OrderUpdateHandler = class extends AbstractUpdateHandler {
1528
1503
  addPayment(context, resource, { payment }) {
1529
- const resolvedPayment = this._storage.getByResourceIdentifier(context.projectKey, payment);
1530
- if (!resolvedPayment) throw new Error(`Payment ${payment.id} not found`);
1504
+ if (!this._storage.getByResourceIdentifier(context.projectKey, payment)) throw new Error(`Payment ${payment.id} not found`);
1531
1505
  if (!resource.paymentInfo) resource.paymentInfo = { payments: [] };
1532
1506
  resource.paymentInfo.payments.push({
1533
1507
  typeId: "payment",
@@ -1649,10 +1623,9 @@ var OrderUpdateHandler = class extends AbstractUpdateHandler {
1649
1623
  if (!store) return;
1650
1624
  const resolvedType = this._storage.getByResourceIdentifier(context.projectKey, store);
1651
1625
  if (!resolvedType) throw new Error(`No store found with key=${store.key}`);
1652
- const storeReference = resolvedType;
1653
1626
  resource.store = {
1654
1627
  typeId: "store",
1655
- key: storeReference.key
1628
+ key: resolvedType.key
1656
1629
  };
1657
1630
  }
1658
1631
  transitionState(context, resource, { state }) {
@@ -1677,7 +1650,7 @@ var OrderUpdateHandler = class extends AbstractUpdateHandler {
1677
1650
  id: resolvedType.id
1678
1651
  },
1679
1652
  externalId,
1680
- syncedAt: syncedAt ?? new Date().toISOString()
1653
+ syncedAt: syncedAt ?? (/* @__PURE__ */ new Date()).toISOString()
1681
1654
  };
1682
1655
  if (!resource.syncInfo?.length) resource.syncInfo = [syncData];
1683
1656
  else {
@@ -1825,7 +1798,7 @@ var OrderRepository = class extends AbstractResourceRepository {
1825
1798
  ...draft.price.value,
1826
1799
  centAmount: (draft.price.value.centAmount ?? 0) * quantity
1827
1800
  });
1828
- const lineItem = {
1801
+ return {
1829
1802
  ...getBaseResourceProperties(),
1830
1803
  custom: createCustomFields(draft.custom, context.projectKey, this._storage),
1831
1804
  discountedPricePerQuantity: [],
@@ -1849,7 +1822,6 @@ var OrderRepository = class extends AbstractResourceRepository {
1849
1822
  attributes: variant.attributes
1850
1823
  }
1851
1824
  };
1852
- return lineItem;
1853
1825
  }
1854
1826
  customLineItemFromImportDraft(context, draft) {
1855
1827
  const quantity = draft.quantity ?? 1;
@@ -1857,7 +1829,7 @@ var OrderRepository = class extends AbstractResourceRepository {
1857
1829
  ...draft.money,
1858
1830
  centAmount: (draft.money.centAmount ?? 0) * quantity
1859
1831
  });
1860
- const lineItem = {
1832
+ return {
1861
1833
  ...getBaseResourceProperties(),
1862
1834
  custom: createCustomFields(draft.custom, context.projectKey, this._storage),
1863
1835
  discountedPricePerQuantity: [],
@@ -1872,7 +1844,6 @@ var OrderRepository = class extends AbstractResourceRepository {
1872
1844
  taxedPrice: calculateTaxedPriceFromRate(totalPrice.centAmount, totalPrice.currencyCode, draft.taxRate),
1873
1845
  taxedPricePortions: []
1874
1846
  };
1875
- return lineItem;
1876
1847
  }
1877
1848
  getWithOrderNumber(context, orderNumber, params = {}) {
1878
1849
  const result = this._storage.query(context.projectKey, this.getTypeId(), {
@@ -1881,7 +1852,6 @@ var OrderRepository = class extends AbstractResourceRepository {
1881
1852
  });
1882
1853
  if (result.count === 1) return result.results[0];
1883
1854
  if (result.count > 1) throw new Error("Duplicate order numbers");
1884
- return;
1885
1855
  }
1886
1856
  createShippingInfo(context, resource, shippingMethodRef) {
1887
1857
  const cartLikeForMatching = {
@@ -1897,15 +1867,13 @@ var OrderRepository = class extends AbstractResourceRepository {
1897
1867
  directDiscounts: resource.directDiscounts || [],
1898
1868
  shippingInfo: void 0
1899
1869
  };
1900
- const shippingMethods = getShippingMethodsMatchingCart(context, this._storage, cartLikeForMatching, { expand: ["zoneRates[*].zone"] });
1901
- const method = shippingMethods.results.find((candidate) => candidate.id === shippingMethodRef.id);
1870
+ const method = getShippingMethodsMatchingCart(context, this._storage, cartLikeForMatching, { expand: ["zoneRates[*].zone"] }).results.find((candidate) => candidate.id === shippingMethodRef.id);
1902
1871
  if (!method) throw new CommercetoolsError({
1903
1872
  code: "ShippingMethodDoesNotMatchCart",
1904
1873
  message: `The shipping method with ID '${shippingMethodRef.id}' is not allowed for the order with ID '${resource.id}'.`
1905
1874
  });
1906
- const baseShippingInfo = createShippingInfoFromMethod(context, this._storage, resource, method);
1907
1875
  return {
1908
- ...baseShippingInfo,
1876
+ ...createShippingInfoFromMethod(context, this._storage, resource, method),
1909
1877
  deliveries: []
1910
1878
  };
1911
1879
  }
@@ -1933,7 +1901,7 @@ var QuoteRequestUpdateHandler = class extends AbstractUpdateHandler {
1933
1901
  }
1934
1902
  }
1935
1903
  transitionState(context, resource, { state, force }) {
1936
- let stateReference = void 0;
1904
+ let stateReference;
1937
1905
  if (state) {
1938
1906
  stateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
1939
1907
  resource.state = stateReference;
@@ -2032,7 +2000,7 @@ var AssociateRoleUpdateHandler = class extends AbstractUpdateHandler {
2032
2000
  }
2033
2001
  removePermission(context, resource, { permission }) {
2034
2002
  if (!resource.permissions) return;
2035
- resource.permissions = resource.permissions.filter((p) => {});
2003
+ resource.permissions = resource.permissions.filter((p) => p !== permission);
2036
2004
  }
2037
2005
  setBuyerAssignable(context, resource, { buyerAssignable }) {
2038
2006
  resource.buyerAssignable = buyerAssignable;
@@ -2191,8 +2159,7 @@ var BusinessUnitUpdateHandler = class extends AbstractUpdateHandler {
2191
2159
  resource.status = status;
2192
2160
  }
2193
2161
  setAssociates(context, resource, { associates }) {
2194
- const newAssociates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0);
2195
- resource.associates = newAssociates || void 0;
2162
+ resource.associates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0) || void 0;
2196
2163
  }
2197
2164
  removeAssociate(context, resource, { customer }) {
2198
2165
  resource.associates = resource.associates.filter((associate) => associate.customer.id !== customer.id);
@@ -2510,8 +2477,7 @@ var CategoryRepository = class extends AbstractResourceRepository {
2510
2477
  postProcessResource(context, resource, params) {
2511
2478
  let node = resource;
2512
2479
  const ancestors = [];
2513
- const expandClauses = params?.expand?.map(parseExpandClause) ?? [];
2514
- const addExpand = expandClauses?.find((c) => c.element === "ancestors" && c.index === "*");
2480
+ const addExpand = (params?.expand?.map(parseExpandClause) ?? [])?.find((c) => c.element === "ancestors" && c.index === "*");
2515
2481
  while (node.parent) {
2516
2482
  node = this._storage.getByResourceIdentifier(context.projectKey, node.parent);
2517
2483
  ancestors.push({
@@ -2600,9 +2566,8 @@ var CustomObjectRepository = class extends AbstractResourceRepository {
2600
2566
  code: "InvalidOperation",
2601
2567
  message: "version on create must be 0"
2602
2568
  }, 400);
2603
- const baseProperties = getBaseResourceProperties();
2604
2569
  const resource = {
2605
- ...baseProperties,
2570
+ ...getBaseResourceProperties(),
2606
2571
  container: draft.container,
2607
2572
  key: draft.key,
2608
2573
  value: draft.value
@@ -2611,8 +2576,7 @@ var CustomObjectRepository = class extends AbstractResourceRepository {
2611
2576
  return resource;
2612
2577
  }
2613
2578
  getWithContainerAndKey(context, container, key) {
2614
- const items = this._storage.all(context.projectKey, this.getTypeId());
2615
- return items.find((item) => item.container === container && item.key === key);
2579
+ return this._storage.all(context.projectKey, this.getTypeId()).find((item) => item.container === container && item.key === key);
2616
2580
  }
2617
2581
  queryWithContainer(context, container, params = {}) {
2618
2582
  const whereClause = params.where || [];
@@ -2718,10 +2682,9 @@ var CustomerUpdateHandler = class extends AbstractUpdateHandler {
2718
2682
  code: "InvalidOperation",
2719
2683
  message: "CustomerGroup is required."
2720
2684
  }, 400);
2721
- const group = this._storage.getByResourceIdentifier(context.projectKey, action.customerGroup);
2722
2685
  resource.customerGroup = {
2723
2686
  typeId: "customer-group",
2724
- id: group.id
2687
+ id: this._storage.getByResourceIdentifier(context.projectKey, action.customerGroup).id
2725
2688
  };
2726
2689
  }
2727
2690
  setCustomerNumber(_context, resource, { customerNumber }) {
@@ -2818,8 +2781,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2818
2781
  this.actions = new CustomerUpdateHandler(config.storage);
2819
2782
  }
2820
2783
  create(context, draft) {
2821
- const results = this._storage.query(context.projectKey, this.getTypeId(), { where: [`lowercaseEmail="${draft.email.toLowerCase()}"`] });
2822
- if (results.count > 0) throw new CommercetoolsError({
2784
+ if (this._storage.query(context.projectKey, this.getTypeId(), { where: [`lowercaseEmail="${draft.email.toLowerCase()}"`] }).count > 0) throw new CommercetoolsError({
2823
2785
  code: "CustomerAlreadyExists",
2824
2786
  statusCode: 400,
2825
2787
  message: "There is already an existing customer with the provided email.",
@@ -2896,7 +2858,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2896
2858
  message: `The Customer with ID '${request.email}' was not found.`
2897
2859
  });
2898
2860
  const ttlMinutes = request.ttlMinutes ?? 34560;
2899
- const expiresAt = new Date(new Date().getTime() + ttlMinutes * 60 * 1e3);
2861
+ const expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1e3);
2900
2862
  const customer = results.results[0];
2901
2863
  const rest = getBaseResourceProperties();
2902
2864
  const token = createPasswordResetToken(customer, expiresAt);
@@ -2933,7 +2895,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2933
2895
  code: "ResourceNotFound",
2934
2896
  message: `The Customer with ID '${id}' was not found.`
2935
2897
  });
2936
- const expiresAt = new Date(Date.now() + 30 * 60);
2898
+ const expiresAt = new Date(Date.now() + 1800);
2937
2899
  const customer = results.results[0];
2938
2900
  const rest = getBaseResourceProperties();
2939
2901
  const token = createEmailVerifyToken(customer);
@@ -3186,6 +3148,11 @@ var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
3186
3148
  resource.quantityOnStock = quantity;
3187
3149
  resource.availableQuantity = quantity;
3188
3150
  }
3151
+ removeQuantity(context, resource, { quantity }) {
3152
+ const newQuantity = Math.max(0, resource.quantityOnStock - quantity);
3153
+ resource.quantityOnStock = newQuantity;
3154
+ resource.availableQuantity = newQuantity;
3155
+ }
3189
3156
  setCustomField(context, resource, { name, value }) {
3190
3157
  if (!resource.custom) throw new Error("Resource has no custom field");
3191
3158
  resource.custom.fields[name] = value;
@@ -3279,12 +3246,10 @@ var MyCustomerRepository = class extends CustomerRepository {
3279
3246
  deleteMe(context) {
3280
3247
  const results = this._storage.query(context.projectKey, this.getTypeId(), {});
3281
3248
  if (results.count > 0) return this.delete(context, results.results[0].id);
3282
- return;
3283
3249
  }
3284
3250
  getMe(context) {
3285
3251
  const results = this._storage.query(context.projectKey, this.getTypeId(), {});
3286
3252
  if (results.count > 0) return results.results[0];
3287
- return;
3288
3253
  }
3289
3254
  };
3290
3255
 
@@ -3365,8 +3330,7 @@ var PaymentUpdateHandler = class extends AbstractUpdateHandler {
3365
3330
  }
3366
3331
  setCustomer(_context, resource, { customer }) {
3367
3332
  if (customer) {
3368
- const c = getReferenceFromResourceIdentifier(customer, _context.projectKey, this._storage);
3369
- resource.customer = c;
3333
+ resource.customer = getReferenceFromResourceIdentifier(customer, _context.projectKey, this._storage);
3370
3334
  resource.anonymousId = void 0;
3371
3335
  }
3372
3336
  }
@@ -3508,11 +3472,10 @@ var ReviewStatisticsService = class {
3508
3472
  this._storage = _storage;
3509
3473
  }
3510
3474
  calculateProductReviewStatistics(projectKey, productId) {
3511
- const allReviews = this._storage.all(projectKey, "review");
3512
- const productReviews = allReviews.filter((review) => review.target?.typeId === "product" && review.target?.id === productId && review.includedInStatistics && review.rating !== void 0);
3513
- if (productReviews.length === 0) return void 0;
3475
+ const productReviews = this._storage.all(projectKey, "review").filter((review) => review.target?.typeId === "product" && review.target?.id === productId && review.includedInStatistics && review.rating !== void 0);
3476
+ if (productReviews.length === 0) return;
3514
3477
  const ratings = productReviews.map((review) => review.rating).filter((rating) => rating !== void 0);
3515
- if (ratings.length === 0) return void 0;
3478
+ if (ratings.length === 0) return;
3516
3479
  const count = ratings.length;
3517
3480
  const sum = ratings.reduce((acc, rating) => acc + rating, 0);
3518
3481
  const averageRating = Math.round(sum / count * 1e5) / 1e5;
@@ -3615,11 +3578,9 @@ var Token = class {
3615
3578
  * @return {TokenPosition}
3616
3579
  */
3617
3580
  strpos() {
3618
- const start = this.lexer.strpos(this.start);
3619
- const end = this.lexer.strpos(this.end);
3620
3581
  return {
3621
- start,
3622
- end
3582
+ start: this.lexer.strpos(this.start),
3583
+ end: this.lexer.strpos(this.end)
3623
3584
  };
3624
3585
  }
3625
3586
  isEof() {
@@ -3850,7 +3811,7 @@ var Lexer = class {
3850
3811
  unexpected += e$1.unexpected;
3851
3812
  }
3852
3813
  const { line, column } = this.strpos(position);
3853
- const e = new Error(`Unexpected input: ${unexpected} at (${line}:${column})`);
3814
+ const e = /* @__PURE__ */ new Error(`Unexpected input: ${unexpected} at (${line}:${column})`);
3854
3815
  e.unexpected = unexpected;
3855
3816
  e.end = position + unexpected.length;
3856
3817
  throw e;
@@ -3863,11 +3824,9 @@ var Lexer = class {
3863
3824
  strpos(i) {
3864
3825
  let lines = this._state.source.substring(0, i).split(/\r?\n/);
3865
3826
  if (!Array.isArray(lines)) lines = [lines];
3866
- const line = lines.length;
3867
- const column = lines[lines.length - 1].length + 1;
3868
3827
  return {
3869
- line,
3870
- column
3828
+ line: lines.length,
3829
+ column: lines[lines.length - 1].length + 1
3871
3830
  };
3872
3831
  }
3873
3832
  /**
@@ -3905,7 +3864,7 @@ var Lexer = class {
3905
3864
  * @param kwd The keyword to add as a token
3906
3865
  */
3907
3866
  keyword(kwd) {
3908
- return this.token(kwd, new RegExp(`${kwd}(?=\\W|$)`));
3867
+ return this.token(kwd, /* @__PURE__ */ new RegExp(`${kwd}(?=\\W|$)`));
3909
3868
  }
3910
3869
  /**
3911
3870
  * Creates an operator
@@ -3977,9 +3936,9 @@ var Parser = class {
3977
3936
  * @type {ILexer<T>}
3978
3937
  */
3979
3938
  this.lexer = lexer;
3980
- this._nuds = new Map();
3981
- this._leds = new Map();
3982
- this._bps = new Map();
3939
+ this._nuds = /* @__PURE__ */ new Map();
3940
+ this._leds = /* @__PURE__ */ new Map();
3941
+ this._bps = /* @__PURE__ */ new Map();
3983
3942
  }
3984
3943
  _type(tokenOrType) {
3985
3944
  return tokenOrType && typeof tokenOrType.isEof == "function" ? tokenOrType.type : tokenOrType;
@@ -4047,10 +4006,9 @@ var Parser = class {
4047
4006
  }, true);
4048
4007
  };
4049
4008
  const mkinfo = (token) => {
4050
- const bp = this.bp(token);
4051
4009
  return {
4052
4010
  token,
4053
- bp,
4011
+ bp: this.bp(token),
4054
4012
  stop,
4055
4013
  ctx: opts.ctx,
4056
4014
  options: opts
@@ -4152,8 +4110,7 @@ const parseFilter = (filter) => {
4152
4110
  const parser = new Parser(lexer).builder().nud("IDENTIFIER", 100, (t) => t.token.match).led(":", 100, ({ left, bp }) => {
4153
4111
  const parsed = parser.parse({ terminals: [bp - 1] });
4154
4112
  const expressions = !Array.isArray(parsed) ? [parsed] : parsed;
4155
- const unique = new Set(expressions.map((expr) => expr.type));
4156
- if (unique.size > 1) throw new Error("Invalid expression");
4113
+ if (new Set(expressions.map((expr) => expr.type)).size > 1) throw new Error("Invalid expression");
4157
4114
  if (expressions.some((expr) => expr.type === "Symbol")) return {
4158
4115
  source: left,
4159
4116
  type: "FilterExpression",
@@ -4238,22 +4195,18 @@ const generateFacetFunc = (filter) => {
4238
4195
  return parseFilter(filter);
4239
4196
  };
4240
4197
  const filterProduct = (source, exprFunc) => (p, markMatchingVariants) => {
4241
- const value = nestedLookup(p, source);
4242
- return exprFunc(value);
4198
+ return exprFunc(nestedLookup(p, source));
4243
4199
  };
4244
4200
  const filterVariants = (source, exprFunc) => (p, markMatchingVariants) => {
4245
4201
  const [, ...paths] = source.split(".");
4246
4202
  const path = paths.join(".");
4247
4203
  const variants = getVariants(p);
4248
- for (const variant of variants) {
4249
- const value = resolveVariantValue(variant, path);
4250
- if (exprFunc(value)) {
4251
- if (markMatchingVariants) {
4252
- for (const v of variants) v.isMatchingVariant = false;
4253
- variant.isMatchingVariant = true;
4254
- }
4255
- return true;
4204
+ for (const variant of variants) if (exprFunc(resolveVariantValue(variant, path))) {
4205
+ if (markMatchingVariants) {
4206
+ for (const v of variants) v.isMatchingVariant = false;
4207
+ variant.isMatchingVariant = true;
4256
4208
  }
4209
+ return true;
4257
4210
  }
4258
4211
  return false;
4259
4212
  };
@@ -4262,7 +4215,7 @@ const resolveVariantValue = (obj, path) => {
4262
4215
  if (path.startsWith("variants.")) path = path.substring(path.indexOf(".") + 1);
4263
4216
  if (path.startsWith("attributes.")) {
4264
4217
  const [, attrName, ...rest] = path.split(".");
4265
- if (!obj.attributes) return void 0;
4218
+ if (!obj.attributes) return;
4266
4219
  for (const attr of obj.attributes) if (attr.name === attrName) return nestedLookup(attr.value, rest.join("."));
4267
4220
  }
4268
4221
  if (path === "price.centAmount") return obj.prices && obj.prices.length > 0 ? obj.prices[0].value.centAmount : void 0;
@@ -4274,17 +4227,14 @@ const getVariants = (p) => [p.masterVariant, ...p.variants ?? []];
4274
4227
  //#region src/lib/productSearchFilter.ts
4275
4228
  const parseSearchQuery = (searchQuery) => {
4276
4229
  if (isSearchAndExpression$1(searchQuery)) return (obj, markMatchingVariant) => searchQuery.and.every((expr) => {
4277
- const filterFunc = parseSearchQuery(expr);
4278
- return filterFunc(obj, markMatchingVariant);
4230
+ return parseSearchQuery(expr)(obj, markMatchingVariant);
4279
4231
  });
4280
4232
  if (isSearchOrExpression$1(searchQuery)) return (obj, markMatchingVariant) => searchQuery.or.some((expr) => {
4281
- const filterFunc = parseSearchQuery(expr);
4282
- return filterFunc(obj, markMatchingVariant);
4233
+ return parseSearchQuery(expr)(obj, markMatchingVariant);
4283
4234
  });
4284
4235
  if (isSearchNotExpression$1(searchQuery)) return (obj, markMatchingVariant) => !parseSearchQuery(searchQuery.not)(obj, markMatchingVariant);
4285
4236
  if (isSearchFilterExpression$1(searchQuery)) return (obj, markMatchingVariant) => searchQuery.filter.every((expr) => {
4286
- const filterFunc = parseSearchQuery(expr);
4287
- return filterFunc(obj, markMatchingVariant);
4237
+ return parseSearchQuery(expr)(obj, markMatchingVariant);
4288
4238
  });
4289
4239
  if (isSearchRangeExpression$1(searchQuery)) {
4290
4240
  const generateRangeMatchFunc = (value) => {
@@ -4320,18 +4270,15 @@ const generateFieldMatchFunc = (matchFunc, searchQuery) => {
4320
4270
  if (searchQuery.field.startsWith("variants.")) {
4321
4271
  const variantField = searchQuery.field.substring(searchQuery.field.indexOf(".") + 1);
4322
4272
  const variants = getVariants(obj);
4323
- for (const variant of variants) {
4324
- const value = resolveFieldValue(variant, {
4325
- ...searchQuery,
4326
- field: variantField
4327
- });
4328
- if (matchFunc(value)) {
4329
- if (markMatchingVariants) {
4330
- for (const v of variants) v.isMatchingVariant = false;
4331
- variant.isMatchingVariant = true;
4332
- }
4333
- return true;
4273
+ for (const variant of variants) if (matchFunc(resolveFieldValue(variant, {
4274
+ ...searchQuery,
4275
+ field: variantField
4276
+ }))) {
4277
+ if (markMatchingVariants) {
4278
+ for (const v of variants) v.isMatchingVariant = false;
4279
+ variant.isMatchingVariant = true;
4334
4280
  }
4281
+ return true;
4335
4282
  }
4336
4283
  return false;
4337
4284
  }
@@ -4346,7 +4293,7 @@ const resolveFieldValue = (obj, searchQuery) => {
4346
4293
  if (fieldPath.startsWith("variants.")) fieldPath = fieldPath.substring(fieldPath.indexOf(".") + 1);
4347
4294
  if (fieldPath.startsWith("attributes.")) {
4348
4295
  const [, attrName, ...rest] = fieldPath.split(".");
4349
- if (!obj.attributes) return void 0;
4296
+ if (!obj.attributes) return;
4350
4297
  for (const attr of obj.attributes) if (attr.name === attrName) return nestedLookupByLanguage(attr.value, rest.join("."), language);
4351
4298
  }
4352
4299
  if (fieldPath === "prices.currentCentAmount") return obj.prices && obj.prices.length > 0 ? obj.prices[0].value.centAmount : void 0;
@@ -4375,8 +4322,8 @@ const isSearchWildCardExpression$1 = (expr) => expr.wildcard !== void 0;
4375
4322
  //#endregion
4376
4323
  //#region src/lib/searchQueryTypeChecker.ts
4377
4324
  const validateSearchQuery = (query) => {
4378
- if (isSearchAndExpression(query)) query.and.forEach((expr) => validateSearchQuery(expr));
4379
- else if (isSearchOrExpression(query)) query.or.forEach((expr) => validateSearchQuery(expr));
4325
+ if (isSearchAndExpression(query)) for (const expr of query.and) validateSearchQuery(expr);
4326
+ else if (isSearchOrExpression(query)) for (const expr of query.or) validateSearchQuery(expr);
4380
4327
  else if (isSearchNotExpression(query)) validateSearchQuery(query.not);
4381
4328
  else if (isSearchFilterExpression(query) || isSearchRangeExpression(query) || isSearchExactExpression(query) || isSearchExistsExpression(query) || isSearchFullTextExpression(query) || isSearchFullTextPrefixExpression(query) || isSearchPrefixExpression(query) || isSearchWildCardExpression(query) || isSearchAnyValue(query)) return;
4382
4329
  else throw new Error("Unsupported search query expression");
@@ -4456,7 +4403,7 @@ var ProductSearch = class {
4456
4403
  isOnStockForChannel: existingEntry?.isOnStockForChannel ?? entry.supplyChannel?.id
4457
4404
  });
4458
4405
  return acc;
4459
- }, new Map());
4406
+ }, /* @__PURE__ */ new Map());
4460
4407
  let productResources = this._storage.all(projectKey, "product").map((r) => this.transformProduct(r, params.productProjectionParameters?.staged ?? false, availabilityBySku)).filter((p) => {
4461
4408
  if (!(params.productProjectionParameters?.staged ?? false)) return p.published;
4462
4409
  return true;
@@ -4467,7 +4414,6 @@ var ProductSearch = class {
4467
4414
  const matchFunc = parseSearchQuery(params.query);
4468
4415
  productResources = productResources.filter((resource) => matchFunc(resource, markMatchingVariant));
4469
4416
  } catch (err) {
4470
- console.error(err);
4471
4417
  throw new CommercetoolsError({
4472
4418
  code: "InvalidInput",
4473
4419
  message: err.message
@@ -4543,8 +4489,7 @@ var ProductSearch = class {
4543
4489
  //#endregion
4544
4490
  //#region src/repositories/product/helpers.ts
4545
4491
  const getVariant = (productData, variantId, sku) => {
4546
- const variants = [productData.masterVariant, ...productData.variants];
4547
- const foundVariant = variants.find((variant) => {
4492
+ const foundVariant = [productData.masterVariant, ...productData.variants].find((variant) => {
4548
4493
  if (variantId) return variant.id === variantId;
4549
4494
  if (sku) return variant.sku === sku;
4550
4495
  return false;
@@ -4571,12 +4516,11 @@ const variantFromDraft = (context, storage, variantId, variant) => ({
4571
4516
  images: variant.images ?? []
4572
4517
  });
4573
4518
  const assetFromDraft = (context, storage, draft) => {
4574
- const asset = {
4519
+ return {
4575
4520
  ...draft,
4576
4521
  id: v4(),
4577
4522
  custom: createCustomFields(draft.custom, context.projectKey, storage)
4578
4523
  };
4579
- return asset;
4580
4524
  };
4581
4525
  const priceFromDraft = (context, storage, draft) => ({
4582
4526
  id: v4(),
@@ -4594,10 +4538,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4594
4538
  const { variant, isMasterVariant, variantIndex } = getVariant(data, variantId, sku);
4595
4539
  if (!variant) throw new Error(`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`);
4596
4540
  if (!variant.images) variant.images = [];
4597
- else {
4598
- const existingImage = variant.images.find((x) => x.url === image.url);
4599
- if (existingImage) throw new Error(`Cannot add image '${image.url}' because product '${resource.id}' already has that image.`);
4600
- }
4541
+ else if (variant.images.find((x) => x.url === image.url)) throw new Error(`Cannot add image '${image.url}' because product '${resource.id}' already has that image.`);
4601
4542
  variant.images.push(image);
4602
4543
  if (isMasterVariant) data.masterVariant = variant;
4603
4544
  else data.variants[variantIndex] = variant;
@@ -4649,12 +4590,10 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4649
4590
  assets
4650
4591
  };
4651
4592
  const dataStaged = resource.masterData.staged;
4652
- const allVariants = [dataStaged.masterVariant, ...dataStaged.variants ?? []];
4653
- const maxId = allVariants.reduce((max, element) => element.id > max ? element.id : max, 0);
4593
+ const maxId = [dataStaged.masterVariant, ...dataStaged.variants ?? []].reduce((max, element) => element.id > max ? element.id : max, 0);
4654
4594
  const variant = variantFromDraft(context, this._storage, maxId + 1, variantDraft);
4655
4595
  dataStaged.variants.push(variant);
4656
- const onlyStaged = staged !== void 0 ? staged : true;
4657
- if (!onlyStaged) resource.masterData.current.variants.push(variant);
4596
+ if (!(staged !== void 0 ? staged : true)) resource.masterData.current.variants.push(variant);
4658
4597
  checkForStagedChanges(resource);
4659
4598
  return resource;
4660
4599
  }
@@ -4684,8 +4623,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4684
4623
  }
4685
4624
  changePrice(context, resource, { priceId, price, staged }) {
4686
4625
  const changeVariantPrice = (data) => {
4687
- const allVariants = [data.masterVariant, ...data.variants ?? []];
4688
- const priceVariant = allVariants.find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4626
+ const priceVariant = [data.masterVariant, ...data.variants ?? []].find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4689
4627
  if (!priceVariant) throw new Error(`Price with id ${priceId} not found on product ${resource.id}`);
4690
4628
  const { variant, isMasterVariant, variantIndex } = getVariant(data, priceVariant.id, priceVariant.sku);
4691
4629
  if (!variant) throw new Error(`Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`);
@@ -4740,11 +4678,10 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4740
4678
  const removeCategory = (data) => {
4741
4679
  if (category) {
4742
4680
  const resolvedCategory = getReferenceFromResourceIdentifier(category, context.projectKey, this._storage);
4743
- const foundCategory = data.categories.find((productCategory) => {
4681
+ if (!data.categories.find((productCategory) => {
4744
4682
  if (productCategory.id === resolvedCategory.id) return productCategory;
4745
4683
  return false;
4746
- });
4747
- if (!foundCategory) throw new CommercetoolsError({
4684
+ })) throw new CommercetoolsError({
4748
4685
  code: "InvalidOperation",
4749
4686
  message: `Cannot remove from category '${resolvedCategory.id}' because product '${resource.masterData.current.name}' is not in that category.`
4750
4687
  }, 400);
@@ -4769,8 +4706,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4769
4706
  const { variant, isMasterVariant, variantIndex } = getVariant(data, variantId, sku);
4770
4707
  if (!variant) throw new Error(`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`);
4771
4708
  const variantImages = variant.images ?? [];
4772
- const existingImage = variantImages.find((x) => x.url === imageUrl);
4773
- if (!existingImage) throw new Error(`Cannot remove image '${imageUrl}' because product '${resource.id}' does not have that image.`);
4709
+ if (!variantImages.find((x) => x.url === imageUrl)) throw new Error(`Cannot remove image '${imageUrl}' because product '${resource.id}' does not have that image.`);
4774
4710
  variant.images = variantImages.filter((image) => image.url !== imageUrl);
4775
4711
  if (isMasterVariant) data.masterVariant = variant;
4776
4712
  else data.variants[variantIndex] = variant;
@@ -4783,8 +4719,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4783
4719
  }
4784
4720
  removePrice(context, resource, { priceId, staged }) {
4785
4721
  const removeVariantPrice = (data) => {
4786
- const allVariants = [data.masterVariant, ...data.variants ?? []];
4787
- const priceVariant = allVariants.find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4722
+ const priceVariant = [data.masterVariant, ...data.variants ?? []].find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4788
4723
  if (!priceVariant) throw new Error(`Price with id ${priceId} not found on product ${resource.id}`);
4789
4724
  const { variant, isMasterVariant, variantIndex } = getVariant(data, priceVariant.id, priceVariant.sku);
4790
4725
  if (!variant) throw new Error(`Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`);
@@ -4897,8 +4832,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4897
4832
  return data;
4898
4833
  };
4899
4834
  resource.masterData.staged = updatePriceCustomFields(resource.masterData.staged);
4900
- const onlyStaged = staged !== void 0 ? staged : true;
4901
- if (!onlyStaged) resource.masterData.current = updatePriceCustomFields(resource.masterData.current);
4835
+ if (!(staged !== void 0 ? staged : true)) resource.masterData.current = updatePriceCustomFields(resource.masterData.current);
4902
4836
  checkForStagedChanges(resource);
4903
4837
  return resource;
4904
4838
  }
@@ -4914,13 +4848,12 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4914
4848
  return data;
4915
4849
  };
4916
4850
  resource.masterData.staged = updatePriceCustomType(resource.masterData.staged);
4917
- const onlyStaged = staged !== void 0 ? staged : true;
4918
- if (!onlyStaged) resource.masterData.current = updatePriceCustomType(resource.masterData.current);
4851
+ if (!(staged !== void 0 ? staged : true)) resource.masterData.current = updatePriceCustomType(resource.masterData.current);
4919
4852
  checkForStagedChanges(resource);
4920
4853
  return resource;
4921
4854
  }
4922
4855
  setTaxCategory(context, resource, { taxCategory }) {
4923
- let taxCategoryReference = void 0;
4856
+ let taxCategoryReference;
4924
4857
  if (taxCategory) taxCategoryReference = getReferenceFromResourceIdentifier(taxCategory, context.projectKey, this._storage);
4925
4858
  else throw new CommercetoolsError({
4926
4859
  code: "InvalidJsonInput",
@@ -4931,7 +4864,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4931
4864
  return resource;
4932
4865
  }
4933
4866
  transitionState(context, resource, { state, force }) {
4934
- let productStateReference = void 0;
4867
+ let productStateReference;
4935
4868
  if (state) {
4936
4869
  productStateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
4937
4870
  resource.state = productStateReference;
@@ -4961,7 +4894,7 @@ var ProductRepository = class extends AbstractResourceRepository {
4961
4894
  }
4962
4895
  create(context, draft) {
4963
4896
  if (!draft.masterVariant) throw new Error("Missing master variant");
4964
- let productType = void 0;
4897
+ let productType;
4965
4898
  try {
4966
4899
  productType = getReferenceFromResourceIdentifier(draft.productType, context.projectKey, this._storage);
4967
4900
  } catch (err) {
@@ -4981,9 +4914,9 @@ var ProductRepository = class extends AbstractResourceRepository {
4981
4914
  detailedErrorMessage: "categories: JSON object expected."
4982
4915
  }, 400);
4983
4916
  });
4984
- let taxCategoryReference = void 0;
4917
+ let taxCategoryReference;
4985
4918
  if (draft.taxCategory) taxCategoryReference = getReferenceFromResourceIdentifier(draft.taxCategory, context.projectKey, this._storage);
4986
- let productStateReference = void 0;
4919
+ let productStateReference;
4987
4920
  if (draft.state) productStateReference = getReferenceFromResourceIdentifier(draft.state, context.projectKey, this._storage);
4988
4921
  const productData = {
4989
4922
  name: draft.name,
@@ -5105,12 +5038,17 @@ const haversineDistance = (src, dst) => {
5105
5038
  const dLat = toRadian(dst.latitude - src.latitude);
5106
5039
  const dLon = toRadian(dst.longitude - src.longitude);
5107
5040
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRadian(src.latitude)) * Math.cos(toRadian(dst.latitude)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
5108
- const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
5109
- return RADIUS_OF_EARTH_IN_KM * c * 1e3;
5041
+ return RADIUS_OF_EARTH_IN_KM * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))) * 1e3;
5110
5042
  };
5111
5043
 
5112
5044
  //#endregion
5113
5045
  //#region src/lib/predicateParser.ts
5046
+ /**
5047
+ * This module implements the commercetools query predicate filter expression.
5048
+ * Support should be 100% complete.
5049
+ *
5050
+ * See https://docs.commercetools.com/api/predicates/query
5051
+ */
5114
5052
  var PredicateError = class {
5115
5053
  message;
5116
5054
  constructor(message) {
@@ -5145,7 +5083,7 @@ const resolveValue = (obj, val) => {
5145
5083
  if (val.value === "variants" && obj.masterVariant && obj.variants !== void 0) return [obj.masterVariant, ...obj.variants ?? []];
5146
5084
  if (!(val.value in obj)) {
5147
5085
  if (Array.isArray(obj)) return Object.values(obj).filter((v) => val.value in v).map((v) => v[val.value]);
5148
- return void 0;
5086
+ return;
5149
5087
  }
5150
5088
  return obj[val.value];
5151
5089
  };
@@ -5197,8 +5135,7 @@ const generateMatchFunc = (predicate) => {
5197
5135
  if (Array.isArray(expr)) return [left, ...expr];
5198
5136
  return [left, expr];
5199
5137
  }).nud("(", 100, (t) => {
5200
- const expr = parser.parse({ terminals: [")"] });
5201
- return expr;
5138
+ return parser.parse({ terminals: [")"] });
5202
5139
  }).led("(", 100, ({ left, bp }) => {
5203
5140
  const expr = parser.parse();
5204
5141
  lexer.expect(")");
@@ -5252,33 +5189,25 @@ const generateMatchFunc = (predicate) => {
5252
5189
  return (obj, vars) => resolveValue(obj, left) <= resolveSymbol(expr, vars);
5253
5190
  }).led("IS", 20, ({ left, bp }) => {
5254
5191
  let invert = false;
5255
- const next = lexer.peek();
5256
- if (next.type === "NOT") {
5192
+ if (lexer.peek().type === "NOT") {
5257
5193
  invert = true;
5258
5194
  lexer.next();
5259
5195
  }
5260
- const expr = parser.parse({ terminals: [bp - 1] });
5261
- switch (expr) {
5262
- case "empty": {
5196
+ switch (parser.parse({ terminals: [bp - 1] })) {
5197
+ case "empty":
5263
5198
  if (!invert) return (obj, vars) => {
5264
- const val = resolveValue(obj, left);
5265
- return val.length === 0;
5199
+ return resolveValue(obj, left).length === 0;
5266
5200
  };
5267
5201
  return (obj, vars) => {
5268
- const val = resolveValue(obj, left);
5269
- return val.length !== 0;
5202
+ return resolveValue(obj, left).length !== 0;
5270
5203
  };
5271
- }
5272
- case "defined": {
5204
+ case "defined":
5273
5205
  if (!invert) return (obj, vars) => {
5274
- const val = resolveValue(obj, left);
5275
- return val !== void 0;
5206
+ return resolveValue(obj, left) !== void 0;
5276
5207
  };
5277
5208
  return (obj, vars) => {
5278
- const val = resolveValue(obj, left);
5279
- return val === void 0;
5209
+ return resolveValue(obj, left) === void 0;
5280
5210
  };
5281
- }
5282
5211
  default: throw new Error("Unexpected");
5283
5212
  }
5284
5213
  }).led("IN", 20, ({ left, bp }) => {
@@ -5312,14 +5241,13 @@ const generateMatchFunc = (predicate) => {
5312
5241
  const value = resolveValue(obj, left);
5313
5242
  if (!value) return false;
5314
5243
  const maxDistance = resolveSymbol(expr[2], vars);
5315
- const distance = haversineDistance({
5244
+ return haversineDistance({
5316
5245
  longitude: value[0],
5317
5246
  latitude: value[1]
5318
5247
  }, {
5319
5248
  longitude: resolveSymbol(expr[0], vars),
5320
5249
  latitude: resolveSymbol(expr[1], vars)
5321
- });
5322
- return distance <= maxDistance;
5250
+ }) <= maxDistance;
5323
5251
  };
5324
5252
  }).led("CONTAINS", 20, ({ left, bp }) => {
5325
5253
  const keyword = lexer.next();
@@ -5367,7 +5295,6 @@ var ProductProjectionSearch = class {
5367
5295
  const filters = params.filter.map(parseFilterExpression);
5368
5296
  resources = resources.filter((resource) => filters.every((f) => f(resource, markMatchingVariant)));
5369
5297
  } catch (err) {
5370
- console.error(err);
5371
5298
  throw new CommercetoolsError({
5372
5299
  code: "InvalidInput",
5373
5300
  message: err.message
@@ -5423,7 +5350,7 @@ var ProductProjectionSearch = class {
5423
5350
  getFacets(params, products) {
5424
5351
  if (!params.facet) return {};
5425
5352
  const result = {};
5426
- const regexp = new RegExp(/ counting products$/);
5353
+ const regexp = /* @__PURE__ */ new RegExp(/ counting products$/);
5427
5354
  for (let facet of params.facet) {
5428
5355
  let countProducts = false;
5429
5356
  if (facet.endsWith(" counting products")) {
@@ -5489,36 +5416,34 @@ var ProductProjectionSearch = class {
5489
5416
  };
5490
5417
  }
5491
5418
  rangeFacet(source, ranges, products, countProducts) {
5492
- const counts = ranges?.map((range) => {
5493
- if (source.startsWith("variants.")) {
5494
- const values = [];
5495
- for (const p of products) for (const v of getVariants(p)) {
5496
- const val = resolveVariantValue(v, source);
5497
- if (val === void 0) continue;
5498
- if (range.match(val)) values.push(val);
5499
- }
5500
- const numValues = values.length;
5501
- return {
5502
- type: "double",
5503
- from: range.start || 0,
5504
- fromStr: range.start !== null ? Number(range.start).toFixed(1) : "",
5505
- to: range.stop || 0,
5506
- toStr: range.stop !== null ? Number(range.stop).toFixed(1) : "",
5507
- count: numValues,
5508
- total: values.reduce((a, b) => a + b, 0),
5509
- min: numValues > 0 ? Math.min(...values) : 0,
5510
- max: numValues > 0 ? Math.max(...values) : 0,
5511
- mean: numValues > 0 ? mean(values) : 0
5512
- };
5513
- }
5514
- throw new Error("not supported");
5515
- }) || [];
5516
- const data = {
5419
+ return {
5517
5420
  type: "range",
5518
5421
  dataType: "number",
5519
- ranges: counts
5422
+ ranges: ranges?.map((range) => {
5423
+ if (source.startsWith("variants.")) {
5424
+ const values = [];
5425
+ for (const p of products) for (const v of getVariants(p)) {
5426
+ const val = resolveVariantValue(v, source);
5427
+ if (val === void 0) continue;
5428
+ if (range.match(val)) values.push(val);
5429
+ }
5430
+ const numValues = values.length;
5431
+ return {
5432
+ type: "double",
5433
+ from: range.start || 0,
5434
+ fromStr: range.start !== null ? Number(range.start).toFixed(1) : "",
5435
+ to: range.stop || 0,
5436
+ toStr: range.stop !== null ? Number(range.stop).toFixed(1) : "",
5437
+ count: numValues,
5438
+ total: values.reduce((a, b) => a + b, 0),
5439
+ min: numValues > 0 ? Math.min(...values) : 0,
5440
+ max: numValues > 0 ? Math.max(...values) : 0,
5441
+ mean: numValues > 0 ? mean(values) : 0
5442
+ };
5443
+ }
5444
+ throw new Error("not supported");
5445
+ }) || []
5520
5446
  };
5521
- return data;
5522
5447
  }
5523
5448
  };
5524
5449
  const mean = (arr) => {
@@ -5749,12 +5674,12 @@ var ProjectUpdateHandler = class extends AbstractUpdateHandler {
5749
5674
  changeCustomerSearchStatus(context, resource, { status }) {
5750
5675
  if (!resource.searchIndexing?.customers) throw new Error("Invalid project state");
5751
5676
  resource.searchIndexing.customers.status = status;
5752
- resource.searchIndexing.customers.lastModifiedAt = new Date().toISOString();
5677
+ resource.searchIndexing.customers.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5753
5678
  }
5754
5679
  changeBusinessUnitSearchStatus(context, resource, { status }) {
5755
5680
  if (!resource.searchIndexing?.businessUnits) throw new Error("Invalid project state");
5756
5681
  resource.searchIndexing.businessUnits.status = status;
5757
- resource.searchIndexing.businessUnits.lastModifiedAt = new Date().toISOString();
5682
+ resource.searchIndexing.businessUnits.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5758
5683
  }
5759
5684
  changeLanguages(context, resource, { languages }) {
5760
5685
  resource.languages = languages;
@@ -5773,18 +5698,18 @@ var ProjectUpdateHandler = class extends AbstractUpdateHandler {
5773
5698
  changeOrderSearchStatus(context, resource, { status }) {
5774
5699
  if (!resource.searchIndexing?.orders) throw new Error("Invalid project state");
5775
5700
  resource.searchIndexing.orders.status = status;
5776
- resource.searchIndexing.orders.lastModifiedAt = new Date().toISOString();
5701
+ resource.searchIndexing.orders.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5777
5702
  }
5778
5703
  changeProductSearchIndexingEnabled(context, resource, { enabled, mode }) {
5779
5704
  if (mode === "ProductsSearch") {
5780
5705
  if (!resource.searchIndexing?.productsSearch) throw new Error("Invalid project state");
5781
5706
  resource.searchIndexing.productsSearch.status = enabled ? "Activated" : "Deactivated";
5782
- resource.searchIndexing.productsSearch.lastModifiedAt = new Date().toISOString();
5707
+ resource.searchIndexing.productsSearch.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5783
5708
  return;
5784
5709
  }
5785
5710
  if (!resource.searchIndexing?.products) throw new Error("Invalid project state");
5786
5711
  resource.searchIndexing.products.status = enabled ? "Activated" : "Deactivated";
5787
- resource.searchIndexing.products.lastModifiedAt = new Date().toISOString();
5712
+ resource.searchIndexing.products.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5788
5713
  }
5789
5714
  setExternalOAuth(context, resource, { externalOAuth }) {
5790
5715
  resource.externalOAuth = externalOAuth;
@@ -5823,7 +5748,7 @@ var QuoteUpdateHandler = class extends AbstractUpdateHandler {
5823
5748
  }
5824
5749
  }
5825
5750
  transitionState(context, resource, { state, force }) {
5826
- let stateReference = void 0;
5751
+ let stateReference;
5827
5752
  if (state) {
5828
5753
  stateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
5829
5754
  resource.state = stateReference;
@@ -5847,7 +5772,7 @@ var QuoteRepository = class extends AbstractResourceRepository {
5847
5772
  const staged = this._storage.getByResourceIdentifier(context.projectKey, draft.stagedQuote);
5848
5773
  const cart = this._storage.getByResourceIdentifier(context.projectKey, staged.quotationCart);
5849
5774
  if (!cart.customerId) throw new Error("Cart does not have a customer");
5850
- const resource = {
5775
+ return {
5851
5776
  ...getBaseResourceProperties(),
5852
5777
  quoteState: "Accepted",
5853
5778
  quoteRequest: staged.quoteRequest,
@@ -5870,7 +5795,6 @@ var QuoteRepository = class extends AbstractResourceRepository {
5870
5795
  billingAddress: cart.billingAddress,
5871
5796
  shippingAddress: cart.shippingAddress
5872
5797
  };
5873
- return resource;
5874
5798
  }
5875
5799
  };
5876
5800
 
@@ -5896,7 +5820,7 @@ var StagedQuoteUpdateHandler = class extends AbstractUpdateHandler {
5896
5820
  }
5897
5821
  }
5898
5822
  transitionState(context, resource, { state, force }) {
5899
- let stateReference = void 0;
5823
+ let stateReference;
5900
5824
  if (state) {
5901
5825
  stateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
5902
5826
  resource.state = stateReference;
@@ -5920,7 +5844,7 @@ var StagedQuoteRepository = class extends AbstractResourceRepository {
5920
5844
  const quoteRequest = this._storage.getByResourceIdentifier(context.projectKey, draft.quoteRequest);
5921
5845
  if (!quoteRequest.cart) throw new Error("Cannot find quote request");
5922
5846
  const cart = this._storage.getByResourceIdentifier(context.projectKey, quoteRequest.cart);
5923
- const resource = {
5847
+ return {
5924
5848
  ...getBaseResourceProperties(),
5925
5849
  stagedQuoteState: "InProgress",
5926
5850
  quoteRequest: {
@@ -5932,7 +5856,6 @@ var StagedQuoteRepository = class extends AbstractResourceRepository {
5932
5856
  id: cart.id
5933
5857
  }
5934
5858
  };
5935
- return resource;
5936
5859
  }
5937
5860
  };
5938
5861
 
@@ -6053,8 +5976,7 @@ var RecurringOrderRepository = class extends AbstractResourceRepository {
6053
5976
  }
6054
5977
  create(context, draft) {
6055
5978
  assert(draft.cart, "draft.cart is missing");
6056
- const orderRepo = new OrderRepository(this.config);
6057
- const initialOrder = orderRepo.createFromCart(context, {
5979
+ const initialOrder = new OrderRepository(this.config).createFromCart(context, {
6058
5980
  id: draft.cart.id,
6059
5981
  typeId: "cart"
6060
5982
  });
@@ -6259,7 +6181,7 @@ var ShippingMethodRepository = class extends AbstractResourceRepository {
6259
6181
  }
6260
6182
  matchingCart(context, cartId, params = {}) {
6261
6183
  const cart = this._storage.get(context.projectKey, "cart", cartId);
6262
- if (!cart) return void 0;
6184
+ if (!cart) return;
6263
6185
  return getShippingMethodsMatchingCart(context, this._storage, cart, params);
6264
6186
  }
6265
6187
  _transformZoneRateDraft(context, draft) {
@@ -6288,12 +6210,11 @@ var ShoppingListUpdateHandler = class extends AbstractUpdateHandler {
6288
6210
  let varId = variantId;
6289
6211
  if (sku) varId = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((x) => x.sku === sku)?.id;
6290
6212
  if (!varId) varId = product.masterData.current.masterVariant.id;
6291
- const alreadyAdded = resource.lineItems.some((x) => x.productId === product?.id && x.variantId === varId);
6292
- if (alreadyAdded) resource.lineItems.forEach((x) => {
6213
+ if (resource.lineItems.some((x) => x.productId === product?.id && x.variantId === varId)) resource.lineItems.forEach((x) => {
6293
6214
  if (x.productId === product?.id && x.variantId === varId) x.quantity += quantity;
6294
6215
  });
6295
6216
  else resource.lineItems.push({
6296
- addedAt: addedAt ? addedAt : new Date().toISOString(),
6217
+ addedAt: addedAt ? addedAt : (/* @__PURE__ */ new Date()).toISOString(),
6297
6218
  id: v4(),
6298
6219
  key,
6299
6220
  productId: product.id,
@@ -6337,8 +6258,7 @@ var ShoppingListUpdateHandler = class extends AbstractUpdateHandler {
6337
6258
  code: "General",
6338
6259
  message: `A line item with ID '${lineItemId}' not found.`
6339
6260
  });
6340
- const shouldDelete = !quantity || quantity >= lineItem.quantity;
6341
- if (shouldDelete) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
6261
+ if (!quantity || quantity >= lineItem.quantity) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
6342
6262
  else resource.lineItems.forEach((x) => {
6343
6263
  if (x.id === lineItemId && quantity) x.quantity -= quantity;
6344
6264
  });
@@ -6435,17 +6355,14 @@ var ShoppingListRepository = class extends AbstractResourceRepository {
6435
6355
  const items = this._storage.query(projectKey, "product", { where: [`masterData(current(masterVariant(sku="${sku}"))) or masterData(current(variants(sku="${sku}")))`] });
6436
6356
  if (items.count === 0) throw new Error(`Product with sku ${sku} not found`);
6437
6357
  const product = items.results[0];
6438
- const allVariants = [product.masterData.current.masterVariant, ...product.masterData.current.variants];
6439
- const variantId$1 = allVariants.find((e) => e.sku === sku)?.id;
6440
- lineItem.variantId = variantId$1;
6358
+ lineItem.variantId = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((e) => e.sku === sku)?.id;
6441
6359
  lineItem.productId = product.id;
6442
6360
  return lineItem;
6443
6361
  }
6444
6362
  if (productId) {
6445
6363
  const items = this._storage.query(projectKey, "product", { where: [`id="${productId}"`] });
6446
6364
  if (items.count === 0) throw new Error(`Product with id ${productId} not found`);
6447
- const variantId$1 = items.results[0].masterData.current.masterVariant.id;
6448
- lineItem.variantId = variantId$1;
6365
+ lineItem.variantId = items.results[0].masterData.current.masterVariant.id;
6449
6366
  return lineItem;
6450
6367
  }
6451
6368
  throw new Error("must provide either sku, productId or variantId for ShoppingListLineItem");
@@ -6610,9 +6527,7 @@ var SubscriptionRepository = class extends AbstractResourceRepository {
6610
6527
  }
6611
6528
  create(context, draft) {
6612
6529
  if (draft.destination.type === "SQS") {
6613
- const queueURL = new URL(draft.destination.queueUrl);
6614
- const accountId = queueURL.pathname.split("/")[1];
6615
- if (accountId === "0000000000") {
6530
+ if (new URL(draft.destination.queueUrl).pathname.split("/")[1] === "0000000000") {
6616
6531
  const dest = draft.destination;
6617
6532
  throw new CommercetoolsError({
6618
6533
  code: "InvalidInput",
@@ -6664,10 +6579,7 @@ var TaxCategoryUpdateHandler = class extends AbstractUpdateHandler {
6664
6579
  replaceTaxRate(context, resource, { taxRateId, taxRate }) {
6665
6580
  if (resource.rates === void 0) resource.rates = [];
6666
6581
  const taxRateObj = taxRateFromTaxRateDraft(taxRate);
6667
- for (let i = 0; i < resource.rates.length; i++) {
6668
- const rate = resource.rates[i];
6669
- if (rate.id === taxRateId) resource.rates[i] = taxRateObj;
6670
- }
6582
+ for (let i = 0; i < resource.rates.length; i++) if (resource.rates[i].id === taxRateId) resource.rates[i] = taxRateObj;
6671
6583
  }
6672
6584
  setDescription(context, resource, { description }) {
6673
6585
  resource.description = description;
@@ -6875,11 +6787,10 @@ const validateData = (data, schema) => {
6875
6787
  schema.parse(data);
6876
6788
  return data;
6877
6789
  } catch (err) {
6878
- const validationError = fromZodError(err);
6879
6790
  throw new CommercetoolsError({
6880
6791
  code: "InvalidJsonInput",
6881
6792
  message: "Request body does not contain valid JSON.",
6882
- detailedErrorMessage: validationError.toString()
6793
+ detailedErrorMessage: fromZodError(err).toString()
6883
6794
  });
6884
6795
  }
6885
6796
  };
@@ -6921,7 +6832,6 @@ var AbstractService = class {
6921
6832
  }
6922
6833
  const result = this.repository.query(getRepositoryContext(request), params);
6923
6834
  response.status(200).send(result);
6924
- return;
6925
6835
  }
6926
6836
  getWithId(request, response) {
6927
6837
  const result = this._expandWithId(request, request.params.id);
@@ -7003,8 +6913,7 @@ var AbstractService = class {
7003
6913
  response.status(200).send(result);
7004
6914
  }
7005
6915
  _expandWithId(request, resourceId) {
7006
- const result = this.repository.get(getRepositoryContext(request), resourceId, { expand: this._parseParam(request.query.expand) });
7007
- return result;
6916
+ return this.repository.get(getRepositoryContext(request), resourceId, { expand: this._parseParam(request.query.expand) });
7008
6917
  }
7009
6918
  _parseParam(value) {
7010
6919
  return queryParamsArray(value);
@@ -7291,8 +7200,7 @@ var CustomerService = class extends AbstractService {
7291
7200
  post(request, response) {
7292
7201
  const draft = request.body;
7293
7202
  const resource = this.repository.create(getRepositoryContext(request), draft);
7294
- const expanded = this._expandWithId(request, resource.id);
7295
- const result = { customer: expanded };
7203
+ const result = { customer: this._expandWithId(request, resource.id) };
7296
7204
  response.status(this.createStatusCode).send(result);
7297
7205
  }
7298
7206
  passwordResetToken(request, response) {
@@ -7602,12 +7510,7 @@ var OrderService = class extends AbstractService {
7602
7510
  }
7603
7511
  getWithOrderNumber(request, response) {
7604
7512
  const orderNumber = request.params.orderNumber;
7605
- const resource = this.repository.getWithOrderNumber(
7606
- getRepositoryContext(request),
7607
- orderNumber,
7608
- // @ts-ignore
7609
- request.query
7610
- );
7513
+ const resource = this.repository.getWithOrderNumber(getRepositoryContext(request), orderNumber, request.query);
7611
7514
  if (resource) {
7612
7515
  response.status(200).send(resource);
7613
7516
  return;
@@ -7845,7 +7748,6 @@ var ShippingMethodService = class extends AbstractService {
7845
7748
  }
7846
7749
  const result = this.repository.matchingCart(getRepositoryContext(request), cartId, { expand: this._parseParam(request.query.expand) });
7847
7750
  response.status(200).send(result);
7848
- return;
7849
7751
  }
7850
7752
  };
7851
7753
 
@@ -8107,44 +8009,44 @@ var InMemoryStorage = class extends AbstractStorage {
8107
8009
  this.addProject(projectKey);
8108
8010
  let projectStorage = this.resources[projectKey];
8109
8011
  if (!projectStorage) projectStorage = this.resources[projectKey] = {
8110
- "associate-role": new Map(),
8111
- "attribute-group": new Map(),
8112
- "business-unit": new Map(),
8113
- cart: new Map(),
8114
- "cart-discount": new Map(),
8115
- category: new Map(),
8116
- channel: new Map(),
8117
- customer: new Map(),
8118
- "customer-group": new Map(),
8119
- "discount-code": new Map(),
8120
- "discount-group": new Map(),
8121
- extension: new Map(),
8122
- "inventory-entry": new Map(),
8123
- "key-value-document": new Map(),
8124
- order: new Map(),
8125
- "order-edit": new Map(),
8126
- payment: new Map(),
8127
- product: new Map(),
8128
- quote: new Map(),
8129
- "quote-request": new Map(),
8130
- "product-discount": new Map(),
8131
- "product-selection": new Map(),
8132
- "product-type": new Map(),
8133
- "product-projection": new Map(),
8134
- "product-tailoring": new Map(),
8135
- "recurrence-policy": new Map(),
8136
- "recurring-order": new Map(),
8137
- review: new Map(),
8138
- "shipping-method": new Map(),
8139
- "staged-quote": new Map(),
8140
- state: new Map(),
8141
- store: new Map(),
8142
- "shopping-list": new Map(),
8143
- "standalone-price": new Map(),
8144
- subscription: new Map(),
8145
- "tax-category": new Map(),
8146
- type: new Map(),
8147
- zone: new Map()
8012
+ "associate-role": /* @__PURE__ */ new Map(),
8013
+ "attribute-group": /* @__PURE__ */ new Map(),
8014
+ "business-unit": /* @__PURE__ */ new Map(),
8015
+ cart: /* @__PURE__ */ new Map(),
8016
+ "cart-discount": /* @__PURE__ */ new Map(),
8017
+ category: /* @__PURE__ */ new Map(),
8018
+ channel: /* @__PURE__ */ new Map(),
8019
+ customer: /* @__PURE__ */ new Map(),
8020
+ "customer-group": /* @__PURE__ */ new Map(),
8021
+ "discount-code": /* @__PURE__ */ new Map(),
8022
+ "discount-group": /* @__PURE__ */ new Map(),
8023
+ extension: /* @__PURE__ */ new Map(),
8024
+ "inventory-entry": /* @__PURE__ */ new Map(),
8025
+ "key-value-document": /* @__PURE__ */ new Map(),
8026
+ order: /* @__PURE__ */ new Map(),
8027
+ "order-edit": /* @__PURE__ */ new Map(),
8028
+ payment: /* @__PURE__ */ new Map(),
8029
+ product: /* @__PURE__ */ new Map(),
8030
+ quote: /* @__PURE__ */ new Map(),
8031
+ "quote-request": /* @__PURE__ */ new Map(),
8032
+ "product-discount": /* @__PURE__ */ new Map(),
8033
+ "product-selection": /* @__PURE__ */ new Map(),
8034
+ "product-type": /* @__PURE__ */ new Map(),
8035
+ "product-projection": /* @__PURE__ */ new Map(),
8036
+ "product-tailoring": /* @__PURE__ */ new Map(),
8037
+ "recurrence-policy": /* @__PURE__ */ new Map(),
8038
+ "recurring-order": /* @__PURE__ */ new Map(),
8039
+ review: /* @__PURE__ */ new Map(),
8040
+ "shipping-method": /* @__PURE__ */ new Map(),
8041
+ "staged-quote": /* @__PURE__ */ new Map(),
8042
+ state: /* @__PURE__ */ new Map(),
8043
+ store: /* @__PURE__ */ new Map(),
8044
+ "shopping-list": /* @__PURE__ */ new Map(),
8045
+ "standalone-price": /* @__PURE__ */ new Map(),
8046
+ subscription: /* @__PURE__ */ new Map(),
8047
+ "tax-category": /* @__PURE__ */ new Map(),
8048
+ type: /* @__PURE__ */ new Map(),
8049
+ zone: /* @__PURE__ */ new Map()
8148
8050
  };
8149
8051
  return projectStorage;
8150
8052
  }
@@ -8157,8 +8059,7 @@ var InMemoryStorage = class extends AbstractStorage {
8157
8059
  return [];
8158
8060
  }
8159
8061
  add(projectKey, typeId, obj, params = {}) {
8160
- const store = this.forProjectKey(projectKey);
8161
- store[typeId]?.set(obj.id, obj);
8062
+ this.forProjectKey(projectKey)[typeId]?.set(obj.id, obj);
8162
8063
  const resource = this.get(projectKey, typeId, obj.id, params);
8163
8064
  assert(resource, `resource of type ${typeId} with id ${obj.id} not created`);
8164
8065
  return cloneObject(resource);
@@ -8175,8 +8076,7 @@ var InMemoryStorage = class extends AbstractStorage {
8175
8076
  const store = this.forProjectKey(projectKey);
8176
8077
  const resourceStore = store[typeId];
8177
8078
  if (!store) throw new Error("No type");
8178
- const resources = Array.from(resourceStore.values());
8179
- const resource = resources.find((e) => e.key === key);
8079
+ const resource = Array.from(resourceStore.values()).find((e) => e.key === key);
8180
8080
  if (resource) {
8181
8081
  const clone = cloneObject(resource);
8182
8082
  return this.expand(projectKey, clone, params.expand);
@@ -8192,8 +8092,7 @@ var InMemoryStorage = class extends AbstractStorage {
8192
8092
  return resource;
8193
8093
  }
8194
8094
  query(projectKey, typeId, params) {
8195
- const store = this.forProjectKey(projectKey)[typeId];
8196
- if (!store) throw new Error("No type");
8095
+ if (!this.forProjectKey(projectKey)[typeId]) throw new Error("No type");
8197
8096
  let resources = this.all(projectKey, typeId);
8198
8097
  if (params.where) {
8199
8098
  const vars = Object.fromEntries(Object.entries(params).filter(([key]) => key.startsWith("var.")).map(([key, value]) => [key.slice(4), value]));
@@ -8288,8 +8187,7 @@ var InMemoryStorage = class extends AbstractStorage {
8288
8187
  id: lineItem.productId
8289
8188
  });
8290
8189
  if (!product) return;
8291
- const variant = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((e) => e.id === lineItem.variantId);
8292
- lineItem.variant = variant;
8190
+ lineItem.variant = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((e) => e.id === lineItem.variantId);
8293
8191
  }
8294
8192
  };
8295
8193
 
@@ -8353,17 +8251,14 @@ var CommercetoolsMock = class {
8353
8251
  return this._oauth2.store;
8354
8252
  }
8355
8253
  runServer(port = 3e3, options) {
8356
- const server = this.app.listen(port, () => {
8357
- console.info(`Mock server listening at http://localhost:${port}`);
8358
- });
8254
+ const server = this.app.listen(port, () => {});
8359
8255
  server.keepAliveTimeout = 60 * 1e3;
8360
8256
  }
8361
8257
  createApp(options) {
8362
- const config = {
8258
+ this._repositories = createRepositories({
8363
8259
  strict: this.options.strict,
8364
8260
  storage: this._storage
8365
- };
8366
- this._repositories = createRepositories(config);
8261
+ });
8367
8262
  this._oauth2.setCustomerRepository(this._repositories.customer);
8368
8263
  const app = express();
8369
8264
  app.use(express.json({ limit: "16mb" }));
@@ -8396,9 +8291,7 @@ var CommercetoolsMock = class {
8396
8291
  });
8397
8292
  return;
8398
8293
  }
8399
- console.error(err);
8400
8294
  resp.status(500).send({ error: err.message });
8401
- return;
8402
8295
  });
8403
8296
  return app;
8404
8297
  }
@@ -8426,9 +8319,8 @@ var CommercetoolsMock = class {
8426
8319
  const res = await inject(app).get(`${url.pathname}?${url.searchParams.toString()}`).body(body).headers(headers).end();
8427
8320
  if (res.statusCode === 200) {
8428
8321
  const parsedBody = JSON.parse(res.body);
8429
- const resultCount = "count" in parsedBody ? parsedBody.count : Object.keys(parsedBody).length;
8430
8322
  return new HttpResponse(null, {
8431
- status: resultCount > 0 ? 200 : 404,
8323
+ status: ("count" in parsedBody ? parsedBody.count : Object.keys(parsedBody).length) > 0 ? 200 : 404,
8432
8324
  headers: mapHeaderType(res.headers)
8433
8325
  });
8434
8326
  }
@@ -8476,13 +8368,13 @@ var CommercetoolsMock = class {
8476
8368
  if (_globalListeners.length > 0) {
8477
8369
  if (this._mswServer !== void 0) throw new Error("Server already started");
8478
8370
  process.emitWarning("Server wasn't stopped properly, clearing");
8479
- _globalListeners.forEach((listener) => listener.close());
8371
+ for (const listener of _globalListeners) listener.close();
8372
+ _globalListeners.length = 0;
8480
8373
  }
8481
8374
  const server = setupServer();
8482
8375
  this.registerHandlers(server);
8483
8376
  server.listen({ onUnhandledRequest: (request, print) => {
8484
- const url = new URL(request.url);
8485
- if (url.hostname === "127.0.0.1") return;
8377
+ if (new URL(request.url).hostname === "127.0.0.1") return;
8486
8378
  print.error();
8487
8379
  } });
8488
8380
  _globalListeners.push(server);
@@ -8492,4 +8384,4 @@ var CommercetoolsMock = class {
8492
8384
 
8493
8385
  //#endregion
8494
8386
  export { CommercetoolsMock, getBaseResourceProperties };
8495
- //# sourceMappingURL=index.js.map
8387
+ //# sourceMappingURL=index.mjs.map