@thorprovider/adapters 5.0.10 → 5.0.12

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 (37) hide show
  1. package/AGENTS.md +1 -1
  2. package/dist/index.d.mts +376 -16
  3. package/dist/index.d.ts +376 -16
  4. package/dist/index.js +1687 -528
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +1680 -530
  7. package/dist/index.mjs.map +1 -1
  8. package/package.json +3 -2
  9. package/src/core/errors.ts +31 -0
  10. package/src/factory/index.ts +16 -6
  11. package/src/factory/provider-types.test.ts +32 -0
  12. package/src/factory/provider-types.ts +176 -0
  13. package/src/index.ts +6 -4
  14. package/src/providers/index.ts +1 -1
  15. package/src/providers/medusa/auth.test.ts +148 -25
  16. package/src/providers/medusa/auth.ts +129 -16
  17. package/src/providers/medusa/available-filters.test.ts +280 -0
  18. package/src/providers/medusa/catalog-facet-support.test.ts +715 -0
  19. package/src/providers/medusa/catalog-query.test.ts +422 -0
  20. package/src/providers/medusa/catalog-sort.test.ts +175 -0
  21. package/src/providers/medusa/customer-orders.test.ts +142 -0
  22. package/src/providers/medusa/index.test.ts +480 -0
  23. package/src/providers/medusa/index.ts +1592 -538
  24. package/src/providers/medusa/live-smoke.test.ts +68 -0
  25. package/src/providers/medusa/transforms.test.ts +222 -0
  26. package/src/providers/medusa/transforms.ts +152 -66
  27. package/src/providers/mock/catalog-query.test.ts +491 -0
  28. package/src/providers/mock/index.test.ts +66 -0
  29. package/src/providers/mock/index.ts +43 -1
  30. package/src/providers/mock/mock.ts +513 -3
  31. package/src/types/completion.ts +57 -0
  32. package/src/types/index.ts +7 -0
  33. package/.turbo/turbo-build.log +0 -18
  34. package/.turbo/turbo-test.log +0 -372
  35. package/.turbo/turbo-type-check.log +0 -0
  36. package/dist/.tsbuildinfo +0 -1
  37. package/publish.log +0 -93
package/dist/index.mjs CHANGED
@@ -1,8 +1,3 @@
1
- // src/index.ts
2
- import {
3
- StorefrontConfigError as StorefrontConfigError2
4
- } from "@thorprovider/types";
5
-
6
1
  // src/types/capabilities.types.ts
7
2
  var MOCK_CAPABILITIES = {
8
3
  updateProfile: false,
@@ -366,6 +361,16 @@ var ConfigurationError = class extends CommerceError {
366
361
  this.name = "ConfigurationError";
367
362
  }
368
363
  };
