@labdigital/commercetools-mock 2.60.0 → 2.61.1

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 (223) hide show
  1. package/dist/{index.d.ts → index.d.mts} +154 -275
  2. package/dist/{index.js → index.mjs} +255 -359
  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 +23 -28
  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 +11 -14
  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.test.ts +25 -0
  68. package/src/repositories/helpers.ts +14 -12
  69. package/src/repositories/index.test.ts +3 -3
  70. package/src/repositories/index.ts +43 -43
  71. package/src/repositories/inventory-entry/actions.ts +15 -3
  72. package/src/repositories/inventory-entry/index.ts +5 -5
  73. package/src/repositories/my-customer.ts +5 -5
  74. package/src/repositories/my-order.ts +2 -2
  75. package/src/repositories/my-quote-request.ts +1 -1
  76. package/src/repositories/order/actions.ts +8 -9
  77. package/src/repositories/order/index.test.ts +8 -9
  78. package/src/repositories/order/index.ts +16 -17
  79. package/src/repositories/order-edit.ts +4 -4
  80. package/src/repositories/payment/actions.ts +6 -6
  81. package/src/repositories/payment/helpers.ts +3 -3
  82. package/src/repositories/payment/index.ts +7 -7
  83. package/src/repositories/product/actions.ts +7 -7
  84. package/src/repositories/product/helpers.ts +4 -4
  85. package/src/repositories/product/index.ts +13 -13
  86. package/src/repositories/product-discount.ts +9 -6
  87. package/src/repositories/product-projection.ts +7 -7
  88. package/src/repositories/product-selection.ts +9 -6
  89. package/src/repositories/product-tailoring.ts +6 -3
  90. package/src/repositories/product-type.ts +8 -5
  91. package/src/repositories/project.ts +5 -5
  92. package/src/repositories/quote/actions.ts +6 -6
  93. package/src/repositories/quote/index.ts +5 -5
  94. package/src/repositories/quote-request/actions.ts +6 -6
  95. package/src/repositories/quote-request/index.test.ts +3 -3
  96. package/src/repositories/quote-request/index.ts +5 -5
  97. package/src/repositories/quote-staged/actions.ts +6 -6
  98. package/src/repositories/quote-staged/index.ts +5 -5
  99. package/src/repositories/recurrence-policy/actions.ts +3 -3
  100. package/src/repositories/recurrence-policy/index.ts +4 -8
  101. package/src/repositories/recurring-order/actions.ts +3 -3
  102. package/src/repositories/recurring-order/index.ts +5 -5
  103. package/src/repositories/review.test.ts +5 -5
  104. package/src/repositories/review.ts +10 -9
  105. package/src/repositories/shipping-method/actions.ts +7 -9
  106. package/src/repositories/shipping-method/helpers.ts +1 -1
  107. package/src/repositories/shipping-method/index.ts +8 -8
  108. package/src/repositories/shopping-list/actions.ts +5 -5
  109. package/src/repositories/shopping-list/index.ts +7 -7
  110. package/src/repositories/standalone-price.ts +9 -6
  111. package/src/repositories/state.ts +9 -6
  112. package/src/repositories/store.ts +10 -7
  113. package/src/repositories/subscription.test.ts +3 -3
  114. package/src/repositories/subscription.ts +9 -6
  115. package/src/repositories/tax-category/actions.ts +4 -4
  116. package/src/repositories/tax-category/index.ts +6 -6
  117. package/src/repositories/type/actions.ts +4 -4
  118. package/src/repositories/type/index.ts +5 -5
  119. package/src/repositories/zone.test.ts +3 -3
  120. package/src/repositories/zone.ts +8 -5
  121. package/src/server.ts +4 -3
  122. package/src/services/abstract.ts +5 -5
  123. package/src/services/as-associate-cart.test.ts +1 -1
  124. package/src/services/as-associate-cart.ts +2 -2
  125. package/src/services/as-associate-order.test.ts +1 -1
  126. package/src/services/as-associate-order.ts +2 -2
  127. package/src/services/as-associate-quote-request.ts +2 -3
  128. package/src/services/as-associate.test.ts +1 -1
  129. package/src/services/as-associate.ts +4 -4
  130. package/src/services/associate-roles.test.ts +1 -1
  131. package/src/services/associate-roles.ts +2 -2
  132. package/src/services/attribute-group.test.ts +1 -1
  133. package/src/services/attribute-group.ts +2 -2
  134. package/src/services/business-units.test.ts +5 -5
  135. package/src/services/business-units.ts +2 -2
  136. package/src/services/cart-discount.ts +2 -2
  137. package/src/services/cart.test.ts +7 -3
  138. package/src/services/cart.ts +4 -5
  139. package/src/services/category.test.ts +1 -1
  140. package/src/services/category.ts +2 -2
  141. package/src/services/channel.test.ts +1 -1
  142. package/src/services/channel.ts +2 -2
  143. package/src/services/custom-object.test.ts +2 -2
  144. package/src/services/custom-object.ts +3 -3
  145. package/src/services/customer-group.test.ts +1 -1
  146. package/src/services/customer-group.ts +2 -2
  147. package/src/services/customer.test.ts +3 -3
  148. package/src/services/customer.ts +4 -5
  149. package/src/services/discount-code.test.ts +1 -1
  150. package/src/services/discount-code.ts +2 -2
  151. package/src/services/discount-group.test.ts +1 -1
  152. package/src/services/discount-group.ts +2 -2
  153. package/src/services/extension.test.ts +1 -1
  154. package/src/services/extension.ts +2 -2
  155. package/src/services/index.ts +44 -44
  156. package/src/services/inventory-entry.test.ts +16 -1
  157. package/src/services/inventory-entry.ts +2 -2
  158. package/src/services/my-business-unit.test.ts +1 -1
  159. package/src/services/my-business-unit.ts +2 -2
  160. package/src/services/my-cart.test.ts +1 -1
  161. package/src/services/my-cart.ts +2 -2
  162. package/src/services/my-customer.test.ts +2 -2
  163. package/src/services/my-customer.ts +6 -6
  164. package/src/services/my-order.ts +2 -2
  165. package/src/services/my-payment.test.ts +1 -1
  166. package/src/services/my-payment.ts +2 -2
  167. package/src/services/my-shopping-list.ts +2 -2
  168. package/src/services/order.test.ts +4 -11
  169. package/src/services/order.ts +4 -4
  170. package/src/services/payment.test.ts +1 -1
  171. package/src/services/payment.ts +2 -2
  172. package/src/services/product-discount.test.ts +1 -1
  173. package/src/services/product-discount.ts +2 -2
  174. package/src/services/product-projection.test.ts +2 -2
  175. package/src/services/product-projection.ts +4 -4
  176. package/src/services/product-selection.test.ts +1 -1
  177. package/src/services/product-selection.ts +2 -2
  178. package/src/services/product-type.test.ts +1 -1
  179. package/src/services/product-type.ts +2 -2
  180. package/src/services/product.test.ts +1 -1
  181. package/src/services/product.ts +3 -3
  182. package/src/services/project.test.ts +1 -1
  183. package/src/services/project.ts +4 -4
  184. package/src/services/quote-request.test.ts +2 -2
  185. package/src/services/quote-request.ts +2 -2
  186. package/src/services/quote-staged.ts +2 -2
  187. package/src/services/quote.ts +2 -2
  188. package/src/services/recurrence-policy.test.ts +1 -1
  189. package/src/services/recurrence-policy.ts +2 -2
  190. package/src/services/recurring-order.test.ts +1 -1
  191. package/src/services/recurring-order.ts +2 -2
  192. package/src/services/reviews.test.ts +1 -1
  193. package/src/services/reviews.ts +2 -2
  194. package/src/services/shipping-method.test.ts +2 -2
  195. package/src/services/shipping-method.ts +4 -4
  196. package/src/services/shopping-list.test.ts +1 -1
  197. package/src/services/shopping-list.ts +2 -2
  198. package/src/services/standalone-price.test.ts +1 -1
  199. package/src/services/standalone-price.ts +2 -2
  200. package/src/services/state.test.ts +1 -1
  201. package/src/services/state.ts +2 -2
  202. package/src/services/store.test.ts +1 -1
  203. package/src/services/store.ts +2 -2
  204. package/src/services/subscription.test.ts +1 -1
  205. package/src/services/subscription.ts +2 -2
  206. package/src/services/tax-category.test.ts +1 -1
  207. package/src/services/tax-category.ts +2 -2
  208. package/src/services/type.test.ts +1 -1
  209. package/src/services/type.ts +2 -2
  210. package/src/services/zone.test.ts +1 -1
  211. package/src/services/zone.ts +2 -2
  212. package/src/shipping.test.ts +1 -1
  213. package/src/shipping.ts +8 -8
  214. package/src/storage/abstract.ts +1 -1
  215. package/src/storage/in-memory.ts +15 -17
  216. package/src/storage/index.ts +2 -2
  217. package/src/testing/business-unit.ts +1 -2
  218. package/src/testing/customer.ts +1 -1
  219. package/src/testing/type.ts +1 -1
  220. package/src/types.ts +1 -1
  221. package/src/validate.ts +1 -1
  222. package/dist/index.d.ts.map +0 -1
  223. 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)) {
@@ -527,7 +513,11 @@ var ProductTailoringUpdateHandler = class extends AbstractUpdateHandler {
527
513
  const createAddress = (base, projectKey, storage) => {
528
514
  if (!base) return void 0;
529
515
  if (!base?.country) throw new Error("Country is required");
530
- return { ...base };
516
+ const generateRandomId = () => Math.random().toString(36).substring(2, 10).padEnd(8, "0");
517
+ return {
518
+ ...base,
519
+ id: base.id ?? generateRandomId()
520
+ };
531
521
  };
532
522
  const createCustomFields = (draft, projectKey, storage) => {
533
523
  if (!draft) return void 0;
@@ -601,17 +591,15 @@ const createCentPrecisionMoney = (value) => {
601
591
  };
602
592
  };
603
593
  const createTypedMoney = (value) => {
604
- const result = createCentPrecisionMoney(value);
605
- return result;
594
+ return createCentPrecisionMoney(value);
606
595
  };
607
596
  const resolveStoreReference = (ref, projectKey, storage) => {
608
597
  if (!ref) return void 0;
609
598
  const resource = storage.getByResourceIdentifier(projectKey, ref);
610
599
  if (!resource) throw new Error("No such store");
611
- const store = resource;
612
600
  return {
613
601
  typeId: "store",
614
- key: store.key
602
+ key: resource.key
615
603
  };
616
604
  };
617
605
  const getReferenceFromResourceIdentifier = (resourceIdentifier, projectKey, storage) => {
@@ -713,7 +701,7 @@ const calculateTaxTotals = (resource) => {
713
701
  let totalNet = 0;
714
702
  let totalGross = 0;
715
703
  let totalTax = 0;
716
- const taxPortionsByRate = new Map();
704
+ const taxPortionsByRate = /* @__PURE__ */ new Map();
717
705
  taxedItemPrices.forEach((price) => {
718
706
  totalNet += price.totalNet.centAmount;
719
707
  totalGross += price.totalGross.centAmount;
@@ -746,7 +734,7 @@ const calculateTaxTotals = (resource) => {
746
734
  };
747
735
  };
748
736
  const buildTaxedPriceFromRate = (amount, currencyCode, taxRate) => {
749
- if (!taxRate) return void 0;
737
+ if (!taxRate) return;
750
738
  const toMoney = (centAmount) => createCentPrecisionMoney({
751
739
  type: "centPrecision",
752
740
  currencyCode,
@@ -777,10 +765,9 @@ const buildTaxedPriceFromRate = (amount, currencyCode, taxRate) => {
777
765
  };
778
766
  const calculateTaxedPriceFromRate = (amount, currencyCode, taxRate) => buildTaxedPriceFromRate(amount, currencyCode, taxRate);
779
767
  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;
768
+ if (!taxCategory || !taxCategory.rates.length) return;
769
+ const taxedItemPrice = buildTaxedPriceFromRate(amount, currency, taxCategory.rates.find((rate) => !rate.country || rate.country === country) || taxCategory.rates[0]);
770
+ if (!taxedItemPrice) return;
784
771
  return {
785
772
  totalNet: taxedItemPrice.totalNet,
786
773
  totalGross: taxedItemPrice.totalGross,
@@ -827,11 +814,10 @@ const getShippingMethodsMatchingCart = (context, storage, cart, params = {}) =>
827
814
  code: "InvalidOperation",
828
815
  message: `The cart with ID '${cart.id}' does not have a shipping address set.`
829
816
  });
830
- const zones = storage.query(context.projectKey, "zone", {
817
+ const zoneIds = storage.query(context.projectKey, "zone", {
831
818
  where: [`locations(country="${cart.shippingAddress.country}"))`],
832
819
  limit: 100
833
- });
834
- const zoneIds = zones.results.map((zone) => zone.id);
820
+ }).results.map((zone) => zone.id);
835
821
  const shippingMethods = storage.query(context.projectKey, "shipping-method", {
836
822
  where: ["zoneRates(zone(id in (:zoneIds)))", `zoneRates(shippingRates(price(currencyCode="${cart.totalPrice.currencyCode}")))`],
837
823
  "var.zoneIds": zoneIds,
@@ -891,15 +877,14 @@ const createShippingInfoFromMethod = (context, storage, resource, method) => {
891
877
  centAmount: totalGross.centAmount - totalNet.centAmount
892
878
  }
893
879
  }];
894
- const totalTax = {
895
- ...shippingPrice,
896
- centAmount: taxPortions.reduce((acc, portion) => acc + portion.amount.centAmount, 0)
897
- };
898
880
  const taxedPrice = {
899
881
  totalNet,
900
882
  totalGross,
901
883
  taxPortions,
902
- totalTax
884
+ totalTax: {
885
+ ...shippingPrice,
886
+ centAmount: taxPortions.reduce((acc, portion) => acc + portion.amount.centAmount, 0)
887
+ }
903
888
  };
904
889
  return {
905
890
  shippingMethod: {
@@ -919,7 +904,7 @@ const createShippingInfoFromMethod = (context, storage, resource, method) => {
919
904
  //#endregion
920
905
  //#region src/repositories/cart/helpers.ts
921
906
  const selectPrice = ({ prices, currency, country }) => {
922
- if (!prices) return void 0;
907
+ if (!prices) return;
923
908
  return prices.find((price) => {
924
909
  const countryMatch = !price.country || price.country === country;
925
910
  const currencyMatch = price.value.currencyCode === currency;
@@ -928,17 +913,15 @@ const selectPrice = ({ prices, currency, country }) => {
928
913
  };
929
914
  const calculateLineItemTotalPrice = (lineItem) => lineItem.price?.value.centAmount * lineItem.quantity;
930
915
  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;
916
+ return cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0) + cart.customLineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
934
917
  };
935
918
  const createCustomLineItemFromDraft = (projectKey, draft, storage, country) => {
936
919
  const quantity = draft.quantity ?? 1;
937
920
  const taxCategoryRef = draft.taxCategory ? getReferenceFromResourceIdentifier(draft.taxCategory, projectKey, storage) : void 0;
938
- let taxCategory = void 0;
921
+ let taxCategory;
939
922
  if (taxCategoryRef) try {
940
923
  taxCategory = storage.get(projectKey, "tax-category", taxCategoryRef.id, {}) || void 0;
941
- } catch (error) {}
924
+ } catch (_error) {}
942
925
  const totalPrice = createCentPrecisionMoney({
943
926
  ...draft.money,
944
927
  centAmount: (draft.money.centAmount ?? 0) * quantity
@@ -997,8 +980,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
997
980
  code: "General",
998
981
  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
982
  });
1000
- const alreadyAdded = resource.lineItems.some((x) => x.productId === product?.id && x.variant.id === variant?.id);
1001
- if (alreadyAdded) resource.lineItems.forEach((x) => {
983
+ if (resource.lineItems.some((x) => x.productId === product?.id && x.variant.id === variant?.id)) resource.lineItems.forEach((x) => {
1002
984
  if (x.productId === product?.id && x.variant.id === variant?.id) {
1003
985
  x.quantity += quantity;
1004
986
  x.totalPrice.centAmount = calculateLineItemTotalPrice(x);
@@ -1019,7 +1001,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
1019
1001
  resource.lineItems.push({
1020
1002
  id: v4(),
1021
1003
  key,
1022
- addedAt: addedAt ? addedAt : new Date().toISOString(),
1004
+ addedAt: addedAt ? addedAt : (/* @__PURE__ */ new Date()).toISOString(),
1023
1005
  productId: product.id,
1024
1006
  productKey: product.key,
1025
1007
  productSlug: product.masterData.current.slug,
@@ -1084,8 +1066,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
1084
1066
  code: "General",
1085
1067
  message: `A line item with ID '${lineItemId}' not found.`
1086
1068
  });
1087
- const shouldDelete = !quantity || quantity >= lineItem.quantity;
1088
- if (shouldDelete) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
1069
+ if (!quantity || quantity >= lineItem.quantity) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
1089
1070
  else resource.lineItems.forEach((x) => {
1090
1071
  if (x.id === lineItemId && quantity) {
1091
1072
  x.quantity -= quantity;
@@ -1336,7 +1317,7 @@ var CartUpdateHandler = class extends AbstractUpdateHandler {
1336
1317
  resource.shippingAddress = void 0;
1337
1318
  return;
1338
1319
  }
1339
- let custom = void 0;
1320
+ let custom;
1340
1321
  if (address.custom) custom = createCustomFields(address.custom, context.projectKey, this._storage);
1341
1322
  resource.shippingAddress = {
1342
1323
  ...address,
@@ -1395,7 +1376,7 @@ var CartRepository = class extends AbstractResourceRepository {
1395
1376
  typeId: "customer",
1396
1377
  id: draft.customerId
1397
1378
  });
1398
- let storedBusinessUnit = void 0;
1379
+ let storedBusinessUnit;
1399
1380
  if (draft.businessUnit?.id || draft.businessUnit?.key) storedBusinessUnit = this._storage.getByResourceIdentifier(context.projectKey, {
1400
1381
  typeId: "business-unit",
1401
1382
  id: draft.businessUnit.id,
@@ -1457,7 +1438,6 @@ var CartRepository = class extends AbstractResourceRepository {
1457
1438
  getActiveCart(projectKey) {
1458
1439
  const results = this._storage.query(projectKey, this.getTypeId(), { where: [`cartState="Active"`] });
1459
1440
  if (results.count > 0) return results.results[0];
1460
- return;
1461
1441
  }
1462
1442
  draftLineItemtoLineItem = (projectKey, draftLineItem, currency, country) => {
1463
1443
  const { productId, quantity, variantId, sku } = draftLineItem;
@@ -1512,8 +1492,7 @@ var CartRepository = class extends AbstractResourceRepository {
1512
1492
  createShippingInfo(context, resource, shippingMethodRef) {
1513
1493
  if (resource.taxMode === "External") throw new Error("External tax rate is not supported");
1514
1494
  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);
1495
+ const method = getShippingMethodsMatchingCart(context, this._storage, resource, { expand: ["zoneRates[*].zone"] }).results.find((candidate) => shippingMethodRef.id ? candidate.id === shippingMethodRef.id : candidate.key === shippingMethodRef.key);
1517
1496
  if (!method) throw new CommercetoolsError({
1518
1497
  code: "ShippingMethodDoesNotMatchCart",
1519
1498
  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 +1505,7 @@ var CartRepository = class extends AbstractResourceRepository {
1526
1505
  //#region src/repositories/order/actions.ts
1527
1506
  var OrderUpdateHandler = class extends AbstractUpdateHandler {
1528
1507
  addPayment(context, resource, { payment }) {
1529
- const resolvedPayment = this._storage.getByResourceIdentifier(context.projectKey, payment);
1530
- if (!resolvedPayment) throw new Error(`Payment ${payment.id} not found`);
1508
+ if (!this._storage.getByResourceIdentifier(context.projectKey, payment)) throw new Error(`Payment ${payment.id} not found`);
1531
1509
  if (!resource.paymentInfo) resource.paymentInfo = { payments: [] };
1532
1510
  resource.paymentInfo.payments.push({
1533
1511
  typeId: "payment",
@@ -1649,10 +1627,9 @@ var OrderUpdateHandler = class extends AbstractUpdateHandler {
1649
1627
  if (!store) return;
1650
1628
  const resolvedType = this._storage.getByResourceIdentifier(context.projectKey, store);
1651
1629
  if (!resolvedType) throw new Error(`No store found with key=${store.key}`);
1652
- const storeReference = resolvedType;
1653
1630
  resource.store = {
1654
1631
  typeId: "store",
1655
- key: storeReference.key
1632
+ key: resolvedType.key
1656
1633
  };
1657
1634
  }
1658
1635
  transitionState(context, resource, { state }) {
@@ -1677,7 +1654,7 @@ var OrderUpdateHandler = class extends AbstractUpdateHandler {
1677
1654
  id: resolvedType.id
1678
1655
  },
1679
1656
  externalId,
1680
- syncedAt: syncedAt ?? new Date().toISOString()
1657
+ syncedAt: syncedAt ?? (/* @__PURE__ */ new Date()).toISOString()
1681
1658
  };
1682
1659
  if (!resource.syncInfo?.length) resource.syncInfo = [syncData];
1683
1660
  else {
@@ -1825,7 +1802,7 @@ var OrderRepository = class extends AbstractResourceRepository {
1825
1802
  ...draft.price.value,
1826
1803
  centAmount: (draft.price.value.centAmount ?? 0) * quantity
1827
1804
  });
1828
- const lineItem = {
1805
+ return {
1829
1806
  ...getBaseResourceProperties(),
1830
1807
  custom: createCustomFields(draft.custom, context.projectKey, this._storage),
1831
1808
  discountedPricePerQuantity: [],
@@ -1849,7 +1826,6 @@ var OrderRepository = class extends AbstractResourceRepository {
1849
1826
  attributes: variant.attributes
1850
1827
  }
1851
1828
  };
1852
- return lineItem;
1853
1829
  }
1854
1830
  customLineItemFromImportDraft(context, draft) {
1855
1831
  const quantity = draft.quantity ?? 1;
@@ -1857,7 +1833,7 @@ var OrderRepository = class extends AbstractResourceRepository {
1857
1833
  ...draft.money,
1858
1834
  centAmount: (draft.money.centAmount ?? 0) * quantity
1859
1835
  });
1860
- const lineItem = {
1836
+ return {
1861
1837
  ...getBaseResourceProperties(),
1862
1838
  custom: createCustomFields(draft.custom, context.projectKey, this._storage),
1863
1839
  discountedPricePerQuantity: [],
@@ -1872,7 +1848,6 @@ var OrderRepository = class extends AbstractResourceRepository {
1872
1848
  taxedPrice: calculateTaxedPriceFromRate(totalPrice.centAmount, totalPrice.currencyCode, draft.taxRate),
1873
1849
  taxedPricePortions: []
1874
1850
  };
1875
- return lineItem;
1876
1851
  }
1877
1852
  getWithOrderNumber(context, orderNumber, params = {}) {
1878
1853
  const result = this._storage.query(context.projectKey, this.getTypeId(), {
@@ -1881,7 +1856,6 @@ var OrderRepository = class extends AbstractResourceRepository {
1881
1856
  });
1882
1857
  if (result.count === 1) return result.results[0];
1883
1858
  if (result.count > 1) throw new Error("Duplicate order numbers");
1884
- return;
1885
1859
  }
1886
1860
  createShippingInfo(context, resource, shippingMethodRef) {
1887
1861
  const cartLikeForMatching = {
@@ -1897,15 +1871,13 @@ var OrderRepository = class extends AbstractResourceRepository {
1897
1871
  directDiscounts: resource.directDiscounts || [],
1898
1872
  shippingInfo: void 0
1899
1873
  };
1900
- const shippingMethods = getShippingMethodsMatchingCart(context, this._storage, cartLikeForMatching, { expand: ["zoneRates[*].zone"] });
1901
- const method = shippingMethods.results.find((candidate) => candidate.id === shippingMethodRef.id);
1874
+ const method = getShippingMethodsMatchingCart(context, this._storage, cartLikeForMatching, { expand: ["zoneRates[*].zone"] }).results.find((candidate) => candidate.id === shippingMethodRef.id);
1902
1875
  if (!method) throw new CommercetoolsError({
1903
1876
  code: "ShippingMethodDoesNotMatchCart",
1904
1877
  message: `The shipping method with ID '${shippingMethodRef.id}' is not allowed for the order with ID '${resource.id}'.`
1905
1878
  });
1906
- const baseShippingInfo = createShippingInfoFromMethod(context, this._storage, resource, method);
1907
1879
  return {
1908
- ...baseShippingInfo,
1880
+ ...createShippingInfoFromMethod(context, this._storage, resource, method),
1909
1881
  deliveries: []
1910
1882
  };
1911
1883
  }
@@ -1933,7 +1905,7 @@ var QuoteRequestUpdateHandler = class extends AbstractUpdateHandler {
1933
1905
  }
1934
1906
  }
1935
1907
  transitionState(context, resource, { state, force }) {
1936
- let stateReference = void 0;
1908
+ let stateReference;
1937
1909
  if (state) {
1938
1910
  stateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
1939
1911
  resource.state = stateReference;
@@ -2032,7 +2004,7 @@ var AssociateRoleUpdateHandler = class extends AbstractUpdateHandler {
2032
2004
  }
2033
2005
  removePermission(context, resource, { permission }) {
2034
2006
  if (!resource.permissions) return;
2035
- resource.permissions = resource.permissions.filter((p) => {});
2007
+ resource.permissions = resource.permissions.filter((p) => p !== permission);
2036
2008
  }
2037
2009
  setBuyerAssignable(context, resource, { buyerAssignable }) {
2038
2010
  resource.buyerAssignable = buyerAssignable;
@@ -2169,11 +2141,11 @@ var BusinessUnitUpdateHandler = class extends AbstractUpdateHandler {
2169
2141
  changeAddress(context, resource, { addressId, address }) {
2170
2142
  const existingAddressIndex = resource.addresses.findIndex((addr) => addr.id === addressId);
2171
2143
  if (existingAddressIndex === -1) throw new Error(`Address with id ${addressId} not found`);
2172
- const newAddress = createAddress(address, context.projectKey, this._storage);
2173
- if (newAddress) resource.addresses[existingAddressIndex] = {
2174
- ...newAddress,
2144
+ const newAddress = createAddress({
2145
+ ...address,
2175
2146
  id: addressId
2176
- };
2147
+ }, context.projectKey, this._storage);
2148
+ if (newAddress) resource.addresses[existingAddressIndex] = newAddress;
2177
2149
  }
2178
2150
  changeApprovalRuleMode(context, resource, { approvalRuleMode }) {
2179
2151
  resource.approvalRuleMode = approvalRuleMode;
@@ -2191,8 +2163,7 @@ var BusinessUnitUpdateHandler = class extends AbstractUpdateHandler {
2191
2163
  resource.status = status;
2192
2164
  }
2193
2165
  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;
2166
+ resource.associates = associates.map((a) => createAssociate(a, context.projectKey, this._storage)).filter((a) => a !== void 0) || void 0;
2196
2167
  }
2197
2168
  removeAssociate(context, resource, { customer }) {
2198
2169
  resource.associates = resource.associates.filter((associate) => associate.customer.id !== customer.id);
@@ -2510,8 +2481,7 @@ var CategoryRepository = class extends AbstractResourceRepository {
2510
2481
  postProcessResource(context, resource, params) {
2511
2482
  let node = resource;
2512
2483
  const ancestors = [];
2513
- const expandClauses = params?.expand?.map(parseExpandClause) ?? [];
2514
- const addExpand = expandClauses?.find((c) => c.element === "ancestors" && c.index === "*");
2484
+ const addExpand = (params?.expand?.map(parseExpandClause) ?? [])?.find((c) => c.element === "ancestors" && c.index === "*");
2515
2485
  while (node.parent) {
2516
2486
  node = this._storage.getByResourceIdentifier(context.projectKey, node.parent);
2517
2487
  ancestors.push({
@@ -2600,9 +2570,8 @@ var CustomObjectRepository = class extends AbstractResourceRepository {
2600
2570
  code: "InvalidOperation",
2601
2571
  message: "version on create must be 0"
2602
2572
  }, 400);
2603
- const baseProperties = getBaseResourceProperties();
2604
2573
  const resource = {
2605
- ...baseProperties,
2574
+ ...getBaseResourceProperties(),
2606
2575
  container: draft.container,
2607
2576
  key: draft.key,
2608
2577
  value: draft.value
@@ -2611,8 +2580,7 @@ var CustomObjectRepository = class extends AbstractResourceRepository {
2611
2580
  return resource;
2612
2581
  }
2613
2582
  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);
2583
+ return this._storage.all(context.projectKey, this.getTypeId()).find((item) => item.container === container && item.key === key);
2616
2584
  }
2617
2585
  queryWithContainer(context, container, params = {}) {
2618
2586
  const whereClause = params.where || [];
@@ -2655,11 +2623,11 @@ var CustomerUpdateHandler = class extends AbstractUpdateHandler {
2655
2623
  const current = this._findAddress(resource, addressId, addressKey, true);
2656
2624
  assert(current?.id);
2657
2625
  const oldAddressIndex = resource.addresses.findIndex((a) => a.id === current.id);
2658
- const newAddress = createAddress(address, context.projectKey, this._storage);
2659
- if (newAddress) resource.addresses[oldAddressIndex] = {
2660
- id: addressId,
2661
- ...newAddress
2662
- };
2626
+ const newAddress = createAddress({
2627
+ ...address,
2628
+ id: current.id
2629
+ }, context.projectKey, this._storage);
2630
+ if (newAddress) resource.addresses[oldAddressIndex] = newAddress;
2663
2631
  }
2664
2632
  changeEmail(_context, resource, { email }) {
2665
2633
  resource.email = email;
@@ -2718,10 +2686,9 @@ var CustomerUpdateHandler = class extends AbstractUpdateHandler {
2718
2686
  code: "InvalidOperation",
2719
2687
  message: "CustomerGroup is required."
2720
2688
  }, 400);
2721
- const group = this._storage.getByResourceIdentifier(context.projectKey, action.customerGroup);
2722
2689
  resource.customerGroup = {
2723
2690
  typeId: "customer-group",
2724
- id: group.id
2691
+ id: this._storage.getByResourceIdentifier(context.projectKey, action.customerGroup).id
2725
2692
  };
2726
2693
  }
2727
2694
  setCustomerNumber(_context, resource, { customerNumber }) {
@@ -2818,8 +2785,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2818
2785
  this.actions = new CustomerUpdateHandler(config.storage);
2819
2786
  }
2820
2787
  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({
2788
+ if (this._storage.query(context.projectKey, this.getTypeId(), { where: [`lowercaseEmail="${draft.email.toLowerCase()}"`] }).count > 0) throw new CommercetoolsError({
2823
2789
  code: "CustomerAlreadyExists",
2824
2790
  statusCode: 400,
2825
2791
  message: "There is already an existing customer with the provided email.",
@@ -2896,7 +2862,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2896
2862
  message: `The Customer with ID '${request.email}' was not found.`
2897
2863
  });
2898
2864
  const ttlMinutes = request.ttlMinutes ?? 34560;
2899
- const expiresAt = new Date(new Date().getTime() + ttlMinutes * 60 * 1e3);
2865
+ const expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1e3);
2900
2866
  const customer = results.results[0];
2901
2867
  const rest = getBaseResourceProperties();
2902
2868
  const token = createPasswordResetToken(customer, expiresAt);
@@ -2933,7 +2899,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2933
2899
  code: "ResourceNotFound",
2934
2900
  message: `The Customer with ID '${id}' was not found.`
2935
2901
  });
2936
- const expiresAt = new Date(Date.now() + 30 * 60);
2902
+ const expiresAt = new Date(Date.now() + 1800);
2937
2903
  const customer = results.results[0];
2938
2904
  const rest = getBaseResourceProperties();
2939
2905
  const token = createEmailVerifyToken(customer);
@@ -3186,6 +3152,11 @@ var InventoryEntryUpdateHandler = class extends AbstractUpdateHandler {
3186
3152
  resource.quantityOnStock = quantity;
3187
3153
  resource.availableQuantity = quantity;
3188
3154
  }
3155
+ removeQuantity(context, resource, { quantity }) {
3156
+ const newQuantity = Math.max(0, resource.quantityOnStock - quantity);
3157
+ resource.quantityOnStock = newQuantity;
3158
+ resource.availableQuantity = newQuantity;
3159
+ }
3189
3160
  setCustomField(context, resource, { name, value }) {
3190
3161
  if (!resource.custom) throw new Error("Resource has no custom field");
3191
3162
  resource.custom.fields[name] = value;
@@ -3279,12 +3250,10 @@ var MyCustomerRepository = class extends CustomerRepository {
3279
3250
  deleteMe(context) {
3280
3251
  const results = this._storage.query(context.projectKey, this.getTypeId(), {});
3281
3252
  if (results.count > 0) return this.delete(context, results.results[0].id);
3282
- return;
3283
3253
  }
3284
3254
  getMe(context) {
3285
3255
  const results = this._storage.query(context.projectKey, this.getTypeId(), {});
3286
3256
  if (results.count > 0) return results.results[0];
3287
- return;
3288
3257
  }
3289
3258
  };
3290
3259
 
@@ -3365,8 +3334,7 @@ var PaymentUpdateHandler = class extends AbstractUpdateHandler {
3365
3334
  }
3366
3335
  setCustomer(_context, resource, { customer }) {
3367
3336
  if (customer) {
3368
- const c = getReferenceFromResourceIdentifier(customer, _context.projectKey, this._storage);
3369
- resource.customer = c;
3337
+ resource.customer = getReferenceFromResourceIdentifier(customer, _context.projectKey, this._storage);
3370
3338
  resource.anonymousId = void 0;
3371
3339
  }
3372
3340
  }
@@ -3508,11 +3476,10 @@ var ReviewStatisticsService = class {
3508
3476
  this._storage = _storage;
3509
3477
  }
3510
3478
  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;
3479
+ const productReviews = this._storage.all(projectKey, "review").filter((review) => review.target?.typeId === "product" && review.target?.id === productId && review.includedInStatistics && review.rating !== void 0);
3480
+ if (productReviews.length === 0) return;
3514
3481
  const ratings = productReviews.map((review) => review.rating).filter((rating) => rating !== void 0);
3515
- if (ratings.length === 0) return void 0;
3482
+ if (ratings.length === 0) return;
3516
3483
  const count = ratings.length;
3517
3484
  const sum = ratings.reduce((acc, rating) => acc + rating, 0);
3518
3485
  const averageRating = Math.round(sum / count * 1e5) / 1e5;
@@ -3615,11 +3582,9 @@ var Token = class {
3615
3582
  * @return {TokenPosition}
3616
3583
  */
3617
3584
  strpos() {
3618
- const start = this.lexer.strpos(this.start);
3619
- const end = this.lexer.strpos(this.end);
3620
3585
  return {
3621
- start,
3622
- end
3586
+ start: this.lexer.strpos(this.start),
3587
+ end: this.lexer.strpos(this.end)
3623
3588
  };
3624
3589
  }
3625
3590
  isEof() {
@@ -3850,7 +3815,7 @@ var Lexer = class {
3850
3815
  unexpected += e$1.unexpected;
3851
3816
  }
3852
3817
  const { line, column } = this.strpos(position);
3853
- const e = new Error(`Unexpected input: ${unexpected} at (${line}:${column})`);
3818
+ const e = /* @__PURE__ */ new Error(`Unexpected input: ${unexpected} at (${line}:${column})`);
3854
3819
  e.unexpected = unexpected;
3855
3820
  e.end = position + unexpected.length;
3856
3821
  throw e;
@@ -3863,11 +3828,9 @@ var Lexer = class {
3863
3828
  strpos(i) {
3864
3829
  let lines = this._state.source.substring(0, i).split(/\r?\n/);
3865
3830
  if (!Array.isArray(lines)) lines = [lines];
3866
- const line = lines.length;
3867
- const column = lines[lines.length - 1].length + 1;
3868
3831
  return {
3869
- line,
3870
- column
3832
+ line: lines.length,
3833
+ column: lines[lines.length - 1].length + 1
3871
3834
  };
3872
3835
  }
3873
3836
  /**
@@ -3905,7 +3868,7 @@ var Lexer = class {
3905
3868
  * @param kwd The keyword to add as a token
3906
3869
  */
3907
3870
  keyword(kwd) {
3908
- return this.token(kwd, new RegExp(`${kwd}(?=\\W|$)`));
3871
+ return this.token(kwd, /* @__PURE__ */ new RegExp(`${kwd}(?=\\W|$)`));
3909
3872
  }
3910
3873
  /**
3911
3874
  * Creates an operator
@@ -3977,9 +3940,9 @@ var Parser = class {
3977
3940
  * @type {ILexer<T>}
3978
3941
  */
3979
3942
  this.lexer = lexer;
3980
- this._nuds = new Map();
3981
- this._leds = new Map();
3982
- this._bps = new Map();
3943
+ this._nuds = /* @__PURE__ */ new Map();
3944
+ this._leds = /* @__PURE__ */ new Map();
3945
+ this._bps = /* @__PURE__ */ new Map();
3983
3946
  }
3984
3947
  _type(tokenOrType) {
3985
3948
  return tokenOrType && typeof tokenOrType.isEof == "function" ? tokenOrType.type : tokenOrType;
@@ -4047,10 +4010,9 @@ var Parser = class {
4047
4010
  }, true);
4048
4011
  };
4049
4012
  const mkinfo = (token) => {
4050
- const bp = this.bp(token);
4051
4013
  return {
4052
4014
  token,
4053
- bp,
4015
+ bp: this.bp(token),
4054
4016
  stop,
4055
4017
  ctx: opts.ctx,
4056
4018
  options: opts
@@ -4152,8 +4114,7 @@ const parseFilter = (filter) => {
4152
4114
  const parser = new Parser(lexer).builder().nud("IDENTIFIER", 100, (t) => t.token.match).led(":", 100, ({ left, bp }) => {
4153
4115
  const parsed = parser.parse({ terminals: [bp - 1] });
4154
4116
  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");
4117
+ if (new Set(expressions.map((expr) => expr.type)).size > 1) throw new Error("Invalid expression");
4157
4118
  if (expressions.some((expr) => expr.type === "Symbol")) return {
4158
4119
  source: left,
4159
4120
  type: "FilterExpression",
@@ -4238,22 +4199,18 @@ const generateFacetFunc = (filter) => {
4238
4199
  return parseFilter(filter);
4239
4200
  };
4240
4201
  const filterProduct = (source, exprFunc) => (p, markMatchingVariants) => {
4241
- const value = nestedLookup(p, source);
4242
- return exprFunc(value);
4202
+ return exprFunc(nestedLookup(p, source));
4243
4203
  };
4244
4204
  const filterVariants = (source, exprFunc) => (p, markMatchingVariants) => {
4245
4205
  const [, ...paths] = source.split(".");
4246
4206
  const path = paths.join(".");
4247
4207
  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;
4208
+ for (const variant of variants) if (exprFunc(resolveVariantValue(variant, path))) {
4209
+ if (markMatchingVariants) {
4210
+ for (const v of variants) v.isMatchingVariant = false;
4211
+ variant.isMatchingVariant = true;
4256
4212
  }
4213
+ return true;
4257
4214
  }
4258
4215
  return false;
4259
4216
  };
@@ -4262,7 +4219,7 @@ const resolveVariantValue = (obj, path) => {
4262
4219
  if (path.startsWith("variants.")) path = path.substring(path.indexOf(".") + 1);
4263
4220
  if (path.startsWith("attributes.")) {
4264
4221
  const [, attrName, ...rest] = path.split(".");
4265
- if (!obj.attributes) return void 0;
4222
+ if (!obj.attributes) return;
4266
4223
  for (const attr of obj.attributes) if (attr.name === attrName) return nestedLookup(attr.value, rest.join("."));
4267
4224
  }
4268
4225
  if (path === "price.centAmount") return obj.prices && obj.prices.length > 0 ? obj.prices[0].value.centAmount : void 0;
@@ -4274,17 +4231,14 @@ const getVariants = (p) => [p.masterVariant, ...p.variants ?? []];
4274
4231
  //#region src/lib/productSearchFilter.ts
4275
4232
  const parseSearchQuery = (searchQuery) => {
4276
4233
  if (isSearchAndExpression$1(searchQuery)) return (obj, markMatchingVariant) => searchQuery.and.every((expr) => {
4277
- const filterFunc = parseSearchQuery(expr);
4278
- return filterFunc(obj, markMatchingVariant);
4234
+ return parseSearchQuery(expr)(obj, markMatchingVariant);
4279
4235
  });
4280
4236
  if (isSearchOrExpression$1(searchQuery)) return (obj, markMatchingVariant) => searchQuery.or.some((expr) => {
4281
- const filterFunc = parseSearchQuery(expr);
4282
- return filterFunc(obj, markMatchingVariant);
4237
+ return parseSearchQuery(expr)(obj, markMatchingVariant);
4283
4238
  });
4284
4239
  if (isSearchNotExpression$1(searchQuery)) return (obj, markMatchingVariant) => !parseSearchQuery(searchQuery.not)(obj, markMatchingVariant);
4285
4240
  if (isSearchFilterExpression$1(searchQuery)) return (obj, markMatchingVariant) => searchQuery.filter.every((expr) => {
4286
- const filterFunc = parseSearchQuery(expr);
4287
- return filterFunc(obj, markMatchingVariant);
4241
+ return parseSearchQuery(expr)(obj, markMatchingVariant);
4288
4242
  });
4289
4243
  if (isSearchRangeExpression$1(searchQuery)) {
4290
4244
  const generateRangeMatchFunc = (value) => {
@@ -4320,18 +4274,15 @@ const generateFieldMatchFunc = (matchFunc, searchQuery) => {
4320
4274
  if (searchQuery.field.startsWith("variants.")) {
4321
4275
  const variantField = searchQuery.field.substring(searchQuery.field.indexOf(".") + 1);
4322
4276
  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;
4277
+ for (const variant of variants) if (matchFunc(resolveFieldValue(variant, {
4278
+ ...searchQuery,
4279
+ field: variantField
4280
+ }))) {
4281
+ if (markMatchingVariants) {
4282
+ for (const v of variants) v.isMatchingVariant = false;
4283
+ variant.isMatchingVariant = true;
4334
4284
  }
4285
+ return true;
4335
4286
  }
4336
4287
  return false;
4337
4288
  }
@@ -4346,7 +4297,7 @@ const resolveFieldValue = (obj, searchQuery) => {
4346
4297
  if (fieldPath.startsWith("variants.")) fieldPath = fieldPath.substring(fieldPath.indexOf(".") + 1);
4347
4298
  if (fieldPath.startsWith("attributes.")) {
4348
4299
  const [, attrName, ...rest] = fieldPath.split(".");
4349
- if (!obj.attributes) return void 0;
4300
+ if (!obj.attributes) return;
4350
4301
  for (const attr of obj.attributes) if (attr.name === attrName) return nestedLookupByLanguage(attr.value, rest.join("."), language);
4351
4302
  }
4352
4303
  if (fieldPath === "prices.currentCentAmount") return obj.prices && obj.prices.length > 0 ? obj.prices[0].value.centAmount : void 0;
@@ -4375,8 +4326,8 @@ const isSearchWildCardExpression$1 = (expr) => expr.wildcard !== void 0;
4375
4326
  //#endregion
4376
4327
  //#region src/lib/searchQueryTypeChecker.ts
4377
4328
  const validateSearchQuery = (query) => {
4378
- if (isSearchAndExpression(query)) query.and.forEach((expr) => validateSearchQuery(expr));
4379
- else if (isSearchOrExpression(query)) query.or.forEach((expr) => validateSearchQuery(expr));
4329
+ if (isSearchAndExpression(query)) for (const expr of query.and) validateSearchQuery(expr);
4330
+ else if (isSearchOrExpression(query)) for (const expr of query.or) validateSearchQuery(expr);
4380
4331
  else if (isSearchNotExpression(query)) validateSearchQuery(query.not);
4381
4332
  else if (isSearchFilterExpression(query) || isSearchRangeExpression(query) || isSearchExactExpression(query) || isSearchExistsExpression(query) || isSearchFullTextExpression(query) || isSearchFullTextPrefixExpression(query) || isSearchPrefixExpression(query) || isSearchWildCardExpression(query) || isSearchAnyValue(query)) return;
4382
4333
  else throw new Error("Unsupported search query expression");
@@ -4456,7 +4407,7 @@ var ProductSearch = class {
4456
4407
  isOnStockForChannel: existingEntry?.isOnStockForChannel ?? entry.supplyChannel?.id
4457
4408
  });
4458
4409
  return acc;
4459
- }, new Map());
4410
+ }, /* @__PURE__ */ new Map());
4460
4411
  let productResources = this._storage.all(projectKey, "product").map((r) => this.transformProduct(r, params.productProjectionParameters?.staged ?? false, availabilityBySku)).filter((p) => {
4461
4412
  if (!(params.productProjectionParameters?.staged ?? false)) return p.published;
4462
4413
  return true;
@@ -4467,7 +4418,6 @@ var ProductSearch = class {
4467
4418
  const matchFunc = parseSearchQuery(params.query);
4468
4419
  productResources = productResources.filter((resource) => matchFunc(resource, markMatchingVariant));
4469
4420
  } catch (err) {
4470
- console.error(err);
4471
4421
  throw new CommercetoolsError({
4472
4422
  code: "InvalidInput",
4473
4423
  message: err.message
@@ -4543,8 +4493,7 @@ var ProductSearch = class {
4543
4493
  //#endregion
4544
4494
  //#region src/repositories/product/helpers.ts
4545
4495
  const getVariant = (productData, variantId, sku) => {
4546
- const variants = [productData.masterVariant, ...productData.variants];
4547
- const foundVariant = variants.find((variant) => {
4496
+ const foundVariant = [productData.masterVariant, ...productData.variants].find((variant) => {
4548
4497
  if (variantId) return variant.id === variantId;
4549
4498
  if (sku) return variant.sku === sku;
4550
4499
  return false;
@@ -4571,12 +4520,11 @@ const variantFromDraft = (context, storage, variantId, variant) => ({
4571
4520
  images: variant.images ?? []
4572
4521
  });
4573
4522
  const assetFromDraft = (context, storage, draft) => {
4574
- const asset = {
4523
+ return {
4575
4524
  ...draft,
4576
4525
  id: v4(),
4577
4526
  custom: createCustomFields(draft.custom, context.projectKey, storage)
4578
4527
  };
4579
- return asset;
4580
4528
  };
4581
4529
  const priceFromDraft = (context, storage, draft) => ({
4582
4530
  id: v4(),
@@ -4594,10 +4542,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4594
4542
  const { variant, isMasterVariant, variantIndex } = getVariant(data, variantId, sku);
4595
4543
  if (!variant) throw new Error(`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`);
4596
4544
  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
- }
4545
+ 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
4546
  variant.images.push(image);
4602
4547
  if (isMasterVariant) data.masterVariant = variant;
4603
4548
  else data.variants[variantIndex] = variant;
@@ -4649,12 +4594,10 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4649
4594
  assets
4650
4595
  };
4651
4596
  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);
4597
+ const maxId = [dataStaged.masterVariant, ...dataStaged.variants ?? []].reduce((max, element) => element.id > max ? element.id : max, 0);
4654
4598
  const variant = variantFromDraft(context, this._storage, maxId + 1, variantDraft);
4655
4599
  dataStaged.variants.push(variant);
4656
- const onlyStaged = staged !== void 0 ? staged : true;
4657
- if (!onlyStaged) resource.masterData.current.variants.push(variant);
4600
+ if (!(staged !== void 0 ? staged : true)) resource.masterData.current.variants.push(variant);
4658
4601
  checkForStagedChanges(resource);
4659
4602
  return resource;
4660
4603
  }
@@ -4684,8 +4627,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4684
4627
  }
4685
4628
  changePrice(context, resource, { priceId, price, staged }) {
4686
4629
  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));
4630
+ const priceVariant = [data.masterVariant, ...data.variants ?? []].find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4689
4631
  if (!priceVariant) throw new Error(`Price with id ${priceId} not found on product ${resource.id}`);
4690
4632
  const { variant, isMasterVariant, variantIndex } = getVariant(data, priceVariant.id, priceVariant.sku);
4691
4633
  if (!variant) throw new Error(`Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`);
@@ -4740,11 +4682,10 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4740
4682
  const removeCategory = (data) => {
4741
4683
  if (category) {
4742
4684
  const resolvedCategory = getReferenceFromResourceIdentifier(category, context.projectKey, this._storage);
4743
- const foundCategory = data.categories.find((productCategory) => {
4685
+ if (!data.categories.find((productCategory) => {
4744
4686
  if (productCategory.id === resolvedCategory.id) return productCategory;
4745
4687
  return false;
4746
- });
4747
- if (!foundCategory) throw new CommercetoolsError({
4688
+ })) throw new CommercetoolsError({
4748
4689
  code: "InvalidOperation",
4749
4690
  message: `Cannot remove from category '${resolvedCategory.id}' because product '${resource.masterData.current.name}' is not in that category.`
4750
4691
  }, 400);
@@ -4769,8 +4710,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4769
4710
  const { variant, isMasterVariant, variantIndex } = getVariant(data, variantId, sku);
4770
4711
  if (!variant) throw new Error(`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`);
4771
4712
  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.`);
4713
+ if (!variantImages.find((x) => x.url === imageUrl)) throw new Error(`Cannot remove image '${imageUrl}' because product '${resource.id}' does not have that image.`);
4774
4714
  variant.images = variantImages.filter((image) => image.url !== imageUrl);
4775
4715
  if (isMasterVariant) data.masterVariant = variant;
4776
4716
  else data.variants[variantIndex] = variant;
@@ -4783,8 +4723,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4783
4723
  }
4784
4724
  removePrice(context, resource, { priceId, staged }) {
4785
4725
  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));
4726
+ const priceVariant = [data.masterVariant, ...data.variants ?? []].find((variant$1) => variant$1.prices?.some((x) => x.id === priceId));
4788
4727
  if (!priceVariant) throw new Error(`Price with id ${priceId} not found on product ${resource.id}`);
4789
4728
  const { variant, isMasterVariant, variantIndex } = getVariant(data, priceVariant.id, priceVariant.sku);
4790
4729
  if (!variant) throw new Error(`Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`);
@@ -4897,8 +4836,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4897
4836
  return data;
4898
4837
  };
4899
4838
  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);
4839
+ if (!(staged !== void 0 ? staged : true)) resource.masterData.current = updatePriceCustomFields(resource.masterData.current);
4902
4840
  checkForStagedChanges(resource);
4903
4841
  return resource;
4904
4842
  }
@@ -4914,13 +4852,12 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4914
4852
  return data;
4915
4853
  };
4916
4854
  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);
4855
+ if (!(staged !== void 0 ? staged : true)) resource.masterData.current = updatePriceCustomType(resource.masterData.current);
4919
4856
  checkForStagedChanges(resource);
4920
4857
  return resource;
4921
4858
  }
4922
4859
  setTaxCategory(context, resource, { taxCategory }) {
4923
- let taxCategoryReference = void 0;
4860
+ let taxCategoryReference;
4924
4861
  if (taxCategory) taxCategoryReference = getReferenceFromResourceIdentifier(taxCategory, context.projectKey, this._storage);
4925
4862
  else throw new CommercetoolsError({
4926
4863
  code: "InvalidJsonInput",
@@ -4931,7 +4868,7 @@ var ProductUpdateHandler = class extends AbstractUpdateHandler {
4931
4868
  return resource;
4932
4869
  }
4933
4870
  transitionState(context, resource, { state, force }) {
4934
- let productStateReference = void 0;
4871
+ let productStateReference;
4935
4872
  if (state) {
4936
4873
  productStateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
4937
4874
  resource.state = productStateReference;
@@ -4961,7 +4898,7 @@ var ProductRepository = class extends AbstractResourceRepository {
4961
4898
  }
4962
4899
  create(context, draft) {
4963
4900
  if (!draft.masterVariant) throw new Error("Missing master variant");
4964
- let productType = void 0;
4901
+ let productType;
4965
4902
  try {
4966
4903
  productType = getReferenceFromResourceIdentifier(draft.productType, context.projectKey, this._storage);
4967
4904
  } catch (err) {
@@ -4981,9 +4918,9 @@ var ProductRepository = class extends AbstractResourceRepository {
4981
4918
  detailedErrorMessage: "categories: JSON object expected."
4982
4919
  }, 400);
4983
4920
  });
4984
- let taxCategoryReference = void 0;
4921
+ let taxCategoryReference;
4985
4922
  if (draft.taxCategory) taxCategoryReference = getReferenceFromResourceIdentifier(draft.taxCategory, context.projectKey, this._storage);
4986
- let productStateReference = void 0;
4923
+ let productStateReference;
4987
4924
  if (draft.state) productStateReference = getReferenceFromResourceIdentifier(draft.state, context.projectKey, this._storage);
4988
4925
  const productData = {
4989
4926
  name: draft.name,
@@ -5105,12 +5042,17 @@ const haversineDistance = (src, dst) => {
5105
5042
  const dLat = toRadian(dst.latitude - src.latitude);
5106
5043
  const dLon = toRadian(dst.longitude - src.longitude);
5107
5044
  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;
5045
+ return RADIUS_OF_EARTH_IN_KM * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))) * 1e3;
5110
5046
  };
5111
5047
 
5112
5048
  //#endregion
5113
5049
  //#region src/lib/predicateParser.ts
5050
+ /**
5051
+ * This module implements the commercetools query predicate filter expression.
5052
+ * Support should be 100% complete.
5053
+ *
5054
+ * See https://docs.commercetools.com/api/predicates/query
5055
+ */
5114
5056
  var PredicateError = class {
5115
5057
  message;
5116
5058
  constructor(message) {
@@ -5145,7 +5087,7 @@ const resolveValue = (obj, val) => {
5145
5087
  if (val.value === "variants" && obj.masterVariant && obj.variants !== void 0) return [obj.masterVariant, ...obj.variants ?? []];
5146
5088
  if (!(val.value in obj)) {
5147
5089
  if (Array.isArray(obj)) return Object.values(obj).filter((v) => val.value in v).map((v) => v[val.value]);
5148
- return void 0;
5090
+ return;
5149
5091
  }
5150
5092
  return obj[val.value];
5151
5093
  };
@@ -5197,8 +5139,7 @@ const generateMatchFunc = (predicate) => {
5197
5139
  if (Array.isArray(expr)) return [left, ...expr];
5198
5140
  return [left, expr];
5199
5141
  }).nud("(", 100, (t) => {
5200
- const expr = parser.parse({ terminals: [")"] });
5201
- return expr;
5142
+ return parser.parse({ terminals: [")"] });
5202
5143
  }).led("(", 100, ({ left, bp }) => {
5203
5144
  const expr = parser.parse();
5204
5145
  lexer.expect(")");
@@ -5252,33 +5193,25 @@ const generateMatchFunc = (predicate) => {
5252
5193
  return (obj, vars) => resolveValue(obj, left) <= resolveSymbol(expr, vars);
5253
5194
  }).led("IS", 20, ({ left, bp }) => {
5254
5195
  let invert = false;
5255
- const next = lexer.peek();
5256
- if (next.type === "NOT") {
5196
+ if (lexer.peek().type === "NOT") {
5257
5197
  invert = true;
5258
5198
  lexer.next();
5259
5199
  }
5260
- const expr = parser.parse({ terminals: [bp - 1] });
5261
- switch (expr) {
5262
- case "empty": {
5200
+ switch (parser.parse({ terminals: [bp - 1] })) {
5201
+ case "empty":
5263
5202
  if (!invert) return (obj, vars) => {
5264
- const val = resolveValue(obj, left);
5265
- return val.length === 0;
5203
+ return resolveValue(obj, left).length === 0;
5266
5204
  };
5267
5205
  return (obj, vars) => {
5268
- const val = resolveValue(obj, left);
5269
- return val.length !== 0;
5206
+ return resolveValue(obj, left).length !== 0;
5270
5207
  };
5271
- }
5272
- case "defined": {
5208
+ case "defined":
5273
5209
  if (!invert) return (obj, vars) => {
5274
- const val = resolveValue(obj, left);
5275
- return val !== void 0;
5210
+ return resolveValue(obj, left) !== void 0;
5276
5211
  };
5277
5212
  return (obj, vars) => {
5278
- const val = resolveValue(obj, left);
5279
- return val === void 0;
5213
+ return resolveValue(obj, left) === void 0;
5280
5214
  };
5281
- }
5282
5215
  default: throw new Error("Unexpected");
5283
5216
  }
5284
5217
  }).led("IN", 20, ({ left, bp }) => {
@@ -5312,14 +5245,13 @@ const generateMatchFunc = (predicate) => {
5312
5245
  const value = resolveValue(obj, left);
5313
5246
  if (!value) return false;
5314
5247
  const maxDistance = resolveSymbol(expr[2], vars);
5315
- const distance = haversineDistance({
5248
+ return haversineDistance({
5316
5249
  longitude: value[0],
5317
5250
  latitude: value[1]
5318
5251
  }, {
5319
5252
  longitude: resolveSymbol(expr[0], vars),
5320
5253
  latitude: resolveSymbol(expr[1], vars)
5321
- });
5322
- return distance <= maxDistance;
5254
+ }) <= maxDistance;
5323
5255
  };
5324
5256
  }).led("CONTAINS", 20, ({ left, bp }) => {
5325
5257
  const keyword = lexer.next();
@@ -5367,7 +5299,6 @@ var ProductProjectionSearch = class {
5367
5299
  const filters = params.filter.map(parseFilterExpression);
5368
5300
  resources = resources.filter((resource) => filters.every((f) => f(resource, markMatchingVariant)));
5369
5301
  } catch (err) {
5370
- console.error(err);
5371
5302
  throw new CommercetoolsError({
5372
5303
  code: "InvalidInput",
5373
5304
  message: err.message
@@ -5423,7 +5354,7 @@ var ProductProjectionSearch = class {
5423
5354
  getFacets(params, products) {
5424
5355
  if (!params.facet) return {};
5425
5356
  const result = {};
5426
- const regexp = new RegExp(/ counting products$/);
5357
+ const regexp = /* @__PURE__ */ new RegExp(/ counting products$/);
5427
5358
  for (let facet of params.facet) {
5428
5359
  let countProducts = false;
5429
5360
  if (facet.endsWith(" counting products")) {
@@ -5489,36 +5420,34 @@ var ProductProjectionSearch = class {
5489
5420
  };
5490
5421
  }
5491
5422
  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 = {
5423
+ return {
5517
5424
  type: "range",
5518
5425
  dataType: "number",
5519
- ranges: counts
5426
+ ranges: ranges?.map((range) => {
5427
+ if (source.startsWith("variants.")) {
5428
+ const values = [];
5429
+ for (const p of products) for (const v of getVariants(p)) {
5430
+ const val = resolveVariantValue(v, source);
5431
+ if (val === void 0) continue;
5432
+ if (range.match(val)) values.push(val);
5433
+ }
5434
+ const numValues = values.length;
5435
+ return {
5436
+ type: "double",
5437
+ from: range.start || 0,
5438
+ fromStr: range.start !== null ? Number(range.start).toFixed(1) : "",
5439
+ to: range.stop || 0,
5440
+ toStr: range.stop !== null ? Number(range.stop).toFixed(1) : "",
5441
+ count: numValues,
5442
+ total: values.reduce((a, b) => a + b, 0),
5443
+ min: numValues > 0 ? Math.min(...values) : 0,
5444
+ max: numValues > 0 ? Math.max(...values) : 0,
5445
+ mean: numValues > 0 ? mean(values) : 0
5446
+ };
5447
+ }
5448
+ throw new Error("not supported");
5449
+ }) || []
5520
5450
  };
5521
- return data;
5522
5451
  }
5523
5452
  };
5524
5453
  const mean = (arr) => {
@@ -5749,12 +5678,12 @@ var ProjectUpdateHandler = class extends AbstractUpdateHandler {
5749
5678
  changeCustomerSearchStatus(context, resource, { status }) {
5750
5679
  if (!resource.searchIndexing?.customers) throw new Error("Invalid project state");
5751
5680
  resource.searchIndexing.customers.status = status;
5752
- resource.searchIndexing.customers.lastModifiedAt = new Date().toISOString();
5681
+ resource.searchIndexing.customers.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5753
5682
  }
5754
5683
  changeBusinessUnitSearchStatus(context, resource, { status }) {
5755
5684
  if (!resource.searchIndexing?.businessUnits) throw new Error("Invalid project state");
5756
5685
  resource.searchIndexing.businessUnits.status = status;
5757
- resource.searchIndexing.businessUnits.lastModifiedAt = new Date().toISOString();
5686
+ resource.searchIndexing.businessUnits.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5758
5687
  }
5759
5688
  changeLanguages(context, resource, { languages }) {
5760
5689
  resource.languages = languages;
@@ -5773,18 +5702,18 @@ var ProjectUpdateHandler = class extends AbstractUpdateHandler {
5773
5702
  changeOrderSearchStatus(context, resource, { status }) {
5774
5703
  if (!resource.searchIndexing?.orders) throw new Error("Invalid project state");
5775
5704
  resource.searchIndexing.orders.status = status;
5776
- resource.searchIndexing.orders.lastModifiedAt = new Date().toISOString();
5705
+ resource.searchIndexing.orders.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5777
5706
  }
5778
5707
  changeProductSearchIndexingEnabled(context, resource, { enabled, mode }) {
5779
5708
  if (mode === "ProductsSearch") {
5780
5709
  if (!resource.searchIndexing?.productsSearch) throw new Error("Invalid project state");
5781
5710
  resource.searchIndexing.productsSearch.status = enabled ? "Activated" : "Deactivated";
5782
- resource.searchIndexing.productsSearch.lastModifiedAt = new Date().toISOString();
5711
+ resource.searchIndexing.productsSearch.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5783
5712
  return;
5784
5713
  }
5785
5714
  if (!resource.searchIndexing?.products) throw new Error("Invalid project state");
5786
5715
  resource.searchIndexing.products.status = enabled ? "Activated" : "Deactivated";
5787
- resource.searchIndexing.products.lastModifiedAt = new Date().toISOString();
5716
+ resource.searchIndexing.products.lastModifiedAt = (/* @__PURE__ */ new Date()).toISOString();
5788
5717
  }
5789
5718
  setExternalOAuth(context, resource, { externalOAuth }) {
5790
5719
  resource.externalOAuth = externalOAuth;
@@ -5823,7 +5752,7 @@ var QuoteUpdateHandler = class extends AbstractUpdateHandler {
5823
5752
  }
5824
5753
  }
5825
5754
  transitionState(context, resource, { state, force }) {
5826
- let stateReference = void 0;
5755
+ let stateReference;
5827
5756
  if (state) {
5828
5757
  stateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
5829
5758
  resource.state = stateReference;
@@ -5847,7 +5776,7 @@ var QuoteRepository = class extends AbstractResourceRepository {
5847
5776
  const staged = this._storage.getByResourceIdentifier(context.projectKey, draft.stagedQuote);
5848
5777
  const cart = this._storage.getByResourceIdentifier(context.projectKey, staged.quotationCart);
5849
5778
  if (!cart.customerId) throw new Error("Cart does not have a customer");
5850
- const resource = {
5779
+ return {
5851
5780
  ...getBaseResourceProperties(),
5852
5781
  quoteState: "Accepted",
5853
5782
  quoteRequest: staged.quoteRequest,
@@ -5870,7 +5799,6 @@ var QuoteRepository = class extends AbstractResourceRepository {
5870
5799
  billingAddress: cart.billingAddress,
5871
5800
  shippingAddress: cart.shippingAddress
5872
5801
  };
5873
- return resource;
5874
5802
  }
5875
5803
  };
5876
5804
 
@@ -5896,7 +5824,7 @@ var StagedQuoteUpdateHandler = class extends AbstractUpdateHandler {
5896
5824
  }
5897
5825
  }
5898
5826
  transitionState(context, resource, { state, force }) {
5899
- let stateReference = void 0;
5827
+ let stateReference;
5900
5828
  if (state) {
5901
5829
  stateReference = getReferenceFromResourceIdentifier(state, context.projectKey, this._storage);
5902
5830
  resource.state = stateReference;
@@ -5920,7 +5848,7 @@ var StagedQuoteRepository = class extends AbstractResourceRepository {
5920
5848
  const quoteRequest = this._storage.getByResourceIdentifier(context.projectKey, draft.quoteRequest);
5921
5849
  if (!quoteRequest.cart) throw new Error("Cannot find quote request");
5922
5850
  const cart = this._storage.getByResourceIdentifier(context.projectKey, quoteRequest.cart);
5923
- const resource = {
5851
+ return {
5924
5852
  ...getBaseResourceProperties(),
5925
5853
  stagedQuoteState: "InProgress",
5926
5854
  quoteRequest: {
@@ -5932,7 +5860,6 @@ var StagedQuoteRepository = class extends AbstractResourceRepository {
5932
5860
  id: cart.id
5933
5861
  }
5934
5862
  };
5935
- return resource;
5936
5863
  }
5937
5864
  };
5938
5865
 
@@ -6053,8 +5980,7 @@ var RecurringOrderRepository = class extends AbstractResourceRepository {
6053
5980
  }
6054
5981
  create(context, draft) {
6055
5982
  assert(draft.cart, "draft.cart is missing");
6056
- const orderRepo = new OrderRepository(this.config);
6057
- const initialOrder = orderRepo.createFromCart(context, {
5983
+ const initialOrder = new OrderRepository(this.config).createFromCart(context, {
6058
5984
  id: draft.cart.id,
6059
5985
  typeId: "cart"
6060
5986
  });
@@ -6259,7 +6185,7 @@ var ShippingMethodRepository = class extends AbstractResourceRepository {
6259
6185
  }
6260
6186
  matchingCart(context, cartId, params = {}) {
6261
6187
  const cart = this._storage.get(context.projectKey, "cart", cartId);
6262
- if (!cart) return void 0;
6188
+ if (!cart) return;
6263
6189
  return getShippingMethodsMatchingCart(context, this._storage, cart, params);
6264
6190
  }
6265
6191
  _transformZoneRateDraft(context, draft) {
@@ -6288,12 +6214,11 @@ var ShoppingListUpdateHandler = class extends AbstractUpdateHandler {
6288
6214
  let varId = variantId;
6289
6215
  if (sku) varId = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((x) => x.sku === sku)?.id;
6290
6216
  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) => {
6217
+ if (resource.lineItems.some((x) => x.productId === product?.id && x.variantId === varId)) resource.lineItems.forEach((x) => {
6293
6218
  if (x.productId === product?.id && x.variantId === varId) x.quantity += quantity;
6294
6219
  });
6295
6220
  else resource.lineItems.push({
6296
- addedAt: addedAt ? addedAt : new Date().toISOString(),
6221
+ addedAt: addedAt ? addedAt : (/* @__PURE__ */ new Date()).toISOString(),
6297
6222
  id: v4(),
6298
6223
  key,
6299
6224
  productId: product.id,
@@ -6337,8 +6262,7 @@ var ShoppingListUpdateHandler = class extends AbstractUpdateHandler {
6337
6262
  code: "General",
6338
6263
  message: `A line item with ID '${lineItemId}' not found.`
6339
6264
  });
6340
- const shouldDelete = !quantity || quantity >= lineItem.quantity;
6341
- if (shouldDelete) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
6265
+ if (!quantity || quantity >= lineItem.quantity) resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
6342
6266
  else resource.lineItems.forEach((x) => {
6343
6267
  if (x.id === lineItemId && quantity) x.quantity -= quantity;
6344
6268
  });
@@ -6435,17 +6359,14 @@ var ShoppingListRepository = class extends AbstractResourceRepository {
6435
6359
  const items = this._storage.query(projectKey, "product", { where: [`masterData(current(masterVariant(sku="${sku}"))) or masterData(current(variants(sku="${sku}")))`] });
6436
6360
  if (items.count === 0) throw new Error(`Product with sku ${sku} not found`);
6437
6361
  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;
6362
+ lineItem.variantId = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((e) => e.sku === sku)?.id;
6441
6363
  lineItem.productId = product.id;
6442
6364
  return lineItem;
6443
6365
  }
6444
6366
  if (productId) {
6445
6367
  const items = this._storage.query(projectKey, "product", { where: [`id="${productId}"`] });
6446
6368
  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;
6369
+ lineItem.variantId = items.results[0].masterData.current.masterVariant.id;
6449
6370
  return lineItem;
6450
6371
  }
6451
6372
  throw new Error("must provide either sku, productId or variantId for ShoppingListLineItem");
@@ -6610,9 +6531,7 @@ var SubscriptionRepository = class extends AbstractResourceRepository {
6610
6531
  }
6611
6532
  create(context, draft) {
6612
6533
  if (draft.destination.type === "SQS") {
6613
- const queueURL = new URL(draft.destination.queueUrl);
6614
- const accountId = queueURL.pathname.split("/")[1];
6615
- if (accountId === "0000000000") {
6534
+ if (new URL(draft.destination.queueUrl).pathname.split("/")[1] === "0000000000") {
6616
6535
  const dest = draft.destination;
6617
6536
  throw new CommercetoolsError({
6618
6537
  code: "InvalidInput",
@@ -6664,10 +6583,7 @@ var TaxCategoryUpdateHandler = class extends AbstractUpdateHandler {
6664
6583
  replaceTaxRate(context, resource, { taxRateId, taxRate }) {
6665
6584
  if (resource.rates === void 0) resource.rates = [];
6666
6585
  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
- }
6586
+ for (let i = 0; i < resource.rates.length; i++) if (resource.rates[i].id === taxRateId) resource.rates[i] = taxRateObj;
6671
6587
  }
6672
6588
  setDescription(context, resource, { description }) {
6673
6589
  resource.description = description;
@@ -6875,11 +6791,10 @@ const validateData = (data, schema) => {
6875
6791
  schema.parse(data);
6876
6792
  return data;
6877
6793
  } catch (err) {
6878
- const validationError = fromZodError(err);
6879
6794
  throw new CommercetoolsError({
6880
6795
  code: "InvalidJsonInput",
6881
6796
  message: "Request body does not contain valid JSON.",
6882
- detailedErrorMessage: validationError.toString()
6797
+ detailedErrorMessage: fromZodError(err).toString()
6883
6798
  });
6884
6799
  }
6885
6800
  };
@@ -6921,7 +6836,6 @@ var AbstractService = class {
6921
6836
  }
6922
6837
  const result = this.repository.query(getRepositoryContext(request), params);
6923
6838
  response.status(200).send(result);
6924
- return;
6925
6839
  }
6926
6840
  getWithId(request, response) {
6927
6841
  const result = this._expandWithId(request, request.params.id);
@@ -7003,8 +6917,7 @@ var AbstractService = class {
7003
6917
  response.status(200).send(result);
7004
6918
  }
7005
6919
  _expandWithId(request, resourceId) {
7006
- const result = this.repository.get(getRepositoryContext(request), resourceId, { expand: this._parseParam(request.query.expand) });
7007
- return result;
6920
+ return this.repository.get(getRepositoryContext(request), resourceId, { expand: this._parseParam(request.query.expand) });
7008
6921
  }
7009
6922
  _parseParam(value) {
7010
6923
  return queryParamsArray(value);
@@ -7291,8 +7204,7 @@ var CustomerService = class extends AbstractService {
7291
7204
  post(request, response) {
7292
7205
  const draft = request.body;
7293
7206
  const resource = this.repository.create(getRepositoryContext(request), draft);
7294
- const expanded = this._expandWithId(request, resource.id);
7295
- const result = { customer: expanded };
7207
+ const result = { customer: this._expandWithId(request, resource.id) };
7296
7208
  response.status(this.createStatusCode).send(result);
7297
7209
  }
7298
7210
  passwordResetToken(request, response) {
@@ -7602,12 +7514,7 @@ var OrderService = class extends AbstractService {
7602
7514
  }
7603
7515
  getWithOrderNumber(request, response) {
7604
7516
  const orderNumber = request.params.orderNumber;
7605
- const resource = this.repository.getWithOrderNumber(
7606
- getRepositoryContext(request),
7607
- orderNumber,
7608
- // @ts-ignore
7609
- request.query
7610
- );
7517
+ const resource = this.repository.getWithOrderNumber(getRepositoryContext(request), orderNumber, request.query);
7611
7518
  if (resource) {
7612
7519
  response.status(200).send(resource);
7613
7520
  return;
@@ -7845,7 +7752,6 @@ var ShippingMethodService = class extends AbstractService {
7845
7752
  }
7846
7753
  const result = this.repository.matchingCart(getRepositoryContext(request), cartId, { expand: this._parseParam(request.query.expand) });
7847
7754
  response.status(200).send(result);
7848
- return;
7849
7755
  }
7850
7756
  };
7851
7757
 
@@ -8107,44 +8013,44 @@ var InMemoryStorage = class extends AbstractStorage {
8107
8013
  this.addProject(projectKey);
8108
8014
  let projectStorage = this.resources[projectKey];
8109
8015
  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()
8016
+ "associate-role": /* @__PURE__ */ new Map(),
8017
+ "attribute-group": /* @__PURE__ */ new Map(),
8018
+ "business-unit": /* @__PURE__ */ new Map(),
8019
+ cart: /* @__PURE__ */ new Map(),
8020
+ "cart-discount": /* @__PURE__ */ new Map(),
8021
+ category: /* @__PURE__ */ new Map(),
8022
+ channel: /* @__PURE__ */ new Map(),
8023
+ customer: /* @__PURE__ */ new Map(),
8024
+ "customer-group": /* @__PURE__ */ new Map(),
8025
+ "discount-code": /* @__PURE__ */ new Map(),
8026
+ "discount-group": /* @__PURE__ */ new Map(),
8027
+ extension: /* @__PURE__ */ new Map(),
8028
+ "inventory-entry": /* @__PURE__ */ new Map(),
8029
+ "key-value-document": /* @__PURE__ */ new Map(),
8030
+ order: /* @__PURE__ */ new Map(),
8031
+ "order-edit": /* @__PURE__ */ new Map(),
8032
+ payment: /* @__PURE__ */ new Map(),
8033
+ product: /* @__PURE__ */ new Map(),
8034
+ quote: /* @__PURE__ */ new Map(),
8035
+ "quote-request": /* @__PURE__ */ new Map(),
8036
+ "product-discount": /* @__PURE__ */ new Map(),
8037
+ "product-selection": /* @__PURE__ */ new Map(),
8038
+ "product-type": /* @__PURE__ */ new Map(),
8039
+ "product-projection": /* @__PURE__ */ new Map(),
8040
+ "product-tailoring": /* @__PURE__ */ new Map(),
8041
+ "recurrence-policy": /* @__PURE__ */ new Map(),
8042
+ "recurring-order": /* @__PURE__ */ new Map(),
8043
+ review: /* @__PURE__ */ new Map(),
8044
+ "shipping-method": /* @__PURE__ */ new Map(),
8045
+ "staged-quote": /* @__PURE__ */ new Map(),
8046
+ state: /* @__PURE__ */ new Map(),
8047
+ store: /* @__PURE__ */ new Map(),
8048
+ "shopping-list": /* @__PURE__ */ new Map(),
8049
+ "standalone-price": /* @__PURE__ */ new Map(),
8050
+ subscription: /* @__PURE__ */ new Map(),
8051
+ "tax-category": /* @__PURE__ */ new Map(),
8052
+ type: /* @__PURE__ */ new Map(),
8053
+ zone: /* @__PURE__ */ new Map()
8148
8054
  };
8149
8055
  return projectStorage;
8150
8056
  }
@@ -8157,8 +8063,7 @@ var InMemoryStorage = class extends AbstractStorage {
8157
8063
  return [];
8158
8064
  }
8159
8065
  add(projectKey, typeId, obj, params = {}) {
8160
- const store = this.forProjectKey(projectKey);
8161
- store[typeId]?.set(obj.id, obj);
8066
+ this.forProjectKey(projectKey)[typeId]?.set(obj.id, obj);
8162
8067
  const resource = this.get(projectKey, typeId, obj.id, params);
8163
8068
  assert(resource, `resource of type ${typeId} with id ${obj.id} not created`);
8164
8069
  return cloneObject(resource);
@@ -8175,8 +8080,7 @@ var InMemoryStorage = class extends AbstractStorage {
8175
8080
  const store = this.forProjectKey(projectKey);
8176
8081
  const resourceStore = store[typeId];
8177
8082
  if (!store) throw new Error("No type");
8178
- const resources = Array.from(resourceStore.values());
8179
- const resource = resources.find((e) => e.key === key);
8083
+ const resource = Array.from(resourceStore.values()).find((e) => e.key === key);
8180
8084
  if (resource) {
8181
8085
  const clone = cloneObject(resource);
8182
8086
  return this.expand(projectKey, clone, params.expand);
@@ -8192,8 +8096,7 @@ var InMemoryStorage = class extends AbstractStorage {
8192
8096
  return resource;
8193
8097
  }
8194
8098
  query(projectKey, typeId, params) {
8195
- const store = this.forProjectKey(projectKey)[typeId];
8196
- if (!store) throw new Error("No type");
8099
+ if (!this.forProjectKey(projectKey)[typeId]) throw new Error("No type");
8197
8100
  let resources = this.all(projectKey, typeId);
8198
8101
  if (params.where) {
8199
8102
  const vars = Object.fromEntries(Object.entries(params).filter(([key]) => key.startsWith("var.")).map(([key, value]) => [key.slice(4), value]));
@@ -8288,8 +8191,7 @@ var InMemoryStorage = class extends AbstractStorage {
8288
8191
  id: lineItem.productId
8289
8192
  });
8290
8193
  if (!product) return;
8291
- const variant = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((e) => e.id === lineItem.variantId);
8292
- lineItem.variant = variant;
8194
+ lineItem.variant = [product.masterData.current.masterVariant, ...product.masterData.current.variants].find((e) => e.id === lineItem.variantId);
8293
8195
  }
8294
8196
  };
8295
8197
 
@@ -8353,17 +8255,14 @@ var CommercetoolsMock = class {
8353
8255
  return this._oauth2.store;
8354
8256
  }
8355
8257
  runServer(port = 3e3, options) {
8356
- const server = this.app.listen(port, () => {
8357
- console.info(`Mock server listening at http://localhost:${port}`);
8358
- });
8258
+ const server = this.app.listen(port, () => {});
8359
8259
  server.keepAliveTimeout = 60 * 1e3;
8360
8260
  }
8361
8261
  createApp(options) {
8362
- const config = {
8262
+ this._repositories = createRepositories({
8363
8263
  strict: this.options.strict,
8364
8264
  storage: this._storage
8365
- };
8366
- this._repositories = createRepositories(config);
8265
+ });
8367
8266
  this._oauth2.setCustomerRepository(this._repositories.customer);
8368
8267
  const app = express();
8369
8268
  app.use(express.json({ limit: "16mb" }));
@@ -8396,9 +8295,7 @@ var CommercetoolsMock = class {
8396
8295
  });
8397
8296
  return;
8398
8297
  }
8399
- console.error(err);
8400
8298
  resp.status(500).send({ error: err.message });
8401
- return;
8402
8299
  });
8403
8300
  return app;
8404
8301
  }
@@ -8426,9 +8323,8 @@ var CommercetoolsMock = class {
8426
8323
  const res = await inject(app).get(`${url.pathname}?${url.searchParams.toString()}`).body(body).headers(headers).end();
8427
8324
  if (res.statusCode === 200) {
8428
8325
  const parsedBody = JSON.parse(res.body);
8429
- const resultCount = "count" in parsedBody ? parsedBody.count : Object.keys(parsedBody).length;
8430
8326
  return new HttpResponse(null, {
8431
- status: resultCount > 0 ? 200 : 404,
8327
+ status: ("count" in parsedBody ? parsedBody.count : Object.keys(parsedBody).length) > 0 ? 200 : 404,
8432
8328
  headers: mapHeaderType(res.headers)
8433
8329
  });
8434
8330
  }
@@ -8476,13 +8372,13 @@ var CommercetoolsMock = class {
8476
8372
  if (_globalListeners.length > 0) {
8477
8373
  if (this._mswServer !== void 0) throw new Error("Server already started");
8478
8374
  process.emitWarning("Server wasn't stopped properly, clearing");
8479
- _globalListeners.forEach((listener) => listener.close());
8375
+ for (const listener of _globalListeners) listener.close();
8376
+ _globalListeners.length = 0;
8480
8377
  }
8481
8378
  const server = setupServer();
8482
8379
  this.registerHandlers(server);
8483
8380
  server.listen({ onUnhandledRequest: (request, print) => {
8484
- const url = new URL(request.url);
8485
- if (url.hostname === "127.0.0.1") return;
8381
+ if (new URL(request.url).hostname === "127.0.0.1") return;
8486
8382
  print.error();
8487
8383
  } });
8488
8384
  _globalListeners.push(server);
@@ -8492,4 +8388,4 @@ var CommercetoolsMock = class {
8492
8388
 
8493
8389
  //#endregion
8494
8390
  export { CommercetoolsMock, getBaseResourceProperties };
8495
- //# sourceMappingURL=index.js.map
8391
+ //# sourceMappingURL=index.mjs.map