364
+ var StorefrontConfigError = class extends Error {
365
+ platformType;
366
+ requiredEnvVar;
367
+ constructor(message, platformType, requiredEnvVar) {
368
+ super(message);
369
+ this.name = "StorefrontConfigError";
370
+ this.platformType = platformType;
371
+ this.requiredEnvVar = requiredEnvVar;
372
+ }
373
+ };
369
374
  var ResourceNotFoundError = class extends CommerceError {
370
375
  constructor(resource, identifier) {
371
376
  super(`${resource} not found: ${identifier}`, "RESOURCE_NOT_FOUND", 404);
@@ -900,6 +905,16 @@ function transformMoney(amount, currencyCode = "USD") {
900
905
  currencyCode: currencyCode.toUpperCase()
901
906
  };
902
907
  }
908
+ function transformAmount(amount, currencyCode) {
909
+ const currencyCodeUpper = (currencyCode ?? "").toUpperCase();
910
+ if (typeof amount !== "number" || !Number.isFinite(amount)) {
911
+ return { amount: "", currencyCode: currencyCodeUpper };
912
+ }
913
+ return { amount: amount.toFixed(2), currencyCode: currencyCodeUpper };
914
+ }
915
+ function transformProductPrice(amount, currencyCode) {
916
+ return transformAmount(amount, currencyCode);
917
+ }
903
918
  function transformImage(url, alt = "") {
904
919
  return {
905
920
  url,
@@ -951,39 +966,42 @@ function transformProductOption(option) {
951
966
  values: option.values?.map((v) => v.value ?? "") ?? []
952
967
  };
953
968
  }
954
- function transformProductVariant(variant, currencyCode = "USD") {
969
+ function transformProductVariant(variant, currencyCode) {
955
970
  let priceAmount;
956
971
  let priceCurrency = currencyCode;
957
972
  if (variant.calculated_price) {
958
973
  priceAmount = variant.calculated_price.calculated_amount;
959
- priceCurrency = variant.calculated_price.currency_code || currencyCode;
974
+ priceCurrency = variant.calculated_price.currency_code ?? currencyCode;
960
975
  } else if (variant.prices && variant.prices.length > 0) {
961
- const price = variant.prices.find((p) => p.currency_code === currencyCode.toLowerCase());
976
+ const target = currencyCode?.toLowerCase();
977
+ const price = (target ? variant.prices.find((p) => p.currency_code === target) : void 0) ?? variant.prices[0];
962
978
  priceAmount = price?.amount;
963
- priceCurrency = price?.currency_code || currencyCode;
979
+ priceCurrency = price?.currency_code ?? currencyCode;
964
980
  }
965
981
  const isAvailable = variant.manage_inventory === false ? true : (variant.inventory_quantity ?? 0) > 0 || variant.allow_backorder === true;
966
982
  return {
967
983
  id: variant.id,
968
984
  title: variant.title ?? "Default",
985
+ // SKU is optional descriptive data only — never API/purchase identity.
969
986
  sku: variant.sku ?? void 0,
970
987
  availableForSale: isAvailable,
971
988
  selectedOptions: variant.options?.map((opt) => ({
972
989
  name: opt.option?.title ?? "",
973
990
  value: opt.value ?? ""
974
991
  })) ?? [],
975
- price: transformMoney(priceAmount, priceCurrency),
992
+ price: transformProductPrice(priceAmount, priceCurrency),
976
993
  compareAtPrice: void 0,
977
994
  // Medusa doesn't have compare-at pricing
978
995
  quantityAvailable: variant.manage_inventory ? variant.inventory_quantity : void 0,
979
996
  image: variant.thumbnail ? transformImage(variant.thumbnail, variant.title ?? "") : void 0
980
997
  };
981
998
  }
982
- function transformProduct(product, currencyCode = "USD") {
999
+ function transformProduct(product, currencyCode) {
983
1000
  const variants = product.variants?.map((v) => transformProductVariant(v, currencyCode)) ?? [];
984
- const prices = variants.map((v) => parseFloat(v.price.amount));
985
- const minPrice = Math.min(...prices);
986
- const maxPrice = Math.max(...prices);
1001
+ const validPrices = variants.map((v) => v.price).filter((money) => money.amount !== "" && Number.isFinite(Number(money.amount))).map((money) => Number(money.amount));
1002
+ const rangeCurrency = variants.find((v) => v.price.currencyCode)?.price.currencyCode ?? (currencyCode ?? "").toUpperCase();
1003
+ const minPrice = validPrices.length > 0 ? Math.min(...validPrices) : void 0;
1004
+ const maxPrice = validPrices.length > 0 ? Math.max(...validPrices) : void 0;
987
1005
  return {
988
1006
  id: product.id,
989
1007
  handle: product.handle ?? "",
@@ -999,16 +1017,28 @@ function transformProduct(product, currencyCode = "USD") {
999
1017
  images: product.images?.map((img) => transformImage(img.url ?? "", product.title ?? "")) ?? [],
1000
1018
  priceRange: {
1001
1019
  // Build Money directly from already-resolved major-unit prices.
1002
- // Do NOT pass through transformMoney (which would call toFixed on already-correct values)
1003
- // and do NOT multiply by 100 (that was a compensatory hack for the old /100 bug).
1004
- minVariantPrice: { amount: (Number.isFinite(minPrice) ? minPrice : 0).toFixed(2), currencyCode: currencyCode.toUpperCase() },
1005
- maxVariantPrice: { amount: (Number.isFinite(maxPrice) ? maxPrice : 0).toFixed(2), currencyCode: currencyCode.toUpperCase() }
1020
+ // Do NOT multiply by 100 (that was a compensatory hack for the old /100
1021
+ // bug) and do NOT fabricate a zero for an unresolved price.
1022
+ minVariantPrice: {
1023
+ amount: minPrice !== void 0 ? minPrice.toFixed(2) : "",
1024
+ currencyCode: rangeCurrency
1025
+ },
1026
+ maxVariantPrice: {
1027
+ amount: maxPrice !== void 0 ? maxPrice.toFixed(2) : "",
1028
+ currencyCode: rangeCurrency
1029
+ }
1006
1030
  },
1007
1031
  collections: product.collection ? [{
1008
1032
  id: product.collection.id,
1009
1033
  title: product.collection.title ?? "",
1010
1034
  handle: product.collection.handle ?? ""
1011
1035
  }] : void 0,
1036
+ categories: product.categories?.map((category) => ({
1037
+ id: category.id,
1038
+ name: category.name ?? "",
1039
+ handle: category.handle ?? "",
1040
+ parentCategoryId: category.parent_category_id ?? void 0
1041
+ })),
1012
1042
  productType: product.type?.value ?? void 0,
1013
1043
  vendor: void 0,
1014
1044
  // Medusa doesn't have vendor field
@@ -1025,38 +1055,19 @@ function transformProduct(product, currencyCode = "USD") {
1025
1055
  function resolveMedusaCartItemCurrencyCode(item, cartCurrencyCode) {
1026
1056
  return item?.cart?.currency_code ?? cartCurrencyCode ?? "usd";
1027
1057
  }
1028
- function resolveMedusaCartItemTotal(item) {
1029
- const quantity = item?.quantity ?? 1;
1030
- const safeQuantity = typeof quantity === "number" && quantity > 0 ? quantity : 1;
1031
- const totalCandidates = [
1032
- item?.total,
1033
- item?.item_total,
1034
- item?.original_total,
1035
- item?.subtotal,
1036
- item?.item_subtotal,
1037
- item?.original_subtotal
1038
- ];
1039
- for (const candidate of totalCandidates) {
1040
- if (typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0) {
1058
+ function resolveAuthoritativeLineTotal(item) {
1059
+ const candidates = [item?.total, item?.item_total, item?.subtotal];
1060
+ for (const candidate of candidates) {
1061
+ if (typeof candidate === "number" && Number.isFinite(candidate)) {
1041
1062
  return candidate;
1042
1063
  }
1043
1064
  }
1044
- const unitCandidates = [
1045
- item?.unit_price,
1046
- item?.original_unit_price
1047
- ];
1048
- for (const candidate of unitCandidates) {
1049
- if (typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0) {
1050
- return candidate * safeQuantity;
1051
- }
1052
- }
1053
- return 0;
1065
+ return void 0;
1054
1066
  }
1055
1067
  function transformCartItem(item, cartCurrencyCode) {
1056
1068
  const variant = item.variant;
1057
1069
  const product = variant?.product;
1058
1070
  const currencyCode = resolveMedusaCartItemCurrencyCode(item, cartCurrencyCode);
1059
- const totalCents = resolveMedusaCartItemTotal(item);
1060
1071
  const merchandiseId = variant?.id ?? item.variant_id ?? "";
1061
1072
  const merchandiseTitle = variant?.title ?? item.variant_title ?? "";
1062
1073
  const productId = product?.id ?? item.product_id ?? "";
@@ -1067,7 +1078,9 @@ function transformCartItem(item, cartCurrencyCode) {
1067
1078
  id: item.id,
1068
1079
  quantity: item.quantity ?? 1,
1069
1080
  cost: {
1070
- totalAmount: transformMoney(totalCents, currencyCode)
1081
+ totalAmount: transformAmount(resolveAuthoritativeLineTotal(item), currencyCode),
1082
+ // Backend unit price, carried so the display never derives it locally.
1083
+ unitPrice: transformAmount(item?.unit_price, currencyCode)
1071
1084
  },
1072
1085
  merchandise: {
1073
1086
  id: merchandiseId,
@@ -1086,19 +1099,30 @@ function transformCartItem(item, cartCurrencyCode) {
1086
1099
  };
1087
1100
  }
1088
1101
  function transformCart(cart) {
1089
- const currencyCode = cart.currency_code ?? "usd";
1102
+ const currencyCode = cart.currency_code;
1090
1103
  return {
1091
1104
  id: cart.id,
1092
1105
  checkoutUrl: `/checkout/${cart.id}`,
1093
1106
  // Medusa doesn't have a direct checkout URL
1094
1107
  cost: {
1095
- subtotalAmount: transformMoney(cart.subtotal, currencyCode),
1096
- totalAmount: transformMoney(cart.total, currencyCode),
1097
- totalTaxAmount: transformMoney(cart.tax_total, currencyCode)
1108
+ subtotalAmount: transformAmount(
1109
+ typeof cart.item_subtotal === "number" ? cart.item_subtotal : cart.subtotal,
1110
+ currencyCode
1111
+ ),
1112
+ discountAmount: transformAmount(cart.discount_total, currencyCode),
1113
+ totalTaxAmount: transformAmount(cart.tax_total, currencyCode),
1114
+ shippingAmount: transformAmount(cart.shipping_total, currencyCode),
1115
+ totalAmount: transformAmount(cart.total, currencyCode)
1098
1116
  },
1099
1117
  lines: cart.items?.map((item) => transformCartItem(item, currencyCode)) ?? [],
1100
1118
  totalQuantity: cart.items?.reduce((sum, item) => sum + (item.quantity ?? 0), 0) ?? 0,
1101
- completedAt: cart.completed_at ? typeof cart.completed_at === "string" ? cart.completed_at : cart.completed_at?.toISOString() : void 0
1119
+ salesChannelId: cart.sales_channel_id ?? void 0,
1120
+ regionId: cart.region_id ?? void 0,
1121
+ currencyCode: typeof currencyCode === "string" ? currencyCode.toUpperCase() : void 0,
1122
+ selectedShippingMethodId: cart.shipping_methods?.[0]?.id ?? void 0,
1123
+ selectedShippingOptionId: cart.shipping_methods?.[0]?.shipping_option_id ?? void 0,
1124
+ completedAt: cart.completed_at ? typeof cart.completed_at === "string" ? cart.completed_at : cart.completed_at?.toISOString() : void 0,
1125
+ metadata: cart.metadata ?? void 0
1102
1126
  };
1103
1127
  }
1104
1128
  function transformCollection(collection) {
@@ -1187,8 +1211,8 @@ function transformOrderItem(item, currencyCode) {
1187
1211
  title: item.product_title ?? item.title ?? "",
1188
1212
  variantTitle: item.variant_title ?? variant?.title ?? void 0,
1189
1213
  quantity: item.quantity ?? 1,
1190
- price: transformMoney(item.unit_price, currencyCode),
1191
- total: transformMoney(item.total, currencyCode),
1214
+ price: transformAmount(item.unit_price, currencyCode),
1215
+ total: transformAmount(item.total, currencyCode),
1192
1216
  sku: variant?.sku ?? void 0,
1193
1217
  image: product?.thumbnail || item.thumbnail ? transformImage(product?.thumbnail || item.thumbnail, item.product_title ?? "") : void 0,
1194
1218
  productId: item.product_id ?? product?.id ?? void 0,
@@ -1239,12 +1263,19 @@ function transformOrder(order) {
1239
1263
  customer: order.customer ? transformCustomer(order.customer, order.email) : void 0,
1240
1264
  // Items
1241
1265
  items: (order.items ?? []).filter((item) => item != null).map((item) => transformOrderItem(item, currencyCode)) ?? [],
1242
- // Pricing
1243
- subtotal: transformMoney(order.subtotal, currencyCode),
1244
- total: transformMoney(order.total, currencyCode),
1245
- tax: transformMoney(order.tax_total, currencyCode),
1246
- shipping: transformMoney(order.shipping_total, currencyCode),
1247
- discount: transformMoney(order.discount_total, currencyCode),
1266
+ // Pricing — backend-authoritative; a legitimate zero is preserved and no
1267
+ // amount is derived locally. `subtotal` prefers the backend's
1268
+ // `item_subtotal` (lines only, excluding shipping/tax); Medusa's native
1269
+ // `subtotal` folds in `shipping_subtotal`, so falling back to it is only
1270
+ // for installs that do not supply `item_subtotal`.
1271
+ subtotal: transformAmount(
1272
+ typeof order.item_subtotal === "number" ? order.item_subtotal : order.subtotal,
1273
+ currencyCode
1274
+ ),
1275
+ total: transformAmount(order.total, currencyCode),
1276
+ tax: transformAmount(order.tax_total, currencyCode),
1277
+ shipping: transformAmount(order.shipping_total, currencyCode),
1278
+ discount: transformAmount(order.discount_total, currencyCode),
1248
1279
  // Addresses (transformed to camelCase)
1249
1280
  shippingAddress: order.shipping_address ? transformAddress(order.shipping_address) : void 0,
1250
1281
  billingAddress: order.billing_address ? transformAddress(order.billing_address) : void 0,
@@ -1663,7 +1694,6 @@ function assertEntityBelongsToChannel(entity, expectedChannelId) {
1663
1694
 
1664
1695
  // src/providers/medusa/index.ts
1665
1696
  import Medusa2 from "@medusajs/js-sdk";
1666
- import { StorefrontConfigError } from "@thorprovider/types";
1667
1697
 
1668
1698
  // src/providers/medusa/auth.ts
1669
1699
  var AuthStorageManager = class {
@@ -1781,6 +1811,7 @@ var MedusaAuthProvider = class {
1781
1811
  if (this.authConfig.method === "jwt") {
1782
1812
  await this.storageManager.setToken(token);
1783
1813
  }
1814
+ await this.linkCustomerChannel();
1784
1815
  const customer = await this.getCurrentCustomer();
1785
1816
  this.logger.info("Login successful", { customerId: customer?.id });
1786
1817
  return {
@@ -1788,6 +1819,7 @@ var MedusaAuthProvider = class {
1788
1819
  customer: customer ?? void 0
1789
1820
  };
1790
1821
  } catch (error) {
1822
+ if (error instanceof ProviderAPIError) throw error;
1791
1823
  this.logger.error("Login failed", error);
1792
1824
  throw new ProviderAPIError(
1793
1825
  `Authentication failed: ${error.message}`,
@@ -1799,16 +1831,14 @@ var MedusaAuthProvider = class {
1799
1831
  async register(data) {
1800
1832
  this.logger.debug("register", { email: data.email });
1801
1833
  try {
1802
- await this.sdk.auth.register("customer", "emailpass", {
1834
+ const registrationToken = await this.sdk.auth.register("customer", "emailpass", {
1803
1835
  email: data.email,
1804
1836
  password: data.password
1805
1837
  });
1806
- const { customer } = await this.sdk.store.customer.create({
1807
- email: data.email,
1808
- first_name: data.first_name,
1809
- last_name: data.last_name,
1810
- phone: data.phone
1811
- });
1838
+ if (this.authConfig.method === "jwt" && typeof registrationToken === "string") {
1839
+ await this.storageManager.setToken(registrationToken);
1840
+ }
1841
+ const linked = await this.createChannelLinkedCustomer(data);
1812
1842
  const loginResult = await this.sdk.auth.login("customer", "emailpass", {
1813
1843
  email: data.email,
1814
1844
  password: data.password
@@ -1834,12 +1864,20 @@ var MedusaAuthProvider = class {
1834
1864
  if (this.authConfig.method === "jwt") {
1835
1865
  await this.storageManager.setToken(token);
1836
1866
  }
1867
+ const customer = await this.getCurrentCustomer();
1868
+ if (!customer || customer.id !== linked.id) {
1869
+ throw new ProviderAPIError(
1870
+ "Registration created an auth identity without a linked customer.",
1871
+ "CUSTOMER_LINK_INCOMPLETE"
1872
+ );
1873
+ }
1837
1874
  this.logger.info("Registration successful", { customerId: customer.id });
1838
1875
  return {
1839
1876
  token: this.authConfig.method === "jwt" ? token : void 0,
1840
- customer: transformCustomer(customer, customer.email)
1877
+ customer
1841
1878
  };
1842
1879
  } catch (error) {
1880
+ if (error instanceof ProviderAPIError) throw error;
1843
1881
  this.logger.error("Registration failed", error);
1844
1882
  throw new ProviderAPIError(
1845
1883
  `Registration failed: ${error.message}`,
@@ -1848,6 +1886,79 @@ var MedusaAuthProvider = class {
1848
1886
  );
1849
1887
  }
1850
1888
  }
1889
+ /**
1890
+ * Create and channel-link a customer through `POST /store/thor/customers`.
1891
+ *
1892
+ * The request carries the registration token (read by the SDK from the
1893
+ * request-scoped custom storage) and the publishable key; the backend links
1894
+ * the customer to the publishable-key sales channel. A route that is
1895
+ * unavailable fails closed with a typed error — there is no silent native
1896
+ * fallback that would leave the customer unlinked.
1897
+ */
1898
+ async createChannelLinkedCustomer(data) {
1899
+ const response = await this.fetchChannelAccountRoute(
1900
+ "/store/thor/customers",
1901
+ {
1902
+ method: "POST",
1903
+ body: {
1904
+ email: data.email,
1905
+ first_name: data.first_name,
1906
+ last_name: data.last_name,
1907
+ phone: data.phone
1908
+ }
1909
+ }
1910
+ );
1911
+ const id = response?.customer?.id;
1912
+ if (typeof id !== "string" || id.length === 0) {
1913
+ throw new ProviderAPIError(
1914
+ "Channel-linked customer creation returned no customer id.",
1915
+ "CUSTOMER_LINK_INCOMPLETE"
1916
+ );
1917
+ }
1918
+ return { id };
1919
+ }
1920
+ /**
1921
+ * Link the authenticated customer to the publishable-key sales channel
1922
+ * through `POST /store/thor/customers/me/channels` (idempotent). Called after
1923
+ * login so history is channel-scoped for the current storefront.
1924
+ */
1925
+ async linkCustomerChannel() {
1926
+ const response = await this.fetchChannelAccountRoute("/store/thor/customers/me/channels", { method: "POST" });
1927
+ if (response?.linked === false && response?.reason !== "already_linked") {
1928
+ throw new ProviderAPIError(
1929
+ "Customer channel link did not complete.",
1930
+ "CUSTOMER_LINK_INCOMPLETE"
1931
+ );
1932
+ }
1933
+ }
1934
+ /**
1935
+ * Call a Thor channel account route through the SDK client, which attaches
1936
+ * the request-scoped customer/registration token and the publishable key. A
1937
+ * missing client or an unavailable route (404/405/501) fails closed with a
1938
+ * typed `CUSTOMER_LINK_UNAVAILABLE` error.
1939
+ */
1940
+ async fetchChannelAccountRoute(path, init) {
1941
+ const client = this.sdk.client;
1942
+ if (!client || typeof client.fetch !== "function") {
1943
+ throw new ProviderAPIError(
1944
+ `The channel account route ${path} is unavailable in this SDK.`,
1945
+ "CUSTOMER_LINK_UNAVAILABLE"
1946
+ );
1947
+ }
1948
+ try {
1949
+ return await client.fetch(path, init);
1950
+ } catch (error) {
1951
+ const status = error?.status || error?.statusCode;
1952
+ if (status === 404 || status === 405 || status === 501) {
1953
+ throw new ProviderAPIError(
1954
+ `The channel account route ${path} is unavailable (status ${status}).`,
1955
+ "CUSTOMER_LINK_UNAVAILABLE",
1956
+ status
1957
+ );
1958
+ }
1959
+ throw error;
1960
+ }
1961
+ }
1851
1962
  async logout() {
1852
1963
  this.logger.debug("logout");
1853
1964
  try {
@@ -2193,10 +2304,164 @@ async function getPaymentMethods(sdk, options) {
2193
2304
  }
2194
2305
 
2195
2306
  // src/providers/medusa/index.ts
2196
- var MEDUSA_CART_RETRIEVE_FIELDS = "+items,+items.variant,+items.variant.product,+items.variant.product.thumbnail,+items.variant.options,+items.variant.options.option";
2307
+ var MEDUSA_CART_RETRIEVE_FIELDS = "+items,+items.variant,+items.variant.product,+items.variant.product.thumbnail,+items.variant.options,+items.variant.options.option,+items.total,+items.unit_price,+items.item_subtotal,+items.item_total,+shipping_methods,+shipping_methods.id,+shipping_methods.shipping_option_id";
2308
+ var CUSTOMER_ORDERS_DEFAULT_PAGE_SIZE = 10;
2309
+ var CUSTOMER_ORDERS_MAX_PAGE_SIZE = 100;
2310
+ function normalizeCustomerOrdersPage(options) {
2311
+ const page = Number.isInteger(options.page) && options.page > 0 ? options.page : 1;
2312
+ const requested = Number.isInteger(options.pageSize) && options.pageSize > 0 ? options.pageSize : CUSTOMER_ORDERS_DEFAULT_PAGE_SIZE;
2313
+ const pageSize = Math.min(requested, CUSTOMER_ORDERS_MAX_PAGE_SIZE);
2314
+ return { page, pageSize, limit: pageSize, offset: (page - 1) * pageSize };
2315
+ }
2316
+ var MEDUSA_ORDER_COMPLETION_FIELDS = "*items";
2317
+ var DEFAULT_CATALOG_PAGE_SIZE = 50;
2318
+ function resolveCatalogPageSize(configured) {
2319
+ const fromEnv = process.env.MEDUSA_CATALOG_PAGE_SIZE !== void 0 ? Number(process.env.MEDUSA_CATALOG_PAGE_SIZE) : void 0;
2320
+ const raw = configured ?? fromEnv;
2321
+ if (raw === void 0 || !Number.isFinite(raw) || raw < 1) {
2322
+ return DEFAULT_CATALOG_PAGE_SIZE;
2323
+ }
2324
+ return Math.floor(raw);
2325
+ }
2326
+ function resolveConfiguredSalesChannelId() {
2327
+ return process.env.MEDUSA_SALES_CHANNEL_ID ?? process.env.NEXT_PUBLIC_SALES_CHANNEL_ID;
2328
+ }
2329
+ var MEDUSA_SORT_KEY_MAP = {
2330
+ featured: null,
2331
+ name: "title",
2332
+ newest: "-created_at",
2333
+ "price-asc": null,
2334
+ "price-desc": null,
2335
+ rating: null
2336
+ };
2337
+ function resolveEffectiveCategoryHandles(query) {
2338
+ const { categoryScope, categories } = query;
2339
+ if (categoryScope === void 0) return categories;
2340
+ if (categories === void 0) return [categoryScope];
2341
+ return categories.filter((handle) => handle === categoryScope);
2342
+ }
2343
+ function buildAppliedCatalogFilters(query, effectiveCategoryHandles, includeAdvanced = false) {
2344
+ return {
2345
+ ...query.text ? { text: query.text } : {},
2346
+ ...effectiveCategoryHandles !== void 0 ? { categories: effectiveCategoryHandles } : {},
2347
+ ...query.collections !== void 0 ? { collections: query.collections } : {},
2348
+ ...includeAdvanced && query.priceMin !== void 0 ? { priceMin: query.priceMin } : {},
2349
+ ...includeAdvanced && query.priceMax !== void 0 ? { priceMax: query.priceMax } : {},
2350
+ ...includeAdvanced && query.inStock !== void 0 ? { inStock: query.inStock } : {},
2351
+ ...includeAdvanced && query.attributes !== void 0 ? { attributes: query.attributes } : {}
2352
+ };
2353
+ }
2354
+ function buildBasicDemonstratedQuery(query) {
2355
+ return {
2356
+ ...query.text !== void 0 ? { text: query.text } : {},
2357
+ ...query.categoryScope !== void 0 ? { categoryScope: query.categoryScope } : {},
2358
+ ...query.categories !== void 0 ? { categories: query.categories } : {},
2359
+ ...query.collections !== void 0 ? { collections: query.collections } : {}
2360
+ };
2361
+ }
2362
+ var ADVANCED_SEARCH_ENDPOINT = "/store/search";
2363
+ var BASIC_LISTING_ENDPOINT = "/store/products";
2364
+ function collectRequestedAdvancedFields(query) {
2365
+ const fields = [];
2366
+ if (query.priceMin !== void 0) fields.push("priceMin");
2367
+ if (query.priceMax !== void 0) fields.push("priceMax");
2368
+ if (query.inStock !== void 0) fields.push("inStock");
2369
+ for (const name of Object.keys(query.attributes ?? {})) {
2370
+ fields.push(`attr.${name}`);
2371
+ }
2372
+ return fields;
2373
+ }
2374
+ function advancedFieldToFacet(field) {
2375
+ if (field === "priceMin" || field === "priceMax") return "price";
2376
+ return field;
2377
+ }
2378
+ function collectAdvancedSearchRequestFields(options) {
2379
+ const fields = [];
2380
+ if (options?.priceMin !== void 0) fields.push("priceMin");
2381
+ if (options?.priceMax !== void 0) fields.push("priceMax");
2382
+ if (options?.inStockOnly === true) fields.push("inStock");
2383
+ if (options?.attributes && options.attributes.length > 0) {
2384
+ fields.push("attributes");
2385
+ }
2386
+ return fields;
2387
+ }
2388
+ function toFiniteNumber(value) {
2389
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2390
+ if (typeof value === "string" && value.trim() !== "") {
2391
+ const parsed = Number(value);
2392
+ return Number.isFinite(parsed) ? parsed : void 0;
2393
+ }
2394
+ return void 0;
2395
+ }
2396
+ function readAppliedPriceRange(applied) {
2397
+ const range = applied.price_range;
2398
+ if (!range || typeof range !== "object" || Array.isArray(range)) return {};
2399
+ const record = range;
2400
+ return { min: toFiniteNumber(record.min), max: toFiniteNumber(record.max) };
2401
+ }
2402
+ function mapAppliedFiltersToFacets(applied) {
2403
+ const facets = /* @__PURE__ */ new Set();
2404
+ const priceRange = readAppliedPriceRange(applied);
2405
+ const hasAppliedPriceRange = priceRange.min !== void 0 && priceRange.max !== void 0;
2406
+ if (hasAppliedPriceRange || "price" in applied || "price_min" in applied || "price_max" in applied) {
2407
+ facets.add("price");
2408
+ }
2409
+ if (typeof applied.is_available === "boolean" || "inStock" in applied || "isAvailable" in applied || "available" in applied) {
2410
+ facets.add("inStock");
2411
+ }
2412
+ const attributes = applied.attributes;
2413
+ if (attributes && typeof attributes === "object" && !Array.isArray(attributes)) {
2414
+ for (const name of Object.keys(attributes)) {
2415
+ facets.add(`attr.${name}`);
2416
+ }
2417
+ }
2418
+ return facets;
2419
+ }
2420
+ function collectUnappliedAdvancedFields(applied, query) {
2421
+ const unapplied = [];
2422
+ const priceRange = readAppliedPriceRange(applied);
2423
+ if (query.priceMin !== void 0) {
2424
+ const echoed = toFiniteNumber(
2425
+ priceRange.min ?? applied.price_min ?? applied.priceMin
2426
+ );
2427
+ if (echoed !== query.priceMin) unapplied.push("priceMin");
2428
+ }
2429
+ if (query.priceMax !== void 0) {
2430
+ const echoed = toFiniteNumber(
2431
+ priceRange.max ?? applied.price_max ?? applied.priceMax
2432
+ );
2433
+ if (echoed !== query.priceMax) unapplied.push("priceMax");
2434
+ }
2435
+ if (query.inStock === true) {
2436
+ const echoed = applied.is_available ?? applied.isAvailable ?? applied.inStock ?? applied.available;
2437
+ if (echoed !== true && echoed !== "true") unapplied.push("inStock");
2438
+ }
2439
+ const requestedAttributes = query.attributes ?? {};
2440
+ const appliedAttributes = applied.attributes;
2441
+ for (const name of Object.keys(requestedAttributes)) {
2442
+ const hasName = !!appliedAttributes && typeof appliedAttributes === "object" && !Array.isArray(appliedAttributes) && name in appliedAttributes;
2443
+ if (!hasName) unapplied.push(`attr.${name}`);
2444
+ }
2445
+ return unapplied;
2446
+ }
2447
+ function readFiniteFacetNumber(value) {
2448
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2449
+ }
2197
2450
  var MedusaProvider = class {
2198
2451
  name = "medusa";
2199
2452
  version = "2.0.0";
2453
+ /**
2454
+ * Canonical catalog sort keys this provider applies at the query level.
2455
+ *
2456
+ * Advertises only the backend-verified orderings (E2 Decision 6). `price-asc`,
2457
+ * `price-desc`, and `rating` are intentionally absent: they are not applied at
2458
+ * the query level, so the listing never offers them as global sorts.
2459
+ *
2460
+ * The literal tuple is assignable to `CommerceProvider['supportedCatalogSortKeys']`
2461
+ * (`readonly CatalogSortKey[]`); it is written structurally here so the adapter
2462
+ * compiles against the published `@thorprovider/types` declaration.
2463
+ */
2464
+ supportedCatalogSortKeys = ["featured", "name", "newest"];
2200
2465
  /**
2201
2466
  * Medusa backend capabilities.
2202
2467
  * Starts with static defaults, replaced by dynamic values from
@@ -2218,6 +2483,14 @@ var MedusaProvider = class {
2218
2483
  baseUrl;
2219
2484
  publishableKey;
2220
2485
  regionId;
2486
+ /** Configured per-request catalog listing bound (never an unbounded scan). */
2487
+ catalogPageSize;
2488
+ /**
2489
+ * Per-scope cache of the truthful facet-support descriptor. The optional
2490
+ * advanced endpoint is probed once per demonstrated scope/query rather than on
2491
+ * every listing request (E2 task 2.4).
2492
+ */
2493
+ facetSupportCache = /* @__PURE__ */ new Map();
2221
2494
  /** Secret API key for admin operations (if configured). */
2222
2495
  adminApiKey;
2223
2496
  /**
@@ -2262,6 +2535,7 @@ var MedusaProvider = class {
2262
2535
  this.baseUrl = config.baseUrl;
2263
2536
  this.publishableKey = config.publishableKey;
2264
2537
  this.regionId = config.regionId;
2538
+ this.catalogPageSize = resolveCatalogPageSize(config.catalogPageSize);
2265
2539
  this.retryConfig = {
2266
2540
  maxRetries: config.retry?.maxRetries ?? 3,
2267
2541
  timeoutMs: config.retry?.timeoutMs ?? 1e4,
@@ -2283,7 +2557,16 @@ var MedusaProvider = class {
2283
2557
  debug: config.debug ?? false,
2284
2558
  // Always use JWT mode for auth - SDK needs to send Bearer tokens
2285
2559
  // Configure storage method for JWT tokens (browser only)
2286
- auth: config.auth ? {
2560
+ auth: config.auth ? config.auth.customStorage ? {
2561
+ type: "jwt",
2562
+ // Request-scoped custom storage: the caller supplies a per-request
2563
+ // token holder (for example a server request's customer JWT). The
2564
+ // SDK reads the token on every request and writes the login /
2565
+ // registration token back into the same holder, so a fresh
2566
+ // provider per request is authenticated without shared state.
2567
+ jwtTokenStorageMethod: "custom",
2568
+ storage: config.auth.customStorage
2569
+ } : {
2287
2570
  type: "jwt",
2288
2571
  // Use localStorage in browser, memory storage on server
2289
2572
  jwtTokenStorageMethod: typeof window !== "undefined" ? "local" : "memory"
@@ -2391,35 +2674,52 @@ var MedusaProvider = class {
2391
2674
  }
2392
2675
  throw lastError;
2393
2676
  }
2677
+ /** Fields needed to price a product variant for the current region. */
2678
+ buildProductFields(regionId) {
2679
+ const baseFields = "+variants,+variants.inventory_quantity,+options,+images,+tags,+categories.*";
2680
+ const pricingFields = ",+variants.calculated_price,+variants.prices";
2681
+ return regionId ? baseFields + pricingFields : baseFields;
2682
+ }
2683
+ /** Scope a store query to the configured storefront sales channel, if any. */
2684
+ applySalesChannelScope(queryParams) {
2685
+ const salesChannelId = process.env.NEXT_PUBLIC_SALES_CHANNEL_ID;
2686
+ if (salesChannelId) {
2687
+ queryParams.sales_channel_id = [salesChannelId];
2688
+ }
2689
+ }
2690
+ /**
2691
+ * Directed single-product lookup by a supported native filter (`handle` or
2692
+ * `id`). This is independent of catalog listing pagination, so a known
2693
+ * product beyond the first listing page still resolves without scanning.
2694
+ *
2695
+ * Medusa's store API supports `handle` and `id` on `/store/products`; it
2696
+ * does not expose a variant filter there, so a variant is resolved from the
2697
+ * product once the product is known (see `getProductDetailByHandle` in the
2698
+ * runtime). No `limit` beyond 1 is issued.
2699
+ */
2700
+ async fetchSingleProduct(filter, options) {
2701
+ const regionId = options?.regionId ?? this.regionId;
2702
+ const queryParams = {
2703
+ ...filter,
2704
+ limit: 1,
2705
+ fields: this.buildProductFields(regionId)
2706
+ };
2707
+ if (regionId) {
2708
+ queryParams.region_id = regionId;
2709
+ }
2710
+ this.applySalesChannelScope(queryParams);
2711
+ const { products } = await this.sdk.store.product.list(queryParams);
2712
+ if (!products || products.length === 0) {
2713
+ this.logger.debug("Product not found", filter);
2714
+ return void 0;
2715
+ }
2716
+ return transformProduct(products[0], this.currencyCode);
2717
+ }
2394
2718
  async getProduct(handle, options) {
2395
2719
  this.logger.debug("getProduct", { handle, regionId: options?.regionId });
2396
2720
  try {
2397
2721
  return await this.withRetry(
2398
- async () => {
2399
- const regionId = options?.regionId ?? this.regionId;
2400
- const baseFields = "+variants,+variants.inventory_quantity,+options,+images,+tags";
2401
- const pricingFields = ",+variants.calculated_price,+variants.prices";
2402
- const fields = regionId ? baseFields + pricingFields : baseFields;
2403
- const queryParams = {
2404
- handle,
2405
- limit: 1,
2406
- fields
2407
- };
2408
- if (regionId) {
2409
- queryParams.region_id = regionId;
2410
- }
2411
- const salesChannelId = process.env.NEXT_PUBLIC_SALES_CHANNEL_ID;
2412
- if (salesChannelId) {
2413
- queryParams.sales_channel_id = [salesChannelId];
2414
- }
2415
- const { products } = await this.sdk.store.product.list(queryParams);
2416
- if (!products || products.length === 0) {
2417
- this.logger.debug("Product not found", { handle });
2418
- return void 0;
2419
- }
2420
- const transformedProduct = transformProduct(products[0], this.currencyCode);
2421
- return transformedProduct;
2422
- },
2722
+ () => this.fetchSingleProduct({ handle }, options),
2423
2723
  "getProduct",
2424
2724
  { handle, regionId: options?.regionId }
2425
2725
  );
@@ -2431,6 +2731,26 @@ var MedusaProvider = class {
2431
2731
  );
2432
2732
  }
2433
2733
  }
2734
+ /**
2735
+ * Directed product lookup by backend product ID. Independent of the first
2736
+ * listing page, mirroring `getProduct` for handle-based resolution.
2737
+ */
2738
+ async getProductById(id, options) {
2739
+ this.logger.debug("getProductById", { id, regionId: options?.regionId });
2740
+ try {
2741
+ return await this.withRetry(
2742
+ () => this.fetchSingleProduct({ id }, options),
2743
+ "getProductById",
2744
+ { id, regionId: options?.regionId }
2745
+ );
2746
+ } catch (error) {
2747
+ throw new ProviderAPIError(
2748
+ `Failed to fetch product by id: ${error.message}`,
2749
+ "medusa",
2750
+ error.status
2751
+ );
2752
+ }
2753
+ }
2434
2754
  async getProducts(options = {}) {
2435
2755
  this.logger.debug("getProducts", options);
2436
2756
  try {
@@ -2440,28 +2760,14 @@ var MedusaProvider = class {
2440
2760
  const baseFields = "+variants,+variants.inventory_quantity,+options,+images,+tags";
2441
2761
  const pricingFields = ",+variants.calculated_price,+variants.prices";
2442
2762
  const fields = regionId ? baseFields + pricingFields : baseFields;
2443
- const SORT_KEY_MAP = {
2444
- featured: null,
2445
- // server default order
2446
- name: "title",
2447
- // A→Z by product title
2448
- newest: "-created_at",
2449
- // newest products first
2450
- "price-asc": null,
2451
- // not supported by native endpoint → client-side
2452
- "price-desc": null,
2453
- // not supported by native endpoint → client-side
2454
- rating: null
2455
- // not supported → server default
2456
- };
2457
2763
  const queryParams = {
2458
2764
  q: options.query,
2459
- limit: options.first ?? 100,
2460
- offset: options.after ? parseInt(String(options.after), 10) : void 0,
2765
+ limit: options.first ?? this.catalogPageSize,
2766
+ offset: options.after !== void 0 ? parseInt(String(options.after), 10) : options.skip,
2461
2767
  fields
2462
2768
  };
2463
2769
  if (options.sortKey) {
2464
- const mappedOrder = SORT_KEY_MAP[options.sortKey] ?? null;
2770
+ const mappedOrder = MEDUSA_SORT_KEY_MAP[options.sortKey] ?? null;
2465
2771
  if (mappedOrder !== null) {
2466
2772
  queryParams.order = mappedOrder;
2467
2773
  }
@@ -2501,6 +2807,468 @@ var MedusaProvider = class {
2501
2807
  );
2502
2808
  }
2503
2809
  }
2810
+ /**
2811
+ * Canonical catalog query path (E2 task 2.2).
2812
+ *
2813
+ * Accepts a validated `CatalogQuery`, translates it into Medusa Store
2814
+ * `/store/products` parameters, and returns a truthful `CatalogQueryOutcome`.
2815
+ * The route category scope is always retained and intersected with the
2816
+ * `categories` filter; `categories`/`collections` handles are resolved to
2817
+ * backend IDs through the existing directed lookups (`getCategory`/
2818
+ * `getCollection`). Any requested filter this provider cannot apply
2819
+ * (price/`inStock`/attributes) is rejected as a typed `unsupported-query`
2820
+ * outcome naming the fields — never a partial success and never a silent
2821
+ * drop. Pagination is `offset = (page - 1) * pageSize`, defaulting to the
2822
+ * canonical page size.
2823
+ *
2824
+ * Legacy `getProducts`/`getCategoryProducts` are unchanged; this additive
2825
+ * method is the typed seam the runtime query bridge (E2 task 3.1) consumes.
2826
+ */
2827
+ async getCatalogProducts(query) {
2828
+ this.logger.debug("getCatalogProducts", query);
2829
+ if (query.sort !== void 0 && !this.supportedCatalogSortKeys.includes(query.sort)) {
2830
+ return this.unsupportedCatalogOutcome(["sort"]);
2831
+ }
2832
+ const effectiveCategoryHandles = resolveEffectiveCategoryHandles(query);
2833
+ try {
2834
+ const categoryIds = effectiveCategoryHandles !== void 0 ? await this.resolveCategoryIds(effectiveCategoryHandles) : void 0;
2835
+ const collectionIds = query.collections ? await this.resolveCollectionIds(query.collections) : void 0;
2836
+ const facetSupport = await this.getCatalogFacetSupport({
2837
+ query,
2838
+ categoryIds,
2839
+ collectionIds,
2840
+ scope: query.categoryScope
2841
+ });
2842
+ const requestedAdvanced = collectRequestedAdvancedFields(query);
2843
+ const heldAdvanced = requestedAdvanced.filter(
2844
+ (field) => !facetSupport.offered.includes(advancedFieldToFacet(field))
2845
+ );
2846
+ if (heldAdvanced.length > 0) {
2847
+ return this.unsupportedCatalogOutcome(heldAdvanced);
2848
+ }
2849
+ const emptyIntersection = effectiveCategoryHandles !== void 0 && effectiveCategoryHandles.length === 0;
2850
+ const categoryFilterEmpty = effectiveCategoryHandles !== void 0 && (categoryIds?.length ?? 0) === 0;
2851
+ const collectionFilterEmpty = query.collections !== void 0 && (collectionIds?.length ?? 0) === 0;
2852
+ if (emptyIntersection || categoryFilterEmpty || collectionFilterEmpty) {
2853
+ return {
2854
+ ok: true,
2855
+ results: {
2856
+ products: [],
2857
+ appliedFilters: buildAppliedCatalogFilters(
2858
+ query,
2859
+ effectiveCategoryHandles,
2860
+ requestedAdvanced.length > 0
2861
+ ),
2862
+ facetSupport
2863
+ }
2864
+ };
2865
+ }
2866
+ if (requestedAdvanced.length > 0) {
2867
+ return this.queryAdvancedCatalog(
2868
+ query,
2869
+ categoryIds,
2870
+ collectionIds,
2871
+ facetSupport
2872
+ );
2873
+ }
2874
+ return await this.queryBasicCatalog(
2875
+ query,
2876
+ effectiveCategoryHandles,
2877
+ categoryIds,
2878
+ collectionIds,
2879
+ facetSupport
2880
+ );
2881
+ } catch (error) {
2882
+ this.logger.error("getCatalogProducts error details", {
2883
+ message: error.message,
2884
+ status: error.status
2885
+ });
2886
+ throw new ProviderAPIError(
2887
+ `Failed to run catalog query: ${error.message || "Unknown error"}`,
2888
+ "medusa",
2889
+ error.status
2890
+ );
2891
+ }
2892
+ }
2893
+ /**
2894
+ * Execute a basic-only canonical query against the equivalent basic endpoint
2895
+ * `/store/products`, reporting the filters it actually applied.
2896
+ */
2897
+ async queryBasicCatalog(query, effectiveCategoryHandles, categoryIds, collectionIds, facetSupport) {
2898
+ const pageSize = query.pageSize ?? this.catalogPageSize;
2899
+ const page = query.page ?? 1;
2900
+ const regionId = this.regionId;
2901
+ const baseFields = "+variants,+variants.inventory_quantity,+options,+images,+thumbnail,+tags";
2902
+ const pricingFields = ",+variants.calculated_price,+variants.prices";
2903
+ const queryParams = {
2904
+ limit: pageSize,
2905
+ offset: (page - 1) * pageSize,
2906
+ fields: regionId ? baseFields + pricingFields : baseFields
2907
+ };
2908
+ if (query.text) {
2909
+ queryParams.q = query.text;
2910
+ }
2911
+ if (categoryIds && categoryIds.length > 0) {
2912
+ queryParams.category_id = categoryIds;
2913
+ }
2914
+ if (collectionIds && collectionIds.length > 0) {
2915
+ queryParams.collection_id = collectionIds;
2916
+ }
2917
+ if (query.sort) {
2918
+ const mappedOrder = MEDUSA_SORT_KEY_MAP[query.sort] ?? null;
2919
+ if (mappedOrder !== null) {
2920
+ queryParams.order = mappedOrder;
2921
+ }
2922
+ }
2923
+ if (regionId) {
2924
+ queryParams.region_id = regionId;
2925
+ }
2926
+ const salesChannelId = process.env.NEXT_PUBLIC_SALES_CHANNEL_ID;
2927
+ if (salesChannelId) {
2928
+ queryParams.sales_channel_id = [salesChannelId];
2929
+ }
2930
+ const response = await this.sdk.store.product.list(queryParams);
2931
+ const products = (response.products ?? []).map(
2932
+ (p) => transformProduct(p, this.currencyCode)
2933
+ );
2934
+ const count = response.count;
2935
+ return {
2936
+ ok: true,
2937
+ results: {
2938
+ products,
2939
+ // Total is only the backend's actual count; never manufactured.
2940
+ ...typeof count === "number" ? { total: count } : {},
2941
+ appliedFilters: buildAppliedCatalogFilters(
2942
+ query,
2943
+ effectiveCategoryHandles
2944
+ ),
2945
+ facetSupport
2946
+ }
2947
+ };
2948
+ }
2949
+ /**
2950
+ * Execute an advanced canonical query against the real optional endpoint
2951
+ * `/store/search`, then re-validate that the response applied every requested
2952
+ * filter. A response that does not confirm a requested field, or an endpoint
2953
+ * failure, yields a typed `unsupported-query` error — never a partial result
2954
+ * labelled success and never a silent fallback to the basic endpoint.
2955
+ */
2956
+ async queryAdvancedCatalog(query, categoryIds, collectionIds, facetSupport) {
2957
+ const pageSize = query.pageSize ?? this.catalogPageSize;
2958
+ const page = query.page ?? 1;
2959
+ const advancedQuery = this.buildAdvancedSearchQuery(
2960
+ query,
2961
+ categoryIds ?? [],
2962
+ collectionIds ?? []
2963
+ );
2964
+ advancedQuery.limit = pageSize;
2965
+ advancedQuery.offset = (page - 1) * pageSize;
2966
+ let data;
2967
+ try {
2968
+ data = await this.sdk.client.fetch(ADVANCED_SEARCH_ENDPOINT, {
2969
+ query: advancedQuery
2970
+ });
2971
+ } catch (error) {
2972
+ this.logger.error("Advanced catalog listing failed", {
2973
+ message: error?.message,
2974
+ status: error?.status
2975
+ });
2976
+ return this.unsupportedCatalogOutcome(
2977
+ collectRequestedAdvancedFields(query)
2978
+ );
2979
+ }
2980
+ const appliedRaw = data?.applied_filters ?? data?.appliedFilters;
2981
+ if (!appliedRaw || typeof appliedRaw !== "object") {
2982
+ this.logger.warn("Advanced endpoint did not echo applied filters", {
2983
+ endpoint: ADVANCED_SEARCH_ENDPOINT
2984
+ });
2985
+ return this.unsupportedCatalogOutcome(
2986
+ collectRequestedAdvancedFields(query)
2987
+ );
2988
+ }
2989
+ const unapplied = collectUnappliedAdvancedFields(
2990
+ appliedRaw,
2991
+ query
2992
+ );
2993
+ if (unapplied.length > 0) {
2994
+ this.logger.warn("Advanced endpoint did not apply requested filters", {
2995
+ endpoint: ADVANCED_SEARCH_ENDPOINT,
2996
+ fields: unapplied
2997
+ });
2998
+ return this.unsupportedCatalogOutcome(unapplied);
2999
+ }
3000
+ const products = (data.hits ?? []).map(
3001
+ (hit) => transformProduct(hit, this.currencyCode)
3002
+ );
3003
+ const total = typeof data.estimatedTotalHits === "number" ? data.estimatedTotalHits : typeof data.count === "number" ? data.count : void 0;
3004
+ return {
3005
+ ok: true,
3006
+ results: {
3007
+ products,
3008
+ ...total !== void 0 ? { total } : {},
3009
+ appliedFilters: buildAppliedCatalogFilters(
3010
+ query,
3011
+ resolveEffectiveCategoryHandles(query),
3012
+ true
3013
+ ),
3014
+ facetSupport
3015
+ }
3016
+ };
3017
+ }
3018
+ /** Resolve category handles to Medusa category IDs via directed lookups. */
3019
+ async resolveCategoryIds(handles) {
3020
+ const ids = [];
3021
+ for (const handle of handles) {
3022
+ const category = await this.getCategory(handle);
3023
+ if (category) ids.push(category.id);
3024
+ }
3025
+ return ids;
3026
+ }
3027
+ /** Resolve collection handles to Medusa collection IDs via directed lookups. */
3028
+ async resolveCollectionIds(handles) {
3029
+ const ids = [];
3030
+ for (const handle of handles) {
3031
+ const collection = await this.getCollection(handle);
3032
+ if (collection) ids.push(collection.id);
3033
+ }
3034
+ return ids;
3035
+ }
3036
+ /**
3037
+ * Truthful facet-support descriptor for a scope (E2 task 2.4).
3038
+ *
3039
+ * Basic facets (`categories`, `collections`) are always offered: they are
3040
+ * applied by the canonical basic endpoint `/store/products`, and the
3041
+ * descriptor records that endpoint with the applied query and scope as their
3042
+ * demonstration source.
3043
+ *
3044
+ * Optional advanced facets (`price`, `inStock`, and advertised `attr.<name>`)
3045
+ * are offered only when the real optional `/store/search` endpoint has been
3046
+ * demonstrated with the applied query for the current scope AND the response
3047
+ * echoes the filter as applied. Otherwise they are held with the real probe
3048
+ * status/reason — a capability boolean or returned facet metadata is never
3049
+ * accepted as proof (E2 Decisions 4–5; spec "Backend support is proven against
3050
+ * the real endpoint, not assumed").
3051
+ *
3052
+ * The descriptor carries no counts or ranges and no invented timestamp; every
3053
+ * offered facet has an actual `{ endpoint, appliedQuery, scope }` source.
3054
+ */
3055
+ async getCatalogFacetSupport(options = {}) {
3056
+ const query = options.query ?? {};
3057
+ const scope = options.scope ?? query.categoryScope;
3058
+ const key = JSON.stringify({
3059
+ scope: scope ?? null,
3060
+ categoryIds: options.categoryIds ?? null,
3061
+ collectionIds: options.collectionIds ?? null,
3062
+ categories: query.categories ?? null,
3063
+ text: query.text ?? null,
3064
+ collections: query.collections ?? null,
3065
+ priceMin: query.priceMin ?? null,
3066
+ priceMax: query.priceMax ?? null,
3067
+ inStock: query.inStock ?? null,
3068
+ attributes: query.attributes ?? null
3069
+ });
3070
+ const cached = this.facetSupportCache.get(key);
3071
+ if (cached) return cached;
3072
+ const pending = this.resolveCatalogFacetSupport(
3073
+ query,
3074
+ options.categoryIds,
3075
+ options.collectionIds,
3076
+ scope
3077
+ );
3078
+ this.facetSupportCache.set(key, pending);
3079
+ return pending;
3080
+ }
3081
+ async resolveCatalogFacetSupport(query, providedCategoryIds, providedCollectionIds, scope) {
3082
+ const advancedDemonstratedQuery = {
3083
+ ...query.text !== void 0 ? { text: query.text } : {},
3084
+ ...query.categoryScope !== void 0 ? { categoryScope: query.categoryScope } : {},
3085
+ ...query.categories !== void 0 ? { categories: query.categories } : {},
3086
+ ...query.collections !== void 0 ? { collections: query.collections } : {},
3087
+ ...query.priceMin !== void 0 ? { priceMin: query.priceMin } : {},
3088
+ ...query.priceMax !== void 0 ? { priceMax: query.priceMax } : {},
3089
+ ...query.inStock !== void 0 ? { inStock: query.inStock } : {},
3090
+ ...query.attributes !== void 0 ? { attributes: query.attributes } : {}
3091
+ };
3092
+ const basicDemonstratedQuery = buildBasicDemonstratedQuery(query);
3093
+ const scopeField = scope !== void 0 ? { scope } : {};
3094
+ const offered = ["categories", "collections"];
3095
+ const demonstrations = {
3096
+ categories: {
3097
+ endpoint: BASIC_LISTING_ENDPOINT,
3098
+ appliedQuery: basicDemonstratedQuery,
3099
+ ...scopeField
3100
+ },
3101
+ collections: {
3102
+ endpoint: BASIC_LISTING_ENDPOINT,
3103
+ appliedQuery: basicDemonstratedQuery,
3104
+ ...scopeField
3105
+ }
3106
+ };
3107
+ const held = [];
3108
+ const heldReasons = {};
3109
+ const categoryIds = providedCategoryIds ?? await this.resolveScopeCategoryIds(query);
3110
+ const collectionIds = providedCollectionIds ?? (query.collections ? await this.resolveCollectionIds(query.collections) : []);
3111
+ const candidates = ["price", "inStock"];
3112
+ for (const handle of await this.resolveFilterableAttributeHandles(
3113
+ categoryIds
3114
+ )) {
3115
+ const facet = `attr.${handle}`;
3116
+ if (!candidates.includes(facet)) candidates.push(facet);
3117
+ }
3118
+ const probe = await this.probeAdvancedSearchSupport(
3119
+ query,
3120
+ categoryIds,
3121
+ collectionIds
3122
+ );
3123
+ if (probe.available) {
3124
+ for (const facet of candidates) {
3125
+ if (probe.applied.has(facet)) {
3126
+ offered.push(facet);
3127
+ demonstrations[facet] = {
3128
+ endpoint: ADVANCED_SEARCH_ENDPOINT,
3129
+ appliedQuery: advancedDemonstratedQuery,
3130
+ ...scopeField
3131
+ };
3132
+ } else {
3133
+ held.push(facet);
3134
+ heldReasons[facet] = `not echoed as applied by ${ADVANCED_SEARCH_ENDPOINT}`;
3135
+ }
3136
+ }
3137
+ } else {
3138
+ for (const facet of candidates) {
3139
+ held.push(facet);
3140
+ heldReasons[facet] = probe.reason;
3141
+ }
3142
+ }
3143
+ return {
3144
+ offered,
3145
+ held,
3146
+ demonstrations,
3147
+ ...Object.keys(heldReasons).length > 0 ? { heldReasons } : {}
3148
+ };
3149
+ }
3150
+ /**
3151
+ * Demonstrate the optional advanced endpoint with the applied query for the
3152
+ * current scope. A non-2xx response (including the HTTP 404/500 an absent
3153
+ * plugin returns), an unparseable body, or a response that does not echo the
3154
+ * applied filters all mean the facet is not demonstrated — never a silent
3155
+ * assumption of support. Uses a single SDK request (no retry): a support probe
3156
+ * must not amplify a broken optional endpoint into repeated requests.
3157
+ */
3158
+ async probeAdvancedSearchSupport(query, categoryIds, collectionIds) {
3159
+ const advancedQuery = this.buildAdvancedSearchQuery(
3160
+ query,
3161
+ categoryIds,
3162
+ collectionIds
3163
+ );
3164
+ advancedQuery.limit = 1;
3165
+ try {
3166
+ const data = await this.sdk.client.fetch(ADVANCED_SEARCH_ENDPOINT, {
3167
+ query: advancedQuery
3168
+ });
3169
+ const appliedRaw = data?.applied_filters ?? data?.appliedFilters;
3170
+ if (!appliedRaw || typeof appliedRaw !== "object") {
3171
+ return {
3172
+ available: false,
3173
+ applied: /* @__PURE__ */ new Set(),
3174
+ reason: `${ADVANCED_SEARCH_ENDPOINT} did not echo applied filters; support unverified`
3175
+ };
3176
+ }
3177
+ return {
3178
+ available: true,
3179
+ applied: mapAppliedFiltersToFacets(
3180
+ appliedRaw
3181
+ ),
3182
+ reason: `${ADVANCED_SEARCH_ENDPOINT} demonstrated with the applied query`
3183
+ };
3184
+ } catch (error) {
3185
+ const status = typeof error?.status === "number" ? error.status : void 0;
3186
+ this.logger.warn("Optional advanced search endpoint not demonstrated", {
3187
+ endpoint: ADVANCED_SEARCH_ENDPOINT,
3188
+ status,
3189
+ message: error?.message
3190
+ });
3191
+ return {
3192
+ available: false,
3193
+ applied: /* @__PURE__ */ new Set(),
3194
+ reason: status !== void 0 ? `${ADVANCED_SEARCH_ENDPOINT} returned ${status}; optional advanced endpoint not demonstrated` : `${ADVANCED_SEARCH_ENDPOINT} unavailable: ${extractErrorMessage(error)}`,
3195
+ ...status !== void 0 ? { status } : {}
3196
+ };
3197
+ }
3198
+ }
3199
+ /**
3200
+ * Build the advanced-endpoint query parameters from the canonical query. The
3201
+ * SDK serializes the plain object, so no manual stringification is needed.
3202
+ */
3203
+ buildAdvancedSearchQuery(query, categoryIds, collectionIds) {
3204
+ const advancedQuery = {};
3205
+ if (query.text) advancedQuery.q = query.text;
3206
+ if (categoryIds.length > 0) advancedQuery.categories = categoryIds.join(",");
3207
+ if (collectionIds.length > 0) {
3208
+ advancedQuery.collections = collectionIds.join(",");
3209
+ }
3210
+ if (query.priceMin !== void 0) advancedQuery.price_min = query.priceMin;
3211
+ if (query.priceMax !== void 0) advancedQuery.price_max = query.priceMax;
3212
+ if (query.inStock === true) advancedQuery.isAvailable = true;
3213
+ if (query.attributes) {
3214
+ const attributes = Object.entries(query.attributes).map(([id, values]) => ({
3215
+ id,
3216
+ values
3217
+ }));
3218
+ advancedQuery.attributes = JSON.stringify(attributes);
3219
+ }
3220
+ if (query.sort) {
3221
+ const mappedOrder = MEDUSA_SORT_KEY_MAP[query.sort] ?? null;
3222
+ if (mappedOrder !== null) advancedQuery.order = mappedOrder;
3223
+ }
3224
+ if (this.regionId) advancedQuery.region_id = this.regionId;
3225
+ if (this.currencyCode) {
3226
+ advancedQuery.currency_code = this.currencyCode.toLowerCase();
3227
+ }
3228
+ return advancedQuery;
3229
+ }
3230
+ /** Resolve the effective category scope of a query to backend IDs. */
3231
+ async resolveScopeCategoryIds(query) {
3232
+ const handles = resolveEffectiveCategoryHandles(query);
3233
+ if (handles === void 0 || handles.length === 0) return [];
3234
+ return this.resolveCategoryIds(handles);
3235
+ }
3236
+ /**
3237
+ * Advertised filterable attribute handles for the scope. The custom-attributes
3238
+ * endpoint is facet *metadata* (which attributes exist), not proof that a
3239
+ * filter can be applied; these handles are candidates only, and each still
3240
+ * requires the advanced endpoint to echo it as applied before it is offered.
3241
+ */
3242
+ async resolveFilterableAttributeHandles(categoryIds) {
3243
+ const handles = [];
3244
+ for (const categoryId of categoryIds) {
3245
+ try {
3246
+ const data = await this.sdk.client.fetch(
3247
+ `/store/custom-attributes/category/${categoryId}`
3248
+ );
3249
+ for (const item of data?.attributes ?? []) {
3250
+ const attr = item.attribute ?? item;
3251
+ if (attr?.is_filterable && attr?.is_active && typeof attr.handle === "string" && attr.handle.length > 0) {
3252
+ handles.push(attr.handle);
3253
+ }
3254
+ }
3255
+ } catch {
3256
+ }
3257
+ }
3258
+ return handles;
3259
+ }
3260
+ /** Build a typed `unsupported-query` outcome naming the offending fields. */
3261
+ unsupportedCatalogOutcome(fields) {
3262
+ return {
3263
+ ok: false,
3264
+ error: {
3265
+ code: "unsupported-query",
3266
+ fields,
3267
+ message: `Unsupported catalog query: ${fields.join(", ")}`,
3268
+ repair: { remove: fields }
3269
+ }
3270
+ };
3271
+ }
2504
3272
  async getProductRecommendations(productId) {
2505
3273
  this.logger.debug("getProductRecommendations", { productId });
2506
3274
  this.logger.warn("Product recommendations not yet implemented for Medusa");
@@ -2522,16 +3290,8 @@ var MedusaProvider = class {
2522
3290
  async searchProductsAdvanced(options) {
2523
3291
  this.logger.debug("searchProductsAdvanced", options);
2524
3292
  if (!this.capabilities.advancedSearch) {
2525
- this.logger.warn("Advanced search not available, falling back to getProducts()");
2526
- const products = await this.getProducts(options);
2527
- return {
2528
- products,
2529
- meta: {
2530
- limit: options?.first ?? 20,
2531
- offset: Number(options?.after ?? 0),
2532
- hybridSearchUsed: false
2533
- }
2534
- };
3293
+ this.logger.warn("Advanced search capability disabled, using faithful fallback");
3294
+ return this.fallbackAdvancedSearch(options);
2535
3295
  }
2536
3296
  try {
2537
3297
  const queryParams = {};
@@ -2631,20 +3391,39 @@ var MedusaProvider = class {
2631
3391
  });
2632
3392
  return { products, meta };
2633
3393
  } catch (error) {
2634
- this.logger.error("Advanced search failed, falling back to getProducts()", {
3394
+ this.logger.error("Advanced search failed, using faithful fallback", {
2635
3395
  error: error.message,
2636
3396
  stack: error.stack
2637
3397
  });
2638
- const products = await this.getProducts(options);
2639
- return {
2640
- products,
2641
- meta: {
2642
- limit: options?.first ?? 20,
2643
- offset: Number(options?.after ?? 0),
2644
- hybridSearchUsed: false
2645
- }
2646
- };
3398
+ return this.fallbackAdvancedSearch(options);
3399
+ }
3400
+ }
3401
+ /**
3402
+ * Faithful fallback for `searchProductsAdvanced`. A basic-only request is
3403
+ * served by `getProducts`; a request that depends on the optional advanced
3404
+ * endpoint is rejected as a typed `ProviderAPIError` naming the unappliable
3405
+ * fields, so a failed advanced search never returns an unfiltered result
3406
+ * labelled success (E2 task 2.4).
3407
+ */
3408
+ async fallbackAdvancedSearch(options) {
3409
+ const requested = collectAdvancedSearchRequestFields(options);
3410
+ if (requested.length > 0) {
3411
+ throw new ProviderAPIError(
3412
+ `Advanced search unavailable for requested fields: ${requested.join(", ")}`,
3413
+ "medusa",
3414
+ void 0,
3415
+ { fields: requested, repair: { remove: requested } }
3416
+ );
2647
3417
  }
3418
+ const products = await this.getProducts(options);
3419
+ return {
3420
+ products,
3421
+ meta: {
3422
+ limit: options?.first ?? 20,
3423
+ offset: Number(options?.after ?? 0),
3424
+ hybridSearchUsed: false
3425
+ }
3426
+ };
2648
3427
  }
2649
3428
  /**
2650
3429
  * Get available filter options for product filtering
@@ -2699,23 +3478,20 @@ var MedusaProvider = class {
2699
3478
  });
2700
3479
  }
2701
3480
  }
2702
- if (options.useAdvancedSearch && this.capabilities.advancedSearch) {
2703
- filters.push({
2704
- id: "price",
2705
- label: "Price",
2706
- type: "range",
2707
- min: 0,
2708
- max: 1e4,
2709
- isActive: false,
2710
- ranking: 0
2711
- });
2712
- filters.push({
2713
- id: "isAvailable",
2714
- label: "In Stock",
2715
- type: "boolean",
2716
- isActive: false,
2717
- ranking: 5
3481
+ if (options.useAdvancedSearch) {
3482
+ const support = await this.getCatalogFacetSupport({
3483
+ categoryIds: options.categoryId ? [options.categoryId] : [],
3484
+ scope: options.categoryId
2718
3485
  });
3486
+ if (support.offered.includes("inStock")) {
3487
+ filters.push({
3488
+ id: "isAvailable",
3489
+ label: "In Stock",
3490
+ type: "boolean",
3491
+ isActive: false,
3492
+ ranking: 5
3493
+ });
3494
+ }
2719
3495
  }
2720
3496
  if (options.categoryId && this.capabilities.customAttributes) {
2721
3497
  try {
@@ -2750,19 +3526,27 @@ var MedusaProvider = class {
2750
3526
  // Custom attributes lower priority
2751
3527
  };
2752
3528
  if ((filterType === "single" || filterType === "multi") && attr.values) {
2753
- filter.options = attr.values.map((val) => ({
2754
- value: this.toSlug(val.value),
2755
- // URL slug: ?ram=8gb
2756
- label: val.value,
2757
- // Display: "8GB"
2758
- id: val.id,
2759
- // Backend ID: 01KN03N67V13K5S2E6B6695KRN
2760
- count: options.includeFacetCounts ? val.count : void 0
2761
- }));
3529
+ filter.options = attr.values.map((val) => {
3530
+ const count = options.includeFacetCounts ? readFiniteFacetNumber(val.count) : void 0;
3531
+ return {
3532
+ value: this.toSlug(val.value),
3533
+ // URL slug: ?ram=8gb
3534
+ label: val.value,
3535
+ // Display: "8GB"
3536
+ id: val.id,
3537
+ // Backend ID: 01KN03N67V13K5S2E6B6695KRN
3538
+ ...count !== void 0 ? { count } : {}
3539
+ };
3540
+ });
2762
3541
  }
2763
- if (filterType === "range" && attr.metadata) {
2764
- filter.min = attr.metadata.min || 0;
2765
- filter.max = attr.metadata.max || 100;
3542
+ if (filterType === "range") {
3543
+ const min = readFiniteFacetNumber(attr.metadata?.min);
3544
+ const max = readFiniteFacetNumber(attr.metadata?.max);
3545
+ if (min === void 0 || max === void 0) {
3546
+ return;
3547
+ }
3548
+ filter.min = min;
3549
+ filter.max = max;
2766
3550
  }
2767
3551
  filters.push(filter);
2768
3552
  });
@@ -3124,7 +3908,7 @@ var MedusaProvider = class {
3124
3908
  return customFetcher(options);
3125
3909
  }
3126
3910
  try {
3127
- const limit = options.query ? 1e3 : options.limit ?? 100;
3911
+ const limit = options.limit ?? this.catalogPageSize;
3128
3912
  const queryParams = {
3129
3913
  limit,
3130
3914
  include_descendants_tree: options.includeDescendants ?? false
@@ -3164,11 +3948,15 @@ var MedusaProvider = class {
3164
3948
  }
3165
3949
  const categoryQueryParams = {
3166
3950
  category_id: [category.id],
3167
- order: options.sortKey,
3168
- limit: options.first ?? 100,
3951
+ // Bounded, paginated listing (change B, decision 5).
3952
+ limit: options.first ?? this.catalogPageSize,
3169
3953
  offset: options.after ? parseInt(options.after, 10) : void 0,
3170
- fields: "+variants,+variants.prices,+variants.calculated_prices,+variants.inventory_quantity,+options,+images,+tags"
3954
+ fields: "+variants,+variants.prices,+variants.calculated_price,+variants.inventory_quantity,+options,+images,+tags"
3171
3955
  };
3956
+ const mappedOrder = options.sortKey ? MEDUSA_SORT_KEY_MAP[options.sortKey] ?? null : null;
3957
+ if (mappedOrder !== null) {
3958
+ categoryQueryParams.order = mappedOrder;
3959
+ }
3172
3960
  if (this.regionId) {
3173
3961
  categoryQueryParams.region_id = this.regionId;
3174
3962
  }
@@ -3203,7 +3991,7 @@ var MedusaProvider = class {
3203
3991
  } else {
3204
3992
  createPayload.currency_code = this.currencyCode.toLowerCase();
3205
3993
  }
3206
- const salesChannelId = options?.salesChannelId ?? process.env.NEXT_PUBLIC_SALES_CHANNEL_ID;
3994
+ const salesChannelId = options?.salesChannelId ?? resolveConfiguredSalesChannelId();
3207
3995
  if (salesChannelId) {
3208
3996
  createPayload.sales_channel_id = salesChannelId;
3209
3997
  }
@@ -3274,7 +4062,7 @@ var MedusaProvider = class {
3274
4062
  fields: "+variants,+variants.calculated_price,+variants.prices,+variants.money_amounts",
3275
4063
  region_id: backendCart.region_id
3276
4064
  };
3277
- const salesChannelId = process.env.NEXT_PUBLIC_SALES_CHANNEL_ID;
4065
+ const salesChannelId = resolveConfiguredSalesChannelId();
3278
4066
  if (salesChannelId) {
3279
4067
  variantCheckParams.sales_channel_id = [salesChannelId];
3280
4068
  }
@@ -3446,13 +4234,17 @@ var MedusaProvider = class {
3446
4234
  // Order Operations
3447
4235
  // ============================================
3448
4236
  /**
3449
- * Get all orders for a customer (storefront).
4237
+ * Get all orders for a customer (storefront) as an array (legacy surface).
3450
4238
  *
3451
- * Note: This retrieves orders from the storefront API (store.order.list),
3452
- * which returns orders only for the authenticated customer in the JWT.
4239
+ * Delegates to the channel-scoped paginated contract
4240
+ * ({@link customerOrdersPage}) and returns that window's orders. The backend
4241
+ * (`GET /store/thor/orders`) scopes by BOTH the authenticated customer and
4242
+ * the sales channel resolved from the publishable key, so cross-channel
4243
+ * orders are excluded by the backend before pagination and **no client-side
4244
+ * channel filter runs**.
3453
4245
  *
3454
- * @param options - Order query options (supports callbacks for custom backends)
3455
- * @returns Array of orders for the authenticated customer
4246
+ * @param options - Order query options (supports a custom fetcher)
4247
+ * @returns Array of orders for the authenticated customer on the store channel
3456
4248
  *
3457
4249
  * @example
3458
4250
  * ```typescript
@@ -3466,32 +4258,68 @@ var MedusaProvider = class {
3466
4258
  this.logger.debug("Using custom fetcher for orders");
3467
4259
  return customFetcher(options);
3468
4260
  }
3469
- this.logger.info("Getting orders for authenticated customer");
4261
+ const page = await this.customerOrdersPage({
4262
+ page: 1,
4263
+ pageSize: options.limit ?? CUSTOMER_ORDERS_MAX_PAGE_SIZE,
4264
+ salesChannelId
4265
+ });
4266
+ return page.orders;
4267
+ }
4268
+ /**
4269
+ * Channel-scoped, paginated order history for the authenticated customer.
4270
+ *
4271
+ * Calls the backend route `GET /store/thor/orders`, which requires the
4272
+ * customer session and scopes `order` by `customer_id` **and** the
4273
+ * `sales_channel_id` resolved from the publishable key, returning
4274
+ * `{ orders, count, limit, offset }` with the backend's real total computed
4275
+ * before pagination.
4276
+ *
4277
+ * The `salesChannelId` option is the store's explicitly configured channel.
4278
+ * When supplied, every returned order is asserted to belong to it; a
4279
+ * foreign-channel order (for example from a multi-channel publishable key that
4280
+ * silently resolved an arbitrary first id) fails closed with a typed error
4281
+ * rather than being presented as the customer's history.
4282
+ *
4283
+ * @param options - Bounded pagination window and the store's sales channel
4284
+ * @returns The backend's `{ orders, count, limit, offset }`
4285
+ */
4286
+ async customerOrdersPage(options = {}) {
4287
+ const { page, pageSize, limit, offset } = normalizeCustomerOrdersPage(options);
4288
+ const { salesChannelId } = options;
4289
+ this.logger.info("Getting channel-scoped customer orders", { page, pageSize });
3470
4290
  try {
3471
- const result = await this.withRetry(
3472
- async () => this.sdk.store.order.list({
3473
- // Medusa v2 JS-SDK automatically includes authorization header if JWT is present
3474
- fields: "+items,+items.variant,+items.variant.product,+shipping_address,+billing_address,+customer"
4291
+ const response = await this.withRetry(
4292
+ async () => this.sdk.client.fetch("/store/thor/orders", {
4293
+ method: "GET",
4294
+ query: { limit, offset }
3475
4295
  }),
3476
- "getOrders",
4296
+ "customerOrdersPage",
3477
4297
  {}
3478
4298
  );
3479
- const orders = result.orders ?? [];
3480
- this.logger.debug(`Found ${orders.length} orders for customer`);
3481
- const transformed = orders.map((order) => transformOrder(order));
3482
- const channelId = salesChannelId ?? process.env.NEXT_PUBLIC_SALES_CHANNEL_ID;
3483
- if (channelId) {
3484
- const scoped = filterByChannel(transformed, channelId);
3485
- this.logger.debug(
3486
- `Channel scoping: ${scoped.length}/${transformed.length} orders match channel ${channelId}`
4299
+ const rawOrders = response.orders ?? [];
4300
+ this.logger.debug(`Found ${rawOrders.length} channel-scoped orders for customer`);
4301
+ if (salesChannelId) {
4302
+ const foreign = rawOrders.find(
4303
+ (order) => typeof order?.sales_channel_id === "string" && order.sales_channel_id !== salesChannelId
3487
4304
  );
3488
- return scoped;
4305
+ if (foreign) {
4306
+ throw new ProviderAPIError(
4307
+ `Channel-scoped order history returned an order outside the store's sales channel (${salesChannelId}).`,
4308
+ "medusa"
4309
+ );
4310
+ }
3489
4311
  }
3490
- return transformed;
4312
+ return {
4313
+ orders: rawOrders.map((order) => transformOrder(order)),
4314
+ count: typeof response.count === "number" ? response.count : rawOrders.length,
4315
+ limit: typeof response.limit === "number" ? response.limit : limit,
4316
+ offset: typeof response.offset === "number" ? response.offset : offset
4317
+ };
3491
4318
  } catch (error) {
4319
+ if (error instanceof ProviderAPIError) throw error;
3492
4320
  const status = error?.status || error?.statusCode;
3493
4321
  const errorMessage = extractErrorMessage(error);
3494
- this.logger.error("Error getting orders", { error: errorMessage });
4322
+ this.logger.error("Error getting channel-scoped orders", { error: errorMessage });
3495
4323
  throw new ProviderAPIError(
3496
4324
  `Failed to fetch orders: ${errorMessage}`,
3497
4325
  "medusa",
@@ -4390,32 +5218,85 @@ var MedusaProvider = class {
4390
5218
  * @throws {ProviderAPIError} If checkout fails
4391
5219
  */
4392
5220
  async completeCheckout(cartId) {
4393
- this.logger.debug("completeCheckout", { cartId });
4394
- try {
4395
- return await this.withRetry(
4396
- async () => {
4397
- const { order } = await this.sdk.store.cart.complete(cartId);
4398
- if (!order) {
4399
- throw new ProviderAPIError("Checkout completed but no order returned", "medusa", 500);
4400
- }
4401
- this.logger.info("Checkout completed successfully", {
4402
- orderId: order.id,
4403
- displayId: order.display_id
4404
- });
4405
- return transformOrder(order);
4406
- },
4407
- "completeCheckout",
4408
- { cartId }
5221
+ const result = await this.completeCart(cartId);
5222
+ if (result.type === "order") {
5223
+ return result.order;
5224
+ }
5225
+ if (result.type === "cart") {
5226
+ throw new ProviderAPIError(
5227
+ `Failed to complete checkout: ${result.error.message}`,
5228
+ "medusa",
5229
+ result.error.status
4409
5230
  );
5231
+ }
5232
+ throw new ProviderAPIError(
5233
+ `Checkout outcome is unresolved: ${result.error.message}`,
5234
+ "medusa",
5235
+ result.error.status
5236
+ );
5237
+ }
5238
+ /**
5239
+ * Complete a cart exactly once and preserve the native discriminator
5240
+ * (change B, decision 11).
5241
+ *
5242
+ * Medusa's `POST /store/carts/:id/complete` returns HTTP 200 whose body is
5243
+ * either `{ type: 'order', order }` or `{ type: 'cart', cart, error }`. This
5244
+ * method never retries: a thrown transport/timeout/5xx failure becomes an
5245
+ * `unresolved` result so the caller reconciles the committed cart before any
5246
+ * further attempt. The Medusa JS SDK performs no implicit retry of its own,
5247
+ * so there is no blind retry beneath this call either.
5248
+ */
5249
+ async completeCart(cartId) {
5250
+ this.logger.debug("completeCart", { cartId });
5251
+ try {
5252
+ const response = await this.sdk.store.cart.complete(cartId, {
5253
+ fields: MEDUSA_ORDER_COMPLETION_FIELDS
5254
+ });
5255
+ if (response?.type === "cart" || response?.cart && response?.error) {
5256
+ const error = this.toCompletionError(response.error);
5257
+ this.logger.warn("Cart completion returned a cart with an error", {
5258
+ cartId,
5259
+ code: error.code,
5260
+ message: error.message
5261
+ });
5262
+ return { type: "cart", cart: transformCart(response.cart), error };
5263
+ }
5264
+ const order = response?.order;
5265
+ if (!order) {
5266
+ return {
5267
+ type: "unresolved",
5268
+ error: { message: "Checkout returned neither an order nor a cart error" }
5269
+ };
5270
+ }
5271
+ this.logger.info("Checkout completed successfully", {
5272
+ orderId: order.id,
5273
+ displayId: order.display_id
5274
+ });
5275
+ return { type: "order", order: transformOrder(order) };
4410
5276
  } catch (error) {
4411
- this.logger.error("Failed to complete checkout", { cartId, error: error.message });
4412
- throw new ProviderAPIError(
4413
- `Failed to complete checkout: ${error.message}`,
4414
- "medusa",
4415
- error.status
4416
- );
5277
+ const completionError = this.toCompletionError(error);
5278
+ this.logger.error("Cart completion failed (unresolved, not retried)", {
5279
+ cartId,
5280
+ status: completionError.status,
5281
+ message: completionError.message
5282
+ });
5283
+ return { type: "unresolved", error: completionError };
4417
5284
  }
4418
5285
  }
5286
+ /** Normalize any thrown/returned completion failure into a structured error. */
5287
+ toCompletionError(error) {
5288
+ if (error && typeof error === "object") {
5289
+ const err = error;
5290
+ const message = typeof err.message === "string" && err.message.length > 0 ? err.message : extractErrorMessage(error);
5291
+ return {
5292
+ message,
5293
+ code: typeof err.code === "string" ? err.code : void 0,
5294
+ status: err.status ?? err.statusCode,
5295
+ raw: err
5296
+ };
5297
+ }
5298
+ return { message: extractErrorMessage(error), raw: error };
5299
+ }
4419
5300
  /**
4420
5301
  * Get available shipping methods for cart
4421
5302
  *
@@ -4426,130 +5307,66 @@ var MedusaProvider = class {
4426
5307
  * @throws {ProviderAPIError} If cart not found or region not configured
4427
5308
  */
4428
5309
  async getShippingMethods(cartId) {
4429
- this.logger.info("\u{1F69A} [DEBUG] getShippingMethods called", { cartId });
5310
+ this.logger.debug("getShippingMethods", { cartId });
4430
5311
  try {
4431
5312
  return await this.withRetry(
4432
5313
  async () => {
4433
- this.logger.info("\u{1F69A} [DEBUG] Step 1: Retrieving cart from Medusa...", { cartId });
4434
5314
  const cartResponse = await this.sdk.store.cart.retrieve(cartId);
4435
5315
  const { cart } = cartResponse;
4436
- this.logger.info("\u{1F69A} [DEBUG] Step 2: Cart retrieved from backend", {
4437
- cartId,
4438
- hasCart: !!cart,
4439
- cartKeys: cart ? Object.keys(cart) : [],
4440
- regionId: cart?.region_id,
4441
- currencyCode: cart?.currency_code,
4442
- shippingAddress: cart?.shipping_address ? {
4443
- country: cart.shipping_address.country_code,
4444
- postal: cart.shipping_address.postal_code
4445
- } : null
4446
- });
4447
5316
  if (!cart) {
4448
- this.logger.error("\u{1F69A} [DEBUG] ERROR: Cart not found in response", {
4449
- cartId,
4450
- cartResponse
4451
- });
4452
5317
  throw new ResourceNotFoundError("Cart", cartId);
4453
5318
  }
4454
5319
  if (!cart.region_id) {
4455
- this.logger.error("\u{1F69A} [DEBUG] ERROR: Cart has no region_id", {
4456
- cartId,
4457
- cart: {
4458
- id: cart.id,
4459
- region_id: cart.region_id,
4460
- region: cart.region,
4461
- allKeys: Object.keys(cart)
4462
- }
4463
- });
4464
5320
  throw new ProviderAPIError("Cart has no region assigned", "medusa", 400);
4465
5321
  }
4466
- this.logger.info("\u{1F69A} [DEBUG] Step 3: Fetching shipping options from Medusa...", {
4467
- cartId,
4468
- regionId: cart.region_id,
4469
- endpoint: `${this.baseUrl}store/shipping-options?cart_id=${cartId}`,
4470
- note: "About to fetch shipping options (SDK when available, otherwise HTTP)"
4471
- });
4472
- let shippingResponse;
4473
- let shipping_options;
4474
- try {
4475
- const storeAny = this.sdk.store;
4476
- if (storeAny?.shippingOption?.list) {
4477
- shippingResponse = await storeAny.shippingOption.list({
4478
- cart_id: cartId
4479
- });
4480
- } else {
4481
- const baseUrl = this.baseUrl.endsWith("/") ? this.baseUrl : `${this.baseUrl}/`;
4482
- const url = new URL("store/shipping-options", baseUrl);
4483
- url.searchParams.set("cart_id", cartId);
4484
- const response = await fetchWithRetry(
4485
- url.toString(),
4486
- {
4487
- method: "GET",
4488
- headers: {
4489
- "x-publishable-api-key": this.publishableKey,
4490
- "content-type": "application/json"
4491
- }
4492
- },
4493
- this.retryConfig
4494
- );
4495
- shippingResponse = await response.json();
4496
- }
4497
- shipping_options = shippingResponse.shipping_options;
4498
- } catch (sdkError) {
4499
- this.logger.error(
4500
- "\u{1F69A} [DEBUG] ERROR: Medusa SDK threw error when fetching shipping options",
5322
+ let shippingOptions = [];
5323
+ const storeAny = this.sdk.store;
5324
+ if (storeAny?.fulfillment?.listCartOptions) {
5325
+ const response = await storeAny.fulfillment.listCartOptions({
5326
+ cart_id: cartId
5327
+ });
5328
+ shippingOptions = response?.shipping_options ?? [];
5329
+ } else {
5330
+ const baseUrl = this.baseUrl.endsWith("/") ? this.baseUrl : `${this.baseUrl}/`;
5331
+ const url = new URL("store/shipping-options", baseUrl);
5332
+ url.searchParams.set("cart_id", cartId);
5333
+ const response = await fetchWithRetry(
5334
+ url.toString(),
4501
5335
  {
4502
- cartId,
4503
- regionId: cart.region_id,
4504
- errorType: sdkError?.constructor?.name,
4505
- errorMessage: sdkError?.message,
4506
- errorStatus: sdkError?.status,
4507
- errorCode: sdkError?.code,
4508
- errorResponse: sdkError?.response ? JSON.stringify(sdkError.response, null, 2) : "N/A",
4509
- errorBody: sdkError?.body ? JSON.stringify(sdkError.body, null, 2) : "N/A",
4510
- fullError: JSON.stringify(sdkError, Object.getOwnPropertyNames(sdkError), 2)
4511
- }
5336
+ method: "GET",
5337
+ headers: {
5338
+ "x-publishable-api-key": this.publishableKey,
5339
+ "content-type": "application/json"
5340
+ }
5341
+ },
5342
+ this.retryConfig
4512
5343
  );
4513
- throw sdkError;
5344
+ shippingOptions = (await response.json())?.shipping_options ?? [];
4514
5345
  }
4515
- this.logger.info("\u{1F69A} [DEBUG] Step 4: Shipping options received from backend", {
4516
- cartId,
4517
- totalOptions: shipping_options?.length || 0,
4518
- rawResponse: JSON.stringify(shippingResponse, null, 2),
4519
- firstOption: shipping_options?.[0] ? {
4520
- id: shipping_options[0].id,
4521
- name: shipping_options[0].name,
4522
- allKeys: Object.keys(shipping_options[0]),
4523
- price_incl_tax: shipping_options[0].price_incl_tax,
4524
- amount: shipping_options[0].amount,
4525
- data: shipping_options[0].data
4526
- } : null
4527
- });
4528
- const methods = shipping_options.map((option) => ({
4529
- id: option.id,
4530
- name: option.name,
4531
- price: {
4532
- amount: option.price_incl_tax?.toString() || option.amount?.toString() || "0",
4533
- currencyCode: cart.currency_code?.toUpperCase() || this.currencyCode
4534
- },
4535
- description: option.data?.description,
4536
- estimatedDays: option.data?.estimated_days || "N/A"
4537
- }));
4538
- this.logger.info("\u{1F69A} [DEBUG] Step 5: Transformed methods for Thor types", {
4539
- cartId,
4540
- count: methods.length,
4541
- methods: JSON.stringify(methods, null, 2)
5346
+ const currencyCode = cart.currency_code?.toUpperCase() ?? "";
5347
+ return shippingOptions.map((option) => {
5348
+ const amount = option?.amount ?? option?.price_incl_tax;
5349
+ const estimatedDays = option?.data?.estimated_days != null ? String(option.data.estimated_days) : void 0;
5350
+ return {
5351
+ id: option.id,
5352
+ name: option.name,
5353
+ price: {
5354
+ amount: typeof amount === "number" && Number.isFinite(amount) ? amount.toFixed(2) : "",
5355
+ currencyCode
5356
+ },
5357
+ description: option?.data?.description,
5358
+ estimatedDays,
5359
+ fulfillmentSetType: option?.service_zone?.fulfillment_set?.type ?? null
5360
+ };
4542
5361
  });
4543
- return methods;
4544
5362
  },
4545
5363
  "getShippingMethods",
4546
5364
  { cartId }
4547
5365
  );
4548
5366
  } catch (error) {
4549
- this.logger.error("\u{1F69A} [DEBUG] ERROR: Failed to fetch shipping methods", {
5367
+ this.logger.error("Failed to fetch shipping methods", {
4550
5368
  cartId,
4551
5369
  errorMessage: error.message,
4552
- errorStack: error.stack,
4553
5370
  errorStatus: error.status
4554
5371
  });
4555
5372
  throw new ProviderAPIError(
@@ -4910,19 +5727,12 @@ var MedusaProvider = class {
4910
5727
  async addShippingMethod(cartId, methodId) {
4911
5728
  this.logger.debug("addShippingMethod", { cartId, methodId });
4912
5729
  try {
4913
- return await this.withRetry(
4914
- async () => {
4915
- const { cart } = await this.sdk.store.cart.addShippingMethod(cartId, {
4916
- option_id: methodId
4917
- });
4918
- this.logger.info("Shipping method added successfully", { cartId, methodId });
4919
- void cart;
4920
- const updatedCart = await this.retrieveCartWithLineDetails(cartId);
4921
- return transformCart(updatedCart);
4922
- },
4923
- "addShippingMethod",
4924
- { cartId, methodId }
4925
- );
5730
+ await this.sdk.store.cart.addShippingMethod(cartId, {
5731
+ option_id: methodId
5732
+ });
5733
+ this.logger.info("Shipping method added successfully", { cartId, methodId });
5734
+ const updatedCart = await this.retrieveCartWithLineDetails(cartId);
5735
+ return transformCart(updatedCart);
4926
5736
  } catch (error) {
4927
5737
  this.logger.error("Failed to add shipping method", {
4928
5738
  cartId,
@@ -4946,166 +5756,75 @@ var MedusaProvider = class {
4946
5756
  * @throws {ProviderAPIError} If provider invalid or cart not ready
4947
5757
  */
4948
5758
  async initiatePaymentSession(cartId, providerId) {
4949
- this.logger.info("\u{1F4B3} [DEBUG] initiatePaymentSession called", { cartId, providerId });
5759
+ this.logger.debug("initiatePaymentSession", { cartId, providerId });
4950
5760
  try {
4951
- await this.withRetry(
4952
- async () => {
4953
- this.logger.info(
4954
- "\u{1F4B3} [DEBUG] Step 1: Retrieving RAW cart from Medusa for payment session...",
4955
- { cartId }
4956
- );
4957
- const { cart: rawCart } = await this.sdk.store.cart.retrieve(cartId, {
4958
- fields: "+shipping_methods,+shipping_address,+email,+region_id,+total,+items,+payment_collection,+payment_collection.payment_sessions,+billing_address"
4959
- });
4960
- this.logger.info("\u{1F4B3} [DEBUG] Step 2: RAW cart retrieved, checking state...", {
4961
- cartId: rawCart.id,
4962
- hasShippingMethod: !!rawCart.shipping_methods?.length,
4963
- shippingMethodIds: rawCart.shipping_methods?.map((sm) => sm.id) || [],
4964
- hasShippingAddress: !!rawCart.shipping_address,
4965
- shippingAddressCity: rawCart.shipping_address?.city || "N/A",
4966
- hasEmail: !!rawCart.email,
4967
- email: rawCart.email || "N/A",
4968
- hasBillingAddress: !!rawCart.billing_address,
4969
- hasPaymentCollection: !!rawCart.payment_collection,
4970
- existingSessionsCount: rawCart.payment_collection?.payment_sessions?.length || 0,
4971
- regionId: rawCart.region_id,
4972
- total: rawCart.total,
4973
- itemCount: rawCart.items?.length || 0
4974
- });
4975
- if (!rawCart.items || rawCart.items.length === 0) {
4976
- this.logger.error("\u{1F4B3} [DEBUG] ERROR: Cannot create payment session for empty cart", {
4977
- cartId,
4978
- itemCount: 0,
4979
- reason: "Cart has no items"
4980
- });
4981
- throw new ProviderAPIError(
4982
- "Cannot create payment session: cart is empty. Please add items to your cart before checking out.",
4983
- "medusa",
4984
- 400
4985
- );
4986
- }
4987
- if (!rawCart.shipping_address) {
4988
- this.logger.error("\u{1F4B3} [DEBUG] ERROR: Shipping address required", { cartId });
4989
- throw new ProviderAPIError(
4990
- "Shipping address is required before initiating payment session",
4991
- "medusa",
4992
- 400
4993
- );
4994
- }
4995
- if (!rawCart.shipping_methods?.length) {
4996
- this.logger.error("\u{1F4B3} [DEBUG] ERROR: Shipping method required", { cartId });
4997
- throw new ProviderAPIError(
4998
- "Shipping method is required before initiating payment session",
4999
- "medusa",
5000
- 400
5001
- );
5002
- }
5003
- if (!rawCart.email) {
5004
- this.logger.error("\u{1F4B3} [DEBUG] ERROR: Email required", { cartId });
5005
- throw new ProviderAPIError(
5006
- "Email is required before initiating payment session",
5007
- "medusa",
5008
- 400
5009
- );
5010
- }
5011
- if (!rawCart.billing_address) {
5012
- this.logger.warn(
5013
- "\u{1F4B3} [DEBUG] WARNING: Billing address not set, payment provider may require it",
5014
- {
5015
- cartId: rawCart.id,
5016
- shippingAddress: rawCart.shipping_address
5017
- }
5018
- );
5019
- }
5020
- const existingSessions = rawCart.payment_collection?.payment_sessions || [];
5021
- if (existingSessions.length > 0) {
5022
- this.logger.info("\u{1F4B3} [DEBUG] Payment session already exists, skipping creation", {
5023
- cartId: rawCart.id,
5024
- sessionCount: existingSessions.length,
5025
- sessionIds: existingSessions.map((s) => s.id)
5026
- });
5027
- return;
5028
- }
5029
- this.logger.info("\u{1F4B3} [DEBUG] Step 2.5: No existing payment sessions, will create new one", {
5030
- cartId: rawCart.id,
5031
- hasPaymentCollection: !!rawCart.payment_collection,
5032
- providerId
5033
- });
5034
- this.logger.info("\u{1F4B3} [DEBUG] Step 3: Calling Medusa SDK initiatePaymentSession...", {
5035
- cartId,
5036
- providerId,
5037
- endpoint: `${this.baseUrl}store/payment-collections`,
5038
- note: "About to call SDK method"
5039
- });
5040
- this.logger.info("\u{1F4B3} [DEBUG] Step 2.5: Validating provider ID...", {
5041
- providerId
5042
- });
5043
- try {
5044
- validatePaymentId(providerId);
5045
- this.logger.info("\u{1F4B3} [DEBUG] Provider ID validation passed", { providerId });
5046
- } catch (validationError) {
5047
- this.logger.error("\u{1F4B3} [DEBUG] ERROR: Invalid provider ID detected", {
5048
- providerId,
5049
- error: validationError.message,
5050
- hint: "Use getBackendProviderId(paymentMethod) to extract correct ID"
5051
- });
5052
- throw new ProviderAPIError(
5053
- validationError.message,
5054
- "medusa",
5055
- 400
5056
- );
5057
- }
5058
- let paymentResponse;
5059
- try {
5060
- paymentResponse = await this.sdk.store.payment.initiatePaymentSession(rawCart, {
5061
- provider_id: providerId
5062
- });
5063
- this.logger.info("\u{1F4B3} [DEBUG] Step 4: Payment session response received", {
5064
- cartId,
5065
- providerId,
5066
- responseKeys: paymentResponse ? Object.keys(paymentResponse) : [],
5067
- response: JSON.stringify(paymentResponse, null, 2)
5068
- });
5069
- } catch (sdkError) {
5070
- this.logger.error(
5071
- "\u{1F4B3} [DEBUG] ERROR: Medusa SDK threw error when initiating payment session",
5072
- {
5073
- cartId,
5074
- providerId,
5075
- errorType: sdkError?.constructor?.name,
5076
- errorMessage: sdkError?.message,
5077
- errorStatus: sdkError?.status,
5078
- errorCode: sdkError?.code,
5079
- errorResponse: sdkError?.response ? JSON.stringify(sdkError.response, null, 2) : "N/A",
5080
- errorBody: sdkError?.body ? JSON.stringify(sdkError.body, null, 2) : "N/A",
5081
- fullError: JSON.stringify(sdkError, Object.getOwnPropertyNames(sdkError), 2),
5082
- // Include cart state in error for debugging
5083
- cartState: {
5084
- hasShippingMethod: !!rawCart.shipping_methods?.length,
5085
- hasShippingAddress: !!rawCart.shipping_address,
5086
- hasBillingAddress: !!rawCart.billing_address,
5087
- hasEmail: !!rawCart.email,
5088
- total: rawCart.total,
5089
- itemCount: rawCart.items?.length || 0
5090
- }
5091
- }
5092
- );
5093
- throw sdkError;
5094
- }
5095
- this.logger.info("\u{1F4B3} [DEBUG] Payment session initiated successfully", {
5096
- cartId,
5097
- providerId
5098
- });
5099
- },
5100
- "initiatePaymentSession",
5101
- { cartId, providerId }
5102
- );
5761
+ const { cart: rawCart } = await this.sdk.store.cart.retrieve(cartId, {
5762
+ fields: "+shipping_methods,+shipping_address,+email,+region_id,+total,+items,+payment_collection,+payment_collection.payment_sessions,+billing_address"
5763
+ });
5764
+ if (!rawCart.items || rawCart.items.length === 0) {
5765
+ throw new ProviderAPIError(
5766
+ "Cannot create payment session: cart is empty. Please add items to your cart before checking out.",
5767
+ "medusa",
5768
+ 400
5769
+ );
5770
+ }
5771
+ if (!rawCart.shipping_address) {
5772
+ throw new ProviderAPIError(
5773
+ "Shipping address is required before initiating payment session",
5774
+ "medusa",
5775
+ 400
5776
+ );
5777
+ }
5778
+ if (!rawCart.shipping_methods?.length) {
5779
+ throw new ProviderAPIError(
5780
+ "Shipping method is required before initiating payment session",
5781
+ "medusa",
5782
+ 400
5783
+ );
5784
+ }
5785
+ if (!rawCart.email) {
5786
+ throw new ProviderAPIError(
5787
+ "Email is required before initiating payment session",
5788
+ "medusa",
5789
+ 400
5790
+ );
5791
+ }
5792
+ validatePaymentId(providerId);
5793
+ const existingSessions = rawCart.payment_collection?.payment_sessions ?? [];
5794
+ const compatible = existingSessions.find((session) => {
5795
+ const statusOk = ["pending", "requires_more", "authorized"].includes(session?.status);
5796
+ return session?.provider_id === providerId && session?.amount === rawCart.total && statusOk;
5797
+ });
5798
+ if (compatible) {
5799
+ this.logger.info("Reusing compatible payment session", {
5800
+ cartId,
5801
+ providerId,
5802
+ sessionId: compatible.id,
5803
+ amount: compatible.amount
5804
+ });
5805
+ return;
5806
+ }
5807
+ if (existingSessions.length > 0) {
5808
+ this.logger.info("Existing payment session incompatible; replacing it", {
5809
+ cartId,
5810
+ providerId,
5811
+ existing: existingSessions.map((session) => ({
5812
+ id: session.id,
5813
+ providerId: session.provider_id,
5814
+ amount: session.amount,
5815
+ status: session.status
5816
+ }))
5817
+ });
5818
+ }
5819
+ await this.sdk.store.payment.initiatePaymentSession(rawCart, {
5820
+ provider_id: providerId
5821
+ });
5822
+ this.logger.info("Payment session initiated", { cartId, providerId });
5103
5823
  } catch (error) {
5104
- this.logger.error("\u{1F4B3} [DEBUG] ERROR: Failed to initiate payment session", {
5824
+ this.logger.error("Failed to initiate payment session", {
5105
5825
  cartId,
5106
5826
  providerId,
5107
5827
  errorMessage: error.message,
5108
- errorStack: error.stack,
5109
5828
  errorStatus: error.status
5110
5829
  });
5111
5830
  throw new ProviderAPIError(
@@ -5128,31 +5847,23 @@ var MedusaProvider = class {
5128
5847
  async applyDiscountCode(cartId, code) {
5129
5848
  this.logger.debug("applyDiscountCode", { cartId, code });
5130
5849
  try {
5131
- return await this.withRetry(
5132
- async () => {
5133
- const response = await fetch(`${this.baseUrl}/store/carts/${cartId}/promotions`, {
5134
- method: "POST",
5135
- headers: {
5136
- "Content-Type": "application/json",
5137
- "x-publishable-api-key": this.publishableKey || ""
5138
- },
5139
- body: JSON.stringify({
5140
- promo_codes: [code]
5141
- })
5142
- });
5143
- if (!response.ok) {
5144
- const error = await response.json();
5145
- throw new Error(error.message || "Failed to apply discount code");
5146
- }
5147
- const { cart: medusaCart } = await response.json();
5148
- this.logger.info("Discount code applied successfully", { cartId, code });
5149
- void medusaCart;
5150
- const updatedCart = await this.retrieveCartWithLineDetails(cartId);
5151
- return transformCart(updatedCart);
5850
+ const response = await fetch(`${this.baseUrl}/store/carts/${cartId}/promotions`, {
5851
+ method: "POST",
5852
+ headers: {
5853
+ "Content-Type": "application/json",
5854
+ "x-publishable-api-key": this.publishableKey || ""
5152
5855
  },
5153
- "applyDiscountCode",
5154
- { cartId, code }
5155
- );
5856
+ body: JSON.stringify({
5857
+ promo_codes: [code]
5858
+ })
5859
+ });
5860
+ if (!response.ok) {
5861
+ const error = await response.json();
5862
+ throw new Error(error.message || "Failed to apply discount code");
5863
+ }
5864
+ this.logger.info("Discount code applied successfully", { cartId, code });
5865
+ const updatedCart = await this.retrieveCartWithLineDetails(cartId);
5866
+ return transformCart(updatedCart);
5156
5867
  } catch (error) {
5157
5868
  this.logger.error("Failed to apply discount code", { cartId, code, error: error.message });
5158
5869
  throw new ProviderAPIError(
@@ -5175,31 +5886,23 @@ var MedusaProvider = class {
5175
5886
  async removeDiscountCode(cartId, code) {
5176
5887
  this.logger.debug("removeDiscountCode", { cartId, code });
5177
5888
  try {
5178
- return await this.withRetry(
5179
- async () => {
5180
- const response = await fetch(`${this.baseUrl}/store/carts/${cartId}/promotions`, {
5181
- method: "DELETE",
5182
- headers: {
5183
- "Content-Type": "application/json",
5184
- "x-publishable-api-key": this.publishableKey || ""
5185
- },
5186
- body: JSON.stringify({
5187
- promo_codes: [code]
5188
- })
5189
- });
5190
- if (!response.ok) {
5191
- const error = await response.json();
5192
- throw new Error(error.message || "Failed to remove discount code");
5193
- }
5194
- const { cart: medusaCart } = await response.json();
5195
- this.logger.info("Discount code removed successfully", { cartId, code });
5196
- void medusaCart;
5197
- const updatedCart = await this.retrieveCartWithLineDetails(cartId);
5198
- return transformCart(updatedCart);
5889
+ const response = await fetch(`${this.baseUrl}/store/carts/${cartId}/promotions`, {
5890
+ method: "DELETE",
5891
+ headers: {
5892
+ "Content-Type": "application/json",
5893
+ "x-publishable-api-key": this.publishableKey || ""
5199
5894
  },
5200
- "removeDiscountCode",
5201
- { cartId, code }
5202
- );
5895
+ body: JSON.stringify({
5896
+ promo_codes: [code]
5897
+ })
5898
+ });
5899
+ if (!response.ok) {
5900
+ const error = await response.json();
5901
+ throw new Error(error.message || "Failed to remove discount code");
5902
+ }
5903
+ this.logger.info("Discount code removed successfully", { cartId, code });
5904
+ const updatedCart = await this.retrieveCartWithLineDetails(cartId);
5905
+ return transformCart(updatedCart);
5203
5906
  } catch (error) {
5204
5907
  this.logger.error("Failed to remove discount code", { cartId, code, error: error.message });
5205
5908
  throw new ProviderAPIError(
@@ -9194,6 +9897,7 @@ var StelOrderProvider = class {
9194
9897
  // src/providers/mock/mock.ts
9195
9898
  var FIXTURE_TIMESTAMP = "2026-01-01T00:00:00.000Z";
9196
9899
  var DEFAULT_SITE_URL = "https://mock.thorcommerce.local";
9900
+ var MOCK_SALES_CHANNEL_ID = "mock-sales-channel";
9197
9901
  var regionFixtures = [
9198
9902
  {
9199
9903
  id: "mock-region-us",
@@ -9262,10 +9966,11 @@ var categoryFixtures = [
9262
9966
  description: "Complementary products for cart and bundle flows."
9263
9967
  }
9264
9968
  ];
9265
- var productFixtures = [
9969
+ var heroProductFixtures = [
9266
9970
  {
9267
9971
  id: "mock-product-aurora-jacket",
9268
9972
  handle: "aurora-jacket",
9973
+ createdAt: "2026-01-05T00:00:00.000Z",
9269
9974
  title: "Aurora Quilted Jacket",
9270
9975
  description: "Lightweight quilted outerwear with tonal hardware and a soft structured collar.",
9271
9976
  imageLabel: "Aurora Jacket",
@@ -9307,6 +10012,7 @@ var productFixtures = [
9307
10012
  {
9308
10013
  id: "mock-product-solis-dress",
9309
10014
  handle: "solis-dress",
10015
+ createdAt: "2026-01-03T00:00:00.000Z",
9310
10016
  title: "Solis Pleated Dress",
9311
10017
  description: "A fluid pleated dress with a clean neckline designed for hero storytelling.",
9312
10018
  imageLabel: "Solis Dress",
@@ -9346,6 +10052,7 @@ var productFixtures = [
9346
10052
  {
9347
10053
  id: "mock-product-helios-lamp",
9348
10054
  handle: "helios-lamp",
10055
+ createdAt: "2026-01-04T00:00:00.000Z",
9349
10056
  title: "Helios Table Lamp",
9350
10057
  description: "Warm ambient lamp with sculptural proportions for lifestyle and home grids.",
9351
10058
  imageLabel: "Helios Lamp",
@@ -9369,6 +10076,7 @@ var productFixtures = [
9369
10076
  {
9370
10077
  id: "mock-product-luna-bag",
9371
10078
  handle: "luna-bag",
10079
+ createdAt: "2026-01-02T00:00:00.000Z",
9372
10080
  title: "Luna Crossbody Bag",
9373
10081
  description: "Compact everyday bag for accessory rails, checkout add-ons, and bundle modules.",
9374
10082
  imageLabel: "Luna Bag",
@@ -9390,6 +10098,119 @@ var productFixtures = [
9390
10098
  ]
9391
10099
  }
9392
10100
  ];
10101
+ var generatedBlueprints = [
10102
+ {
10103
+ categoryHandle: "jackets",
10104
+ noun: "Jacket",
10105
+ productType: "outerwear",
10106
+ vendor: "Thor Atelier",
10107
+ tags: ["outerwear", "layer"],
10108
+ variantName: "Size",
10109
+ variantValues: ["S", "M"],
10110
+ names: ["Alpine", "Boreal", "Cinder", "Drift", "Ember", "Fjord", "Harbor", "Meridian", "Nomad", "Tundra", "Vantage"],
10111
+ description: "A considered layering piece in a brushed weave.",
10112
+ basePrice: 118,
10113
+ baseHue: 210
10114
+ },
10115
+ {
10116
+ categoryHandle: "dresses",
10117
+ noun: "Dress",
10118
+ productType: "dress",
10119
+ vendor: "Thor Atelier",
10120
+ tags: ["dress", "editorial"],
10121
+ variantName: "Size",
10122
+ variantValues: ["S", "M"],
10123
+ names: ["Amber", "Camille", "Dahlia", "Elara", "Iris", "Lumen", "Nova", "Rosalind", "Vera"],
10124
+ description: "Cut from a fluid cloth for editorial styling.",
10125
+ basePrice: 142,
10126
+ baseHue: 330
10127
+ },
10128
+ {
10129
+ categoryHandle: "home",
10130
+ noun: "Lamp",
10131
+ productType: "decor",
10132
+ vendor: "Thor Home",
10133
+ tags: ["home", "decor", "interior"],
10134
+ variantName: "Finish",
10135
+ variantValues: ["Brass"],
10136
+ names: ["Atlas", "Copper", "Dune", "Onyx", "Quill", "Slate", "Terra", "Verdant"],
10137
+ description: "A calm sculptural accent for modern interiors.",
10138
+ basePrice: 74,
10139
+ baseHue: 40
10140
+ },
10141
+ {
10142
+ categoryHandle: "accessories",
10143
+ noun: "Bag",
10144
+ productType: "bag",
10145
+ vendor: "Thor Atelier",
10146
+ tags: ["accessory", "everyday"],
10147
+ variantName: "Color",
10148
+ variantValues: ["Juniper"],
10149
+ names: ["Cove", "Fable", "Juniper", "Kestrel", "Marlowe", "Piper", "Rune"],
10150
+ description: "An everyday carry with a textured finish.",
10151
+ basePrice: 68,
10152
+ baseHue: 280
10153
+ }
10154
+ ];
10155
+ var GENERATED_CREATED_AT_BASE = Date.parse("2025-12-30T00:00:00.000Z");
10156
+ var GENERATED_COLLECTION_POOL = ["new-arrivals", "best-sellers", "studio-essentials"];
10157
+ function buildGeneratedProductFixtures() {
10158
+ const fixtures = [];
10159
+ let globalIndex = 0;
10160
+ for (const blueprint of generatedBlueprints) {
10161
+ const noun = blueprint.noun.toLowerCase();
10162
+ blueprint.names.forEach((name, localIndex) => {
10163
+ const handle = `${name.toLowerCase()}-${noun}`;
10164
+ const title = `${name} ${blueprint.noun}`;
10165
+ const price = blueprint.basePrice + localIndex * 7 + localIndex % 3 * 0.5;
10166
+ const quantityAvailable = globalIndex * 5 % 17;
10167
+ const primaryCollection = GENERATED_COLLECTION_POOL[globalIndex % GENERATED_COLLECTION_POOL.length];
10168
+ const collectionHandles = [primaryCollection];
10169
+ if (globalIndex % 5 === 0) {
10170
+ const secondary = GENERATED_COLLECTION_POOL[(globalIndex + 1) % GENERATED_COLLECTION_POOL.length];
10171
+ if (secondary !== primaryCollection) {
10172
+ collectionHandles.push(secondary);
10173
+ }
10174
+ }
10175
+ const createdAt = new Date(GENERATED_CREATED_AT_BASE - globalIndex * 864e5).toISOString();
10176
+ const variants = blueprint.variantValues.map((value, variantIndex) => ({
10177
+ id: `mock-variant-${handle}-${value.toLowerCase()}`,
10178
+ title: value,
10179
+ price,
10180
+ quantityAvailable: Math.max(0, quantityAvailable - variantIndex),
10181
+ selectedOptions: [{ name: blueprint.variantName, value }]
10182
+ }));
10183
+ fixtures.push({
10184
+ id: `mock-product-${handle}`,
10185
+ handle,
10186
+ title,
10187
+ description: `${title} - ${blueprint.description}`,
10188
+ imageLabel: title,
10189
+ imageHue: (blueprint.baseHue + localIndex * 13) % 360,
10190
+ collectionHandles,
10191
+ categoryHandle: blueprint.categoryHandle,
10192
+ productType: blueprint.productType,
10193
+ vendor: blueprint.vendor,
10194
+ tags: [...blueprint.tags],
10195
+ options: [
10196
+ {
10197
+ id: `${handle}-${blueprint.variantName.toLowerCase()}`,
10198
+ name: blueprint.variantName,
10199
+ values: [...blueprint.variantValues]
10200
+ }
10201
+ ],
10202
+ variants,
10203
+ createdAt
10204
+ });
10205
+ globalIndex += 1;
10206
+ });
10207
+ }
10208
+ return fixtures;
10209
+ }
10210
+ var productFixtures = [
10211
+ ...heroProductFixtures,
10212
+ ...buildGeneratedProductFixtures()
10213
+ ];
9393
10214
  var stockLocationFixture = {
9394
10215
  id: "mock-stock-primary",
9395
10216
  name: "Mock Main Warehouse",
@@ -9506,10 +10327,24 @@ function buildProducts(currencyCode) {
9506
10327
  title: collection.title,
9507
10328
  handle: collection.handle
9508
10329
  })),
10330
+ categories: (() => {
10331
+ const category = categoryFixtures.find(
10332
+ (item) => item.handle === product.categoryHandle
10333
+ );
10334
+ if (!category) return void 0;
10335
+ return [
10336
+ {
10337
+ id: category.id,
10338
+ name: category.name,
10339
+ handle: category.handle,
10340
+ parentCategoryId: category.parentCategoryId
10341
+ }
10342
+ ];
10343
+ })(),
9509
10344
  productType: product.productType,
9510
10345
  vendor: product.vendor,
9511
10346
  tags: product.tags,
9512
- createdAt: FIXTURE_TIMESTAMP,
10347
+ createdAt: product.createdAt,
9513
10348
  updatedAt: FIXTURE_TIMESTAMP,
9514
10349
  metadata: {
9515
10350
  categoryHandle: product.categoryHandle,
@@ -9578,6 +10413,92 @@ function paginateProducts(products, skip, first) {
9578
10413
  const end = first ? start + first : void 0;
9579
10414
  return products.slice(start, end);
9580
10415
  }
10416
+ var MOCK_CATALOG_SORT_KEYS = [
10417
+ "featured",
10418
+ "name",
10419
+ "newest"
10420
+ ];
10421
+ var MOCK_CATALOG_ENDPOINT = "mock://catalog/products";
10422
+ var MOCK_CATALOG_PAGE_SIZE = 50;
10423
+ function resolveEffectiveCategoryHandles2(query) {
10424
+ const { categoryScope, categories } = query;
10425
+ if (categoryScope === void 0) return categories;
10426
+ if (categories === void 0) return [categoryScope];
10427
+ return categories.filter((handle) => handle === categoryScope);
10428
+ }
10429
+ function collectRequestedAdvancedFields2(query) {
10430
+ const fields = [];
10431
+ if (query.priceMin !== void 0) fields.push("priceMin");
10432
+ if (query.priceMax !== void 0) fields.push("priceMax");
10433
+ if (query.inStock !== void 0) fields.push("inStock");
10434
+ for (const name of Object.keys(query.attributes ?? {})) {
10435
+ fields.push(`attr.${name}`);
10436
+ }
10437
+ return fields;
10438
+ }
10439
+ function advancedFieldToFacet2(field) {
10440
+ if (field === "priceMin" || field === "priceMax") return "price";
10441
+ return field;
10442
+ }
10443
+ function buildAppliedCatalogFilters2(query, effectiveCategoryHandles) {
10444
+ return {
10445
+ ...query.text ? { text: query.text } : {},
10446
+ ...effectiveCategoryHandles !== void 0 ? { categories: effectiveCategoryHandles } : {},
10447
+ ...query.collections !== void 0 ? { collections: query.collections } : {}
10448
+ };
10449
+ }
10450
+ function buildBasicDemonstratedQuery2(query) {
10451
+ return {
10452
+ ...query.text !== void 0 ? { text: query.text } : {},
10453
+ ...query.categoryScope !== void 0 ? { categoryScope: query.categoryScope } : {},
10454
+ ...query.categories !== void 0 ? { categories: query.categories } : {},
10455
+ ...query.collections !== void 0 ? { collections: query.collections } : {}
10456
+ };
10457
+ }
10458
+ function buildMockFacetSupport(query) {
10459
+ const appliedQuery = buildBasicDemonstratedQuery2(query);
10460
+ const scopeField = query.categoryScope !== void 0 ? { scope: query.categoryScope } : {};
10461
+ return {
10462
+ offered: ["categories", "collections"],
10463
+ held: ["price", "inStock"],
10464
+ demonstrations: {
10465
+ categories: {
10466
+ endpoint: MOCK_CATALOG_ENDPOINT,
10467
+ appliedQuery,
10468
+ ...scopeField
10469
+ },
10470
+ collections: {
10471
+ endpoint: MOCK_CATALOG_ENDPOINT,
10472
+ appliedQuery,
10473
+ ...scopeField
10474
+ }
10475
+ },
10476
+ heldReasons: {
10477
+ price: `${MOCK_CATALOG_ENDPOINT} is the mock basic listing; price filtering is not implemented in mock mode`,
10478
+ inStock: `${MOCK_CATALOG_ENDPOINT} is the mock basic listing; stock filtering is not implemented in mock mode`
10479
+ }
10480
+ };
10481
+ }
10482
+ function unsupportedMockCatalogOutcome(fields) {
10483
+ return {
10484
+ ok: false,
10485
+ error: {
10486
+ code: "unsupported-query",
10487
+ fields,
10488
+ message: `Unsupported catalog query in mock mode: ${fields.join(", ")}`,
10489
+ repair: { remove: fields }
10490
+ }
10491
+ };
10492
+ }
10493
+ function sortMockCatalogProducts(products, sortKey) {
10494
+ const sorted = [...products];
10495
+ if (sortKey === "name") {
10496
+ sorted.sort((left, right) => left.title.localeCompare(right.title));
10497
+ } else if (sortKey === "newest") {
10498
+ sorted.sort((left, right) => right.createdAt.localeCompare(left.createdAt));
10499
+ }
10500
+ return sorted;
10501
+ }
9581
10502
  function resolveVariant(currencyCode, merchandiseId) {
9582
10503
  const products = buildProducts(currencyCode);
9583
10504
  for (const product of products) {
@@ -9642,11 +10563,22 @@ function buildExternalCart(state, currencyCode, siteUrl) {
9642
10563
  checkoutUrl: `${siteUrl}/checkout?cart=${state.id}`,
9643
10564
  cost: {
9644
10565
  subtotalAmount: createMoney(subtotal, regionCurrency),
9645
- totalAmount: createMoney(total, regionCurrency),
9646
- totalTaxAmount: createMoney(totalTax, regionCurrency)
10566
+ discountAmount: createMoney(discount, regionCurrency),
10567
+ totalTaxAmount: createMoney(totalTax, regionCurrency),
10568
+ shippingAmount: createMoney(shipping, regionCurrency),
10569
+ totalAmount: createMoney(total, regionCurrency)
9647
10570
  },
9648
10571
  lines,
9649
10572
  totalQuantity: lines.reduce((sum, line) => sum + line.quantity, 0),
10573
+ salesChannelId: MOCK_SALES_CHANNEL_ID,
10574
+ regionId: state.regionId,
10575
+ currencyCode: regionCurrency.toUpperCase(),
10576
+ selectedShippingMethodId: state.shippingMethodId,
10577
+ // The mock method id IS the shipping option id (the value returned by
10578
+ // `getMockShippingMethods` and accepted by `addShippingMethod`), so the
10579
+ // canonical option identity mirrors the real adapter's `so_` field and the
10580
+ // checkout UI can highlight the selected option.
10581
+ selectedShippingOptionId: state.shippingMethodId,
9650
10582
  completedAt: state.completedAt
9651
10583
  };
9652
10584
  }
@@ -9702,6 +10634,69 @@ function getMockProducts(options) {
9702
10634
  const sorted = sortProducts(filtered, options?.sortKey, options?.reverse);
9703
10635
  return paginateProducts(sorted, options?.skip, options?.first);
9704
10636
  }
10637
+ function getMockCatalogProducts(query, options = {}) {
10638
+ if (query.sort !== void 0 && !MOCK_CATALOG_SORT_KEYS.includes(query.sort)) {
10639
+ return unsupportedMockCatalogOutcome(["sort"]);
10640
+ }
10641
+ const region = getRegionFixture(options.regionId);
10642
+ const currencyCode = options.currencyCode ?? region.currencyCode;
10643
+ const allProducts = buildProducts(currencyCode);
10644
+ const facetSupport = buildMockFacetSupport(query);
10645
+ const requestedAdvanced = collectRequestedAdvancedFields2(query);
10646
+ const heldAdvanced = requestedAdvanced.filter(
10647
+ (field) => !facetSupport.offered.includes(advancedFieldToFacet2(field))
10648
+ );
10649
+ if (heldAdvanced.length > 0) {
10650
+ return unsupportedMockCatalogOutcome(heldAdvanced);
10651
+ }
10652
+ const effectiveCategoryHandles = resolveEffectiveCategoryHandles2(query);
10653
+ const emptyIntersection = effectiveCategoryHandles !== void 0 && effectiveCategoryHandles.length === 0;
10654
+ const categoryFilterEmpty = effectiveCategoryHandles !== void 0 && !effectiveCategoryHandles.some(
10655
+ (handle) => categoryFixtures.some(
10656
+ (category) => category.handle === handle || category.id === handle
10657
+ )
10658
+ );
10659
+ const collectionFilterEmpty = query.collections !== void 0 && !query.collections.some(
10660
+ (handle) => collectionFixtures.some(
10661
+ (collection) => collection.handle === handle || collection.id === handle
10662
+ )
10663
+ );
10664
+ if (emptyIntersection || categoryFilterEmpty || collectionFilterEmpty) {
10665
+ return {
10666
+ ok: true,
10667
+ results: {
10668
+ products: [],
10669
+ appliedFilters: buildAppliedCatalogFilters2(
10670
+ query,
10671
+ effectiveCategoryHandles
10672
+ ),
10673
+ facetSupport
10674
+ }
10675
+ };
10676
+ }
10677
+ const filtered = filterProducts(allProducts, {
10678
+ query: query.text,
10679
+ categoryIds: effectiveCategoryHandles,
10680
+ collectionIds: query.collections
10681
+ });
10682
+ const sorted = sortMockCatalogProducts(filtered, query.sort);
10683
+ const pageSize = query.pageSize ?? MOCK_CATALOG_PAGE_SIZE;
10684
+ const page = query.page ?? 1;
10685
+ const offset = (page - 1) * pageSize;
10686
+ return {
10687
+ ok: true,
10688
+ results: {
10689
+ products: sorted.slice(offset, offset + pageSize),
10690
+ // The full matching fixture count, never the page length.
10691
+ total: filtered.length,
10692
+ appliedFilters: buildAppliedCatalogFilters2(
10693
+ query,
10694
+ effectiveCategoryHandles
10695
+ ),
10696
+ facetSupport
10697
+ }
10698
+ };
10699
+ }
9705
10700
  function getMockProduct(handle, regionId) {
9706
10701
  const region = getRegionFixture(regionId);
9707
10702
  return buildProducts(region.currencyCode).find(
@@ -9814,6 +10809,17 @@ function getMockPaymentMethods(currencyCode) {
9814
10809
  isEnabled: true,
9815
10810
  requiresSetup: false,
9816
10811
  description: "Mock cash payment option for checkout prototypes."
10812
+ },
10813
+ {
10814
+ // The single approved manual TEST provider used by the real Medusa
10815
+ // backend, mirrored in mock mode so the guest TEST purchase path is
10816
+ // exercisable without a backend.
10817
+ id: "pp_system_default",
10818
+ name: "Manual TEST payment",
10819
+ type: "cash_on_delivery",
10820
+ isEnabled: true,
10821
+ requiresSetup: false,
10822
+ description: "Manual system TEST provider (bookkeeping only; not external funds)."
9817
10823
  }
9818
10824
  ];
9819
10825
  }
@@ -9907,6 +10913,7 @@ var MockProvider = class {
9907
10913
  version = "1.0.0";
9908
10914
  capabilities = MOCK_CAPABILITIES;
9909
10915
  isMock = true;
10916
+ supportedCatalogSortKeys = MOCK_CATALOG_SORT_KEYS;
9910
10917
  currencyCode;
9911
10918
  siteUrl;
9912
10919
  constructor(config = {}) {
@@ -9937,6 +10944,18 @@ var MockProvider = class {
9937
10944
  regionId: options?.regionId
9938
10945
  });
9939
10946
  }
10947
+ /**
10948
+ * Canonical catalog query path (E2 task 2.5).
10949
+ *
10950
+ * Delegates to the fixture-backed canonical implementation so mock mode is a
10951
+ * faithful stand-in for the same contract the Medusa adapter honors: scope ∩
10952
+ * categories, collection resolution, global ordering before pagination, the
10953
+ * real full match count, and a typed `unsupported-query` for advanced filters
10954
+ * the mock does not implement.
10955
+ */
10956
+ async getCatalogProducts(query) {
10957
+ return getMockCatalogProducts(query, { currencyCode: this.currencyCode });
10958
+ }
9940
10959
  async getProductRecommendations(productId) {
9941
10960
  return getMockProductRecommendations(productId);
9942
10961
  }
@@ -10072,6 +11091,25 @@ var MockProvider = class {
10072
11091
  const order = completeMockCheckout(cart, this.currencyCode, this.siteUrl);
10073
11092
  return order;
10074
11093
  }
11094
+ /**
11095
+ * Discriminated completion for the fixture provider.
11096
+ *
11097
+ * Completion is idempotent by construction (the fixture order id derives from
11098
+ * the cart id), so completing an already-completed cart returns the same
11099
+ * persisted order — mirroring the native reconcile path without a second
11100
+ * order.
11101
+ */
11102
+ async completeCart(cartId) {
11103
+ const cart = getMockCartState(cartId);
11104
+ if (!cart) {
11105
+ return {
11106
+ type: "unresolved",
11107
+ error: { message: `Cart not found: ${cartId}`, code: "CART_NOT_FOUND", status: 404 }
11108
+ };
11109
+ }
11110
+ const order = completeMockCheckout(cart, this.currencyCode, this.siteUrl);
11111
+ return { type: "order", order };
11112
+ }
10075
11113
  async getShippingMethods(cartId) {
10076
11114
  const cart = getMockCartState(cartId);
10077
11115
  return getMockShippingMethods(cart?.regionId);
@@ -10196,6 +11234,113 @@ var MockProvider = class {
10196
11234
  }
10197
11235
  };
10198
11236
 
11237
+ // src/factory/provider-types.ts
11238
+ var SupportedProviderType = /* @__PURE__ */ ((SupportedProviderType2) => {
11239
+ SupportedProviderType2["Mock"] = "mock";
11240
+ SupportedProviderType2["Medusa"] = "medusa";
11241
+ SupportedProviderType2["StelOrder"] = "stelorder";
11242
+ SupportedProviderType2["Shopify"] = "shopify";
11243
+ SupportedProviderType2["BigCommerce"] = "bigcommerce";
11244
+ SupportedProviderType2["WooCommerce"] = "woocommerce";
11245
+ SupportedProviderType2["Spree"] = "spree";
11246
+ SupportedProviderType2["Magento"] = "magento";
11247
+ return SupportedProviderType2;
11248
+ })(SupportedProviderType || {});
11249
+ var PROVIDER_METADATA = {
11250
+ mock: {
11251
+ name: "Mock",
11252
+ description: "Fixture-backed runtime provider for layout/design mode without a real backend",
11253
+ requiresStorefront: false,
11254
+ requiredEnvVars: [],
11255
+ maxRetries: 0
11256
+ },
11257
+ medusa: {
11258
+ name: "Medusa JS",
11259
+ description: "Medusa v2 commerce engine",
11260
+ requiresStorefront: true,
11261
+ requiredEnvVars: [
11262
+ "NEXT_PUBLIC_COMMERCE_API_URL",
11263
+ "NEXT_PUBLIC_COMMERCE_API_KEY",
11264
+ "NEXT_PUBLIC_SALES_CHANNEL_ID"
11265
+ ],
11266
+ maxRetries: 3
11267
+ },
11268
+ stelorder: {
11269
+ name: "Stel Order",
11270
+ description: "Stel Order ERP and sales document API",
11271
+ requiresStorefront: false,
11272
+ requiredEnvVars: [
11273
+ "NEXT_PUBLIC_COMMERCE_API_URL",
11274
+ "NEXT_PUBLIC_COMMERCE_API_KEY"
11275
+ ],
11276
+ maxRetries: 2
11277
+ },
11278
+ shopify: {
11279
+ name: "Shopify",
11280
+ description: "Shopify Storefront API (GraphQL)",
11281
+ requiresStorefront: false,
11282
+ requiredEnvVars: [
11283
+ "NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN",
11284
+ "NEXT_PUBLIC_SHOPIFY_STOREFRONT_TOKEN"
11285
+ ],
11286
+ maxRetries: 3
11287
+ },
11288
+ bigcommerce: {
11289
+ name: "BigCommerce",
11290
+ description: "BigCommerce REST Storefront API",
11291
+ requiresStorefront: false,
11292
+ requiredEnvVars: [
11293
+ "BIGCOMMERCE_STORE_HASH",
11294
+ "BIGCOMMERCE_STOREFRONT_API_TOKEN",
11295
+ "BIGCOMMERCE_CHANNEL_ID"
11296
+ ],
11297
+ maxRetries: 3
11298
+ },
11299
+ woocommerce: {
11300
+ name: "WooCommerce",
11301
+ description: "WooCommerce Store API + REST API v3",
11302
+ requiresStorefront: false,
11303
+ requiredEnvVars: [
11304
+ "WOOCOMMERCE_URL",
11305
+ "WOOCOMMERCE_CONSUMER_KEY",
11306
+ "WOOCOMMERCE_CONSUMER_SECRET"
11307
+ ],
11308
+ maxRetries: 3
11309
+ },
11310
+ spree: {
11311
+ name: "Spree Commerce",
11312
+ description: "Spree API v2 Storefront (JSON:API)",
11313
+ requiresStorefront: false,
11314
+ requiredEnvVars: [
11315
+ "SPREE_API_URL"
11316
+ ],
11317
+ maxRetries: 3
11318
+ },
11319
+ magento: {
11320
+ name: "Adobe Commerce (Magento)",
11321
+ description: "Adobe Commerce GraphQL + REST API",
11322
+ requiresStorefront: true,
11323
+ requiredEnvVars: [
11324
+ "MAGENTO_URL",
11325
+ "MAGENTO_STORE_CODE"
11326
+ ],
11327
+ maxRetries: 3
11328
+ }
11329
+ };
11330
+ function isSupportedProviderType(value) {
11331
+ return typeof value === "string" && Object.values(SupportedProviderType).includes(value);
11332
+ }
11333
+ function getProviderMetadata(type) {
11334
+ if (!isSupportedProviderType(type)) {
11335
+ throw new Error(
11336
+ `Unsupported provider: ${type}. Supported: ${Object.values(
11337
+ SupportedProviderType
11338
+ ).join(", ")}`
11339
+ );
11340
+ }
11341
+ return PROVIDER_METADATA[type];
11342
+ }
11343
+
10199
11344
  // src/factory/index.ts
10200
11345
  function createProvider(options) {
10201
11346
  if (!options || !options.provider) {
@@ -10245,11 +11390,13 @@ export {
10245
11390
  MAGENTO_CAPABILITIES,
10246
11391
  MEDUSA_CAPABILITIES,
10247
11392
  MOCK_CAPABILITIES,
11393
+ MOCK_SALES_CHANNEL_ID,
10248
11394
  MagentoProvider,
10249
11395
  MedusaMetadataAdapter,
10250
11396
  MedusaProvider,
10251
11397
  MetricsService,
10252
11398
  MockProvider,
11399
+ PROVIDER_METADATA,
10253
11400
  ProviderAPIError,
10254
11401
  ProviderNotFoundError,
10255
11402
  ResourceNotFoundError,
@@ -10259,7 +11406,8 @@ export {
10259
11406
  ShopifyProvider,
10260
11407
  SpreeProvider,
10261
11408
  StelOrderProvider,
10262
- StorefrontConfigError2 as StorefrontConfigError,
11409
+ StorefrontConfigError,
11410
+ SupportedProviderType,
10263
11411
  WOOCOMMERCE_CAPABILITIES,
10264
11412
  WooCommerceProvider,
10265
11413
  assertEntityBelongsToChannel,
@@ -10278,10 +11426,12 @@ export {
10278
11426
  getBackendProviderId,
10279
11427
  getCapabilityDescription,
10280
11428
  getChannelScope,
11429
+ getProviderMetadata,
10281
11430
  isBackendCapabilities,
10282
11431
  isGlobalEntity,
10283
11432
  isProviderType,
10284
11433
  isScopedToChannel,
11434
+ isSupportedProviderType,
10285
11435
  moneyToNumber,
10286
11436
  moneyToNumberSafe,
10287
11437
  numberToMoney,