@thorprovider/adapters 4.1.0 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4,6 +4,31 @@ import {
4
4
  } from "@thorprovider/types";
5
5
 
6
6
  // src/types/capabilities.types.ts
7
+ var MOCK_CAPABILITIES = {
8
+ updateProfile: false,
9
+ updateEmail: false,
10
+ changePasswordDirect: false,
11
+ changePasswordViaEmail: false,
12
+ deleteAccount: false,
13
+ uploadAvatar: false,
14
+ avatarViaMetadata: false,
15
+ customAttributes: false,
16
+ fetchOrders: true,
17
+ cancelOrder: true,
18
+ manageAddresses: false,
19
+ defaultAddress: false,
20
+ applyDiscounts: true,
21
+ shippingCalculation: true,
22
+ guestCheckout: true,
23
+ savedPaymentMethods: false,
24
+ listPaymentProviders: true,
25
+ regionSpecificPayments: true,
26
+ wishlist: false,
27
+ advancedSearch: false,
28
+ facetedFilters: false,
29
+ productReviews: false,
30
+ loyaltyProgram: false
31
+ };
7
32
  var MEDUSA_CAPABILITIES = {
8
33
  // Profile Management
9
34
  updateProfile: true,
@@ -46,6 +71,41 @@ var MEDUSA_CAPABILITIES = {
46
71
  loyaltyProgram: false
47
72
  // Requires custom implementation
48
73
  };
74
+ var STELORDER_CAPABILITIES = {
75
+ // Profile Management
76
+ updateProfile: false,
77
+ updateEmail: false,
78
+ changePasswordDirect: false,
79
+ changePasswordViaEmail: false,
80
+ deleteAccount: false,
81
+ // Avatar
82
+ uploadAvatar: false,
83
+ avatarViaMetadata: false,
84
+ // Custom Attributes
85
+ customAttributes: false,
86
+ // Orders
87
+ fetchOrders: true,
88
+ cancelOrder: false,
89
+ // Addresses
90
+ manageAddresses: true,
91
+ defaultAddress: false,
92
+ // Cart/Checkout
93
+ applyDiscounts: false,
94
+ shippingCalculation: false,
95
+ guestCheckout: false,
96
+ savedPaymentMethods: false,
97
+ listPaymentProviders: true,
98
+ regionSpecificPayments: false,
99
+ // Wishlist
100
+ wishlist: false,
101
+ // Search
102
+ advancedSearch: false,
103
+ facetedFilters: false,
104
+ // Reviews
105
+ productReviews: false,
106
+ // Loyalty
107
+ loyaltyProgram: false
108
+ };
49
109
  var SHOPIFY_CAPABILITIES = {
50
110
  // Profile Management
51
111
  updateProfile: true,
@@ -7952,6 +8012,2036 @@ var MagentoProvider = class {
7952
8012
  }
7953
8013
  };
7954
8014
 
8015
+ // src/providers/stelorder/transforms.ts
8016
+ function normalizeStelCollection(payload) {
8017
+ if (!payload) {
8018
+ return [];
8019
+ }
8020
+ return Array.isArray(payload) ? payload : [payload];
8021
+ }
8022
+ function normalizeStelEntity(payload) {
8023
+ if (!payload) {
8024
+ return void 0;
8025
+ }
8026
+ return Array.isArray(payload) ? payload[0] : payload;
8027
+ }
8028
+ function transformStelMoney(amount, currencyCode = "USD") {
8029
+ const normalizedAmount = typeof amount === "string" ? Number.parseFloat(amount) : amount ?? 0;
8030
+ return {
8031
+ amount: Number.isFinite(normalizedAmount) ? normalizedAmount.toFixed(2) : "0.00",
8032
+ currencyCode: currencyCode.toUpperCase()
8033
+ };
8034
+ }
8035
+ function transformStelImage(url, altText = "") {
8036
+ const normalizedUrl = url?.trim();
8037
+ if (!normalizedUrl) {
8038
+ return void 0;
8039
+ }
8040
+ return {
8041
+ url: normalizedUrl,
8042
+ altText,
8043
+ width: 800,
8044
+ height: 800
8045
+ };
8046
+ }
8047
+ function normalizeStelDate(value) {
8048
+ if (!value) {
8049
+ return (/* @__PURE__ */ new Date()).toISOString();
8050
+ }
8051
+ const parsed = new Date(value);
8052
+ return Number.isNaN(parsed.getTime()) ? (/* @__PURE__ */ new Date()).toISOString() : parsed.toISOString();
8053
+ }
8054
+ function toStelStringId(value) {
8055
+ if (value === null || value === void 0) {
8056
+ return "";
8057
+ }
8058
+ return String(value);
8059
+ }
8060
+ function slugify(value) {
8061
+ return value.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
8062
+ }
8063
+ function buildStelHandle(...candidates) {
8064
+ for (const candidate of candidates) {
8065
+ if (candidate === null || candidate === void 0) {
8066
+ continue;
8067
+ }
8068
+ const normalized = slugify(String(candidate).trim());
8069
+ if (normalized) {
8070
+ return normalized;
8071
+ }
8072
+ }
8073
+ return "stel-item";
8074
+ }
8075
+ function transformStelProductImages(product) {
8076
+ const images = [];
8077
+ if (!product["item-images"]) {
8078
+ return images;
8079
+ }
8080
+ const sorted = [...product["item-images"]].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
8081
+ for (const img of sorted) {
8082
+ const transformed = transformStelImage(img["item-image-path"], product.name ?? "");
8083
+ if (transformed) {
8084
+ images.push(transformed);
8085
+ }
8086
+ }
8087
+ return images;
8088
+ }
8089
+ function deriveStelStockStatus(product) {
8090
+ if (!product["stock-enabled"]) {
8091
+ return "in_stock";
8092
+ }
8093
+ const realStock = product["real-stock"] ?? 0;
8094
+ const minimumStock = product["minimum-stock"] ?? 0;
8095
+ if (realStock <= 0) {
8096
+ return "out_of_stock";
8097
+ }
8098
+ if (realStock <= minimumStock) {
8099
+ return "low_stock";
8100
+ }
8101
+ return "in_stock";
8102
+ }
8103
+ function buildSyntheticVariant(product, currencyCode) {
8104
+ const price = transformStelMoney(product["sales-price"], currencyCode);
8105
+ const stockStatus = deriveStelStockStatus(product);
8106
+ const quantityAvailable = product["stock-enabled"] ? product["real-stock"] ?? 0 : void 0;
8107
+ const image = product["item-images"]?.[0] ? transformStelImage(product["item-images"][0]["item-image-path"], product.name ?? "") : void 0;
8108
+ return {
8109
+ id: toStelStringId(product.id),
8110
+ title: "Default",
8111
+ sku: product.barcode ?? product["full-reference"] ?? void 0,
8112
+ availableForSale: stockStatus !== "out_of_stock",
8113
+ selectedOptions: [],
8114
+ price,
8115
+ compareAtPrice: void 0,
8116
+ quantityAvailable,
8117
+ stockStatus,
8118
+ image
8119
+ };
8120
+ }
8121
+ function transformStelProduct(raw, currencyCode) {
8122
+ const id = toStelStringId(raw.id);
8123
+ const handle = buildStelHandle(raw["full-reference"], raw.reference, raw.name, raw.id);
8124
+ const price = transformStelMoney(raw["sales-price"], currencyCode);
8125
+ const images = transformStelProductImages(raw);
8126
+ const variant = buildSyntheticVariant(raw, currencyCode);
8127
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8128
+ return {
8129
+ id,
8130
+ handle,
8131
+ title: raw.name ?? "",
8132
+ description: raw.description ?? "",
8133
+ availableForSale: variant.availableForSale,
8134
+ options: [],
8135
+ variants: [variant],
8136
+ featuredImage: images[0],
8137
+ images,
8138
+ priceRange: {
8139
+ minVariantPrice: price,
8140
+ maxVariantPrice: price
8141
+ },
8142
+ productType: void 0,
8143
+ vendor: void 0,
8144
+ tags: raw.promotional ? ["promotional"] : [],
8145
+ createdAt: normalizeStelDate(raw["creation-date"]),
8146
+ updatedAt: normalizeStelDate(raw["utc-last-modification-date"]) || now,
8147
+ metadata: {
8148
+ stelFullReference: raw["full-reference"],
8149
+ stelReference: raw.reference,
8150
+ stelBarcode: raw.barcode,
8151
+ stelCategoryId: raw["product-category-id"],
8152
+ stelInactive: raw.inactive,
8153
+ stelPromotional: raw.promotional,
8154
+ stelPurchasePrice: raw["purchase-price"]
8155
+ }
8156
+ };
8157
+ }
8158
+ function transformStelCategory(raw) {
8159
+ const id = toStelStringId(raw.id);
8160
+ const handle = buildStelHandle(raw.slug, raw.name, raw.id);
8161
+ return {
8162
+ id,
8163
+ name: raw.name ?? "",
8164
+ handle,
8165
+ description: raw.description ?? void 0,
8166
+ parentCategoryId: raw["parent-category-id"] ? toStelStringId(raw["parent-category-id"]) : void 0,
8167
+ metadata: {
8168
+ stelSlug: raw.slug
8169
+ }
8170
+ };
8171
+ }
8172
+ function transformStelCategoryToCollection(raw) {
8173
+ const id = toStelStringId(raw.id);
8174
+ const handle = buildStelHandle(raw.slug, raw.name, raw.id);
8175
+ return {
8176
+ id,
8177
+ handle,
8178
+ title: raw.name ?? "",
8179
+ description: raw.description ?? "",
8180
+ path: `/collections/${handle}`,
8181
+ updatedAt: normalizeStelDate(raw["utc-last-modification-date"])
8182
+ };
8183
+ }
8184
+ function transformStelWarehouseToStockLocation(raw) {
8185
+ return {
8186
+ id: toStelStringId(raw.id),
8187
+ name: raw.name ?? "Warehouse"
8188
+ };
8189
+ }
8190
+ function transformStelProductWarehouseToInventoryLevel(pw) {
8191
+ return {
8192
+ locationId: toStelStringId(pw["warehouse-id"]),
8193
+ locationName: pw["warehouse-path"] ?? `Warehouse ${pw["warehouse-id"] ?? "unknown"}`,
8194
+ availableQuantity: pw["real-stock"] ?? 0,
8195
+ reservedQuantity: Math.max(0, (pw["virtual-stock"] ?? 0) - (pw["real-stock"] ?? 0)),
8196
+ stockedQuantity: pw["virtual-stock"] ?? pw["real-stock"] ?? 0
8197
+ };
8198
+ }
8199
+ function splitStelName(fullName) {
8200
+ if (!fullName?.trim()) {
8201
+ return { firstName: "", lastName: "" };
8202
+ }
8203
+ const parts = fullName.trim().split(/\s+/);
8204
+ const firstName = parts[0] ?? "";
8205
+ const lastName = parts.length > 1 ? parts.slice(1).join(" ") : "";
8206
+ return { firstName, lastName };
8207
+ }
8208
+ function transformStelClient(raw) {
8209
+ const { firstName, lastName } = splitStelName(raw.name ?? raw["business-name"]);
8210
+ return {
8211
+ id: toStelStringId(raw.id),
8212
+ email: raw.email ?? "",
8213
+ firstName: firstName || null,
8214
+ lastName: lastName || null,
8215
+ phone: raw.phone ?? raw.mobile ?? null,
8216
+ hasAccount: true,
8217
+ createdAt: normalizeStelDate(raw["utc-last-modification-date"]),
8218
+ updatedAt: normalizeStelDate(raw["utc-last-modification-date"]),
8219
+ metadata: {
8220
+ stelBusinessName: raw["business-name"],
8221
+ stelRateId: raw["rate-id"],
8222
+ stelPaymentOptionId: raw["payment-option-id"],
8223
+ stelPaymentTermId: raw["payment-term-id"],
8224
+ stelDeliveryOptionId: raw["delivery-option-id"]
8225
+ }
8226
+ };
8227
+ }
8228
+ function deriveStelOrderStatus(raw) {
8229
+ if (raw.deleted) {
8230
+ return "cancelled";
8231
+ }
8232
+ const status = (raw.status ?? "").toLowerCase();
8233
+ if (status.includes("cancel") || status.includes("anulad")) {
8234
+ return "cancelled";
8235
+ }
8236
+ if (status.includes("complet") || status.includes("cerrad") || status.includes("settled")) {
8237
+ return "completed";
8238
+ }
8239
+ if (status.includes("process") || status.includes("confirm")) {
8240
+ return "processing";
8241
+ }
8242
+ return "pending";
8243
+ }
8244
+ function deriveStelPaymentStatus(raw) {
8245
+ const orderStatus = deriveStelOrderStatus(raw);
8246
+ if (orderStatus === "completed") {
8247
+ return "paid";
8248
+ }
8249
+ if (orderStatus === "cancelled") {
8250
+ return "pending";
8251
+ }
8252
+ return "pending";
8253
+ }
8254
+ function deriveStelFulfillmentStatus(raw) {
8255
+ const orderStatus = deriveStelOrderStatus(raw);
8256
+ if (orderStatus === "completed") {
8257
+ return "fulfilled";
8258
+ }
8259
+ return "unfulfilled";
8260
+ }
8261
+ function transformStelDocumentLine(line, index, currencyCode) {
8262
+ const unitPrice = line["item-base-price"] ?? 0;
8263
+ const quantity = line.units ?? 1;
8264
+ const lineTotal = unitPrice * quantity;
8265
+ return {
8266
+ id: toStelStringId(line["item-id"] ?? index),
8267
+ title: line["item-name"] ?? "",
8268
+ variantTitle: void 0,
8269
+ quantity,
8270
+ price: transformStelMoney(unitPrice, currencyCode),
8271
+ total: transformStelMoney(lineTotal, currencyCode),
8272
+ sku: void 0,
8273
+ productId: line["item-id"] ? toStelStringId(line["item-id"]) : void 0
8274
+ };
8275
+ }
8276
+ function transformStelSalesOrder(raw, currencyCode) {
8277
+ const id = toStelStringId(raw.id);
8278
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8279
+ const items = (raw["document-lines"] ?? []).filter((line) => line["line-type"] === "ITEM" || !line["line-type"]).map((line, i) => transformStelDocumentLine(line, i, currencyCode));
8280
+ const status = deriveStelOrderStatus(raw);
8281
+ return {
8282
+ id,
8283
+ orderNumber: raw.reference ?? id,
8284
+ email: raw.email ?? "",
8285
+ status,
8286
+ paymentStatus: deriveStelPaymentStatus(raw),
8287
+ fulfillmentStatus: deriveStelFulfillmentStatus(raw),
8288
+ customerId: raw["client-id"] ? toStelStringId(raw["client-id"]) : void 0,
8289
+ items,
8290
+ subtotal: transformStelMoney(raw["total-base"], currencyCode),
8291
+ total: transformStelMoney(raw.total, currencyCode),
8292
+ tax: raw["total-tax"] != null ? transformStelMoney(raw["total-tax"], currencyCode) : void 0,
8293
+ createdAt: normalizeStelDate(raw["creation-date"]),
8294
+ updatedAt: normalizeStelDate(raw["utc-last-modification-date"]) || now,
8295
+ cancelledAt: status === "cancelled" ? normalizeStelDate(raw["utc-last-modification-date"]) : void 0,
8296
+ completedAt: status === "completed" ? normalizeStelDate(raw["utc-last-modification-date"]) : void 0,
8297
+ metadata: {
8298
+ stelReference: raw.reference,
8299
+ stelStatus: raw.status,
8300
+ stelPaymentOptionId: raw["payment-option-id"],
8301
+ stelPaymentTermId: raw["payment-term-id"],
8302
+ stelDeliveryOptionId: raw["delivery-option-id"]
8303
+ }
8304
+ };
8305
+ }
8306
+ function inferPaymentMethodType(name) {
8307
+ if (!name) {
8308
+ return "other";
8309
+ }
8310
+ const lower = name.toLowerCase();
8311
+ if (lower.includes("transfer") || lower.includes("bank") || lower.includes("sepa") || lower.includes("iban")) {
8312
+ return "bank_transfer";
8313
+ }
8314
+ if (lower.includes("card") || lower.includes("tarjeta") || lower.includes("visa") || lower.includes("master")) {
8315
+ return "card";
8316
+ }
8317
+ if (lower.includes("paypal") || lower.includes("wallet") || lower.includes("apple") || lower.includes("google")) {
8318
+ return "wallet";
8319
+ }
8320
+ if (lower.includes("cash") || lower.includes("contrar") || lower.includes("efectivo") || lower.includes("cod")) {
8321
+ return "cash_on_delivery";
8322
+ }
8323
+ if (lower.includes("crypto") || lower.includes("bitcoin")) {
8324
+ return "crypto";
8325
+ }
8326
+ return "other";
8327
+ }
8328
+ function transformStelPaymentOption(raw) {
8329
+ return {
8330
+ id: toStelStringId(raw.id),
8331
+ name: raw.name ?? "Payment Option",
8332
+ type: inferPaymentMethodType(raw.name),
8333
+ isEnabled: !raw.deleted,
8334
+ requiresSetup: false,
8335
+ description: raw.description ?? void 0,
8336
+ metadata: {
8337
+ stelPath: raw.path,
8338
+ source: "paymentOption"
8339
+ }
8340
+ };
8341
+ }
8342
+ function transformStelDeliveryOption(raw, currencyCode) {
8343
+ return {
8344
+ id: toStelStringId(raw.id),
8345
+ name: raw.name ?? "Delivery Option",
8346
+ price: transformStelMoney(0, currencyCode),
8347
+ description: raw.description ?? void 0
8348
+ };
8349
+ }
8350
+
8351
+ // src/providers/stelorder/client.ts
8352
+ var DEFAULT_RETRY_CONFIG2 = {
8353
+ maxRetries: 2,
8354
+ initialDelayMs: 300,
8355
+ backoffMultiplier: 2,
8356
+ maxDelayMs: 5e3,
8357
+ timeoutMs: 1e4,
8358
+ retryableStatusCodes: [408, 429, 500, 502, 503, 504]
8359
+ };
8360
+ function sleep2(ms) {
8361
+ return new Promise((resolve) => setTimeout(resolve, ms));
8362
+ }
8363
+ function calculateDelay2(attempt, retryConfig) {
8364
+ const delay = retryConfig.initialDelayMs * Math.pow(retryConfig.backoffMultiplier, attempt);
8365
+ return Math.min(delay, retryConfig.maxDelayMs);
8366
+ }
8367
+ function isRetryableError2(error, retryConfig) {
8368
+ if (error instanceof ProviderAPIError) {
8369
+ return typeof error.status === "number" && retryConfig.retryableStatusCodes.includes(error.status);
8370
+ }
8371
+ if (!(error instanceof Error)) {
8372
+ return false;
8373
+ }
8374
+ const message = error.message.toLowerCase();
8375
+ return error.name === "AbortError" || error.name === "TimeoutError" || message.includes("fetch failed") || message.includes("timeout") || message.includes("econnrefused") || message.includes("etimedout");
8376
+ }
8377
+ function createRetryingFetch(fetchImplementation, retryConfig, logger2) {
8378
+ return async (url, init) => {
8379
+ let lastError = new Error("Unknown STEL Order request error");
8380
+ for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt += 1) {
8381
+ const controller = new AbortController();
8382
+ const timeoutId = setTimeout(() => controller.abort(), retryConfig.timeoutMs);
8383
+ try {
8384
+ const response = await fetchImplementation(url, {
8385
+ ...init,
8386
+ signal: controller.signal
8387
+ });
8388
+ clearTimeout(timeoutId);
8389
+ if (!response.ok && retryConfig.retryableStatusCodes.includes(response.status)) {
8390
+ throw new ProviderAPIError(
8391
+ `STEL Order API error: ${response.status} ${response.statusText}`,
8392
+ "stelorder",
8393
+ response.status
8394
+ );
8395
+ }
8396
+ return response;
8397
+ } catch (error) {
8398
+ clearTimeout(timeoutId);
8399
+ lastError = error;
8400
+ if (attempt >= retryConfig.maxRetries || !isRetryableError2(error, retryConfig)) {
8401
+ throw error;
8402
+ }
8403
+ const delay = calculateDelay2(attempt, retryConfig);
8404
+ logger2.warn("STEL request failed, retrying.", {
8405
+ url,
8406
+ attempt: attempt + 1,
8407
+ maxAttempts: retryConfig.maxRetries + 1,
8408
+ nextRetryIn: delay,
8409
+ error: extractErrorMessage(error)
8410
+ });
8411
+ await sleep2(delay);
8412
+ }
8413
+ }
8414
+ throw lastError;
8415
+ };
8416
+ }
8417
+ async function parseErrorResponse(response) {
8418
+ const contentType = response.headers.get("content-type") ?? "";
8419
+ try {
8420
+ if (contentType.includes("application/json")) {
8421
+ const body = await response.json();
8422
+ const message = extractErrorMessage(body);
8423
+ if (message && message !== "An unknown error occurred") {
8424
+ return message;
8425
+ }
8426
+ }
8427
+ } catch {
8428
+ }
8429
+ try {
8430
+ const text = await response.text();
8431
+ if (text.trim()) {
8432
+ return text.trim();
8433
+ }
8434
+ } catch {
8435
+ }
8436
+ return `STEL Order API error: ${response.status} ${response.statusText}`;
8437
+ }
8438
+ function normalizeStelApiBaseUrl(baseUrl) {
8439
+ const trimmed = baseUrl.trim();
8440
+ if (!trimmed) {
8441
+ throw new ConfigurationError("Stel Order baseUrl is required.");
8442
+ }
8443
+ const normalized = trimmed.replace(/\/api\/openapi\.json$/i, "").replace(/\/+$/, "");
8444
+ return normalized.endsWith("/app") ? normalized : `${normalized}/app`;
8445
+ }
8446
+ var StelOrderClient = class {
8447
+ apiBaseUrl;
8448
+ apiKey;
8449
+ logger;
8450
+ retryConfig;
8451
+ fetchImplementation;
8452
+ constructor(config) {
8453
+ const apiKey = config.apiKey ?? config.publishableKey;
8454
+ if (!apiKey) {
8455
+ throw new ConfigurationError(
8456
+ "Stel Order API key is required. Pass `apiKey` or `publishableKey` to createProvider()."
8457
+ );
8458
+ }
8459
+ this.apiBaseUrl = normalizeStelApiBaseUrl(config.baseUrl);
8460
+ this.apiKey = apiKey;
8461
+ this.logger = createLogger("StelOrderClient", config.debug);
8462
+ this.retryConfig = {
8463
+ ...DEFAULT_RETRY_CONFIG2,
8464
+ ...config.retry
8465
+ };
8466
+ this.fetchImplementation = config.customFetch ? createRetryingFetch(config.customFetch, this.retryConfig, this.logger) : void 0;
8467
+ this.logger.info("Initializing Stel Order client", {
8468
+ apiBaseUrl: this.apiBaseUrl,
8469
+ retryConfig: this.retryConfig
8470
+ });
8471
+ }
8472
+ async list(resource, query) {
8473
+ const payload = await this.request({
8474
+ method: "GET",
8475
+ path: resource,
8476
+ query
8477
+ });
8478
+ return normalizeStelCollection(payload);
8479
+ }
8480
+ async getOne(resource, id, query) {
8481
+ const payload = await this.request({
8482
+ method: "GET",
8483
+ path: `${resource}/${id}`,
8484
+ query
8485
+ });
8486
+ return normalizeStelEntity(payload);
8487
+ }
8488
+ async create(resource, body) {
8489
+ return this.request({
8490
+ method: "POST",
8491
+ path: resource,
8492
+ body
8493
+ });
8494
+ }
8495
+ async update(resource, id, body) {
8496
+ return this.request({
8497
+ method: "PUT",
8498
+ path: `${resource}/${id}`,
8499
+ body
8500
+ });
8501
+ }
8502
+ async remove(resource, id) {
8503
+ await this.request({
8504
+ method: "DELETE",
8505
+ path: `${resource}/${id}`
8506
+ });
8507
+ }
8508
+ buildUrl(path, query) {
8509
+ const normalizedPath = path.replace(/^\/+/, "");
8510
+ const url = new URL(`${this.apiBaseUrl}/${normalizedPath}`);
8511
+ if (!query) {
8512
+ return url.toString();
8513
+ }
8514
+ for (const [key, value] of Object.entries(query)) {
8515
+ if (value === void 0 || value === null || value === "") {
8516
+ continue;
8517
+ }
8518
+ if (Array.isArray(value)) {
8519
+ url.searchParams.set(key, value.map(String).join(","));
8520
+ continue;
8521
+ }
8522
+ url.searchParams.set(key, String(value));
8523
+ }
8524
+ return url.toString();
8525
+ }
8526
+ buildHeaders(headers, hasBody = false) {
8527
+ const normalizedHeaders = new Headers(headers);
8528
+ normalizedHeaders.set("Accept", "application/json");
8529
+ normalizedHeaders.set("APIKEY", this.apiKey);
8530
+ if (hasBody && !normalizedHeaders.has("Content-Type")) {
8531
+ normalizedHeaders.set("Content-Type", "application/json");
8532
+ }
8533
+ return normalizedHeaders;
8534
+ }
8535
+ async executeFetch(url, init) {
8536
+ if (this.fetchImplementation) {
8537
+ return this.fetchImplementation(url, init);
8538
+ }
8539
+ return fetchWithRetry(url, init, this.retryConfig);
8540
+ }
8541
+ async request(options) {
8542
+ const url = this.buildUrl(options.path, options.query);
8543
+ const hasBody = options.body !== void 0;
8544
+ this.logger.debug("STEL request", {
8545
+ method: options.method,
8546
+ url
8547
+ });
8548
+ const response = await this.executeFetch(url, {
8549
+ method: options.method,
8550
+ headers: this.buildHeaders(options.headers, hasBody),
8551
+ body: hasBody ? JSON.stringify(options.body) : void 0
8552
+ });
8553
+ if (!response.ok) {
8554
+ const message = await parseErrorResponse(response);
8555
+ throw new ProviderAPIError(message, "stelorder", response.status);
8556
+ }
8557
+ if (response.status === 204) {
8558
+ return void 0;
8559
+ }
8560
+ const contentType = response.headers.get("content-type") ?? "";
8561
+ if (contentType.includes("application/json")) {
8562
+ return await response.json();
8563
+ }
8564
+ return await response.text();
8565
+ }
8566
+ };
8567
+
8568
+ // src/providers/stelorder/index.ts
8569
+ var StelOrderProvider = class {
8570
+ name = "stelorder";
8571
+ version = "1.0.0";
8572
+ capabilities = STELORDER_CAPABILITIES;
8573
+ client;
8574
+ logger;
8575
+ currencyCode;
8576
+ storefrontId;
8577
+ companyName;
8578
+ constructor(config) {
8579
+ this.client = new StelOrderClient(config);
8580
+ this.logger = createLogger("StelOrderProvider", config.debug);
8581
+ this.currencyCode = config.currencyCode ?? "USD";
8582
+ this.storefrontId = config.storefrontId ?? "stelorder-primary";
8583
+ this.companyName = config.companyName ?? "Stel Order";
8584
+ this.logger.info("Initializing Stel Order provider", {
8585
+ storefrontId: this.storefrontId,
8586
+ companyName: this.companyName,
8587
+ currencyCode: this.currencyCode
8588
+ });
8589
+ }
8590
+ // ============================================
8591
+ // Product Operations
8592
+ // ============================================
8593
+ async getProduct(handle, _options) {
8594
+ this.logger.debug("getProduct", { handle });
8595
+ try {
8596
+ if (/^\d+$/.test(handle)) {
8597
+ const raw = await this.client.getOne("products", handle);
8598
+ return raw ? transformStelProduct(raw, this.currencyCode) : void 0;
8599
+ }
8600
+ const rawProducts = await this.client.list("products", { limit: 100 });
8601
+ for (const raw of rawProducts) {
8602
+ const productHandle = buildStelHandle(raw["full-reference"], raw.reference, raw.name, raw.id);
8603
+ if (productHandle === handle) {
8604
+ return transformStelProduct(raw, this.currencyCode);
8605
+ }
8606
+ }
8607
+ return void 0;
8608
+ } catch (error) {
8609
+ this.logger.error("getProduct failed", { handle, error });
8610
+ throw this.wrapError("getProduct", error);
8611
+ }
8612
+ }
8613
+ async getProducts(options) {
8614
+ this.logger.debug("getProducts", { options });
8615
+ try {
8616
+ const query = {};
8617
+ if (options?.first) {
8618
+ query.limit = options.first;
8619
+ }
8620
+ if (options?.skip) {
8621
+ query.start = options.skip;
8622
+ }
8623
+ if (typeof options?.after === "number") {
8624
+ query.start = options.after;
8625
+ }
8626
+ if (options?.sortKey) {
8627
+ query.sort = options.reverse ? `-${options.sortKey}` : options.sortKey;
8628
+ }
8629
+ if (options?.categoryIds?.length) {
8630
+ query["product-category-id"] = `in:${options.categoryIds.join(",")}`;
8631
+ }
8632
+ const rawProducts = await this.client.list("products", query);
8633
+ let products = rawProducts.filter((p) => !p.deleted && !p.inactive).map((p) => transformStelProduct(p, this.currencyCode));
8634
+ if (options?.query) {
8635
+ const needle = options.query.toLowerCase();
8636
+ products = products.filter(
8637
+ (p) => p.title.toLowerCase().includes(needle) || p.description.toLowerCase().includes(needle) || p.handle.includes(needle)
8638
+ );
8639
+ }
8640
+ return products;
8641
+ } catch (error) {
8642
+ this.logger.error("getProducts failed", { options, error });
8643
+ throw this.wrapError("getProducts", error);
8644
+ }
8645
+ }
8646
+ async getProductRecommendations(_productId) {
8647
+ return [];
8648
+ }
8649
+ // ============================================
8650
+ // Category Operations
8651
+ // ============================================
8652
+ async getCategory(idOrHandle) {
8653
+ this.logger.debug("getCategory", { idOrHandle });
8654
+ try {
8655
+ if (/^\d+$/.test(idOrHandle)) {
8656
+ const raw = await this.client.getOne("productCategories", idOrHandle);
8657
+ return raw ? transformStelCategory(raw) : void 0;
8658
+ }
8659
+ const rawCategories = await this.client.list("productCategories");
8660
+ for (const raw of rawCategories) {
8661
+ const catHandle = buildStelHandle(raw.slug, raw.name, raw.id);
8662
+ if (catHandle === idOrHandle) {
8663
+ return transformStelCategory(raw);
8664
+ }
8665
+ }
8666
+ return void 0;
8667
+ } catch (error) {
8668
+ this.logger.error("getCategory failed", { idOrHandle, error });
8669
+ throw this.wrapError("getCategory", error);
8670
+ }
8671
+ }
8672
+ async getCategories(options) {
8673
+ this.logger.debug("getCategories", { options });
8674
+ try {
8675
+ if (options?.customFetcher) {
8676
+ return options.customFetcher(options);
8677
+ }
8678
+ const query = {};
8679
+ if (options?.limit) {
8680
+ query.limit = options.limit;
8681
+ }
8682
+ if (options?.parentCategoryId) {
8683
+ query["parent-category-id"] = options.parentCategoryId;
8684
+ }
8685
+ const rawCategories = await this.client.list("productCategories", query);
8686
+ let categories = rawCategories.filter((c) => !c.deleted).map(transformStelCategory);
8687
+ if (options?.query) {
8688
+ const needle = options.query.toLowerCase();
8689
+ categories = categories.filter(
8690
+ (c) => c.name.toLowerCase().includes(needle) || c.handle.includes(needle)
8691
+ );
8692
+ }
8693
+ return categories;
8694
+ } catch (error) {
8695
+ this.logger.error("getCategories failed", { options, error });
8696
+ throw this.wrapError("getCategories", error);
8697
+ }
8698
+ }
8699
+ async getCategoryProducts(handle, options) {
8700
+ this.logger.debug("getCategoryProducts", { handle, options });
8701
+ try {
8702
+ const category = await this.getCategory(handle);
8703
+ if (!category) {
8704
+ return [];
8705
+ }
8706
+ return this.getProducts({
8707
+ categoryIds: [category.id],
8708
+ first: options?.first,
8709
+ sortKey: options?.sortKey,
8710
+ reverse: options?.reverse,
8711
+ after: options?.after
8712
+ });
8713
+ } catch (error) {
8714
+ this.logger.error("getCategoryProducts failed", { handle, error });
8715
+ throw this.wrapError("getCategoryProducts", error);
8716
+ }
8717
+ }
8718
+ // ============================================
8719
+ // Collection Operations (alias categories)
8720
+ // ============================================
8721
+ async getCollection(handle) {
8722
+ this.logger.debug("getCollection", { handle });
8723
+ try {
8724
+ if (/^\d+$/.test(handle)) {
8725
+ const raw = await this.client.getOne("productCategories", handle);
8726
+ return raw ? transformStelCategoryToCollection(raw) : void 0;
8727
+ }
8728
+ const rawCategories = await this.client.list("productCategories");
8729
+ for (const raw of rawCategories) {
8730
+ const catHandle = buildStelHandle(raw.slug, raw.name, raw.id);
8731
+ if (catHandle === handle) {
8732
+ return transformStelCategoryToCollection(raw);
8733
+ }
8734
+ }
8735
+ return void 0;
8736
+ } catch (error) {
8737
+ this.logger.error("getCollection failed", { handle, error });
8738
+ throw this.wrapError("getCollection", error);
8739
+ }
8740
+ }
8741
+ async getCollections(options) {
8742
+ this.logger.debug("getCollections", { options });
8743
+ try {
8744
+ const query = {};
8745
+ if (options?.limit) {
8746
+ query.limit = options.limit;
8747
+ }
8748
+ const rawCategories = await this.client.list("productCategories", query);
8749
+ let collections = rawCategories.filter((c) => !c.deleted).map(transformStelCategoryToCollection);
8750
+ if (options?.query) {
8751
+ const needle = options.query.toLowerCase();
8752
+ collections = collections.filter(
8753
+ (c) => c.title.toLowerCase().includes(needle) || c.handle.includes(needle)
8754
+ );
8755
+ }
8756
+ return collections;
8757
+ } catch (error) {
8758
+ this.logger.error("getCollections failed", { options, error });
8759
+ throw this.wrapError("getCollections", error);
8760
+ }
8761
+ }
8762
+ async getCollectionProducts(handle, options) {
8763
+ return this.getCategoryProducts(handle, options);
8764
+ }
8765
+ // ============================================
8766
+ // Inventory Operations
8767
+ // ============================================
8768
+ async getStockLocations(_params) {
8769
+ this.logger.debug("getStockLocations");
8770
+ try {
8771
+ const rawWarehouses = await this.client.list("warehouses");
8772
+ return rawWarehouses.filter((w) => !w.deleted).map(transformStelWarehouseToStockLocation);
8773
+ } catch (error) {
8774
+ this.logger.error("getStockLocations failed", { error });
8775
+ throw this.wrapError("getStockLocations", error);
8776
+ }
8777
+ }
8778
+ async checkInventoryLevels(variantId, _salesChannelId) {
8779
+ this.logger.debug("checkInventoryLevels", { variantId });
8780
+ try {
8781
+ const raw = await this.client.getOne("products", variantId);
8782
+ if (!raw?.["product-warehouses"]?.length) {
8783
+ return [];
8784
+ }
8785
+ return raw["product-warehouses"].map(transformStelProductWarehouseToInventoryLevel);
8786
+ } catch (error) {
8787
+ this.logger.error("checkInventoryLevels failed", { variantId, error });
8788
+ throw this.wrapError("checkInventoryLevels", error);
8789
+ }
8790
+ }
8791
+ validateCartStock(_cartId) {
8792
+ return this.notSupported("validateCartStock");
8793
+ }
8794
+ getFulfillmentOptions(_cartId, _salesChannelId) {
8795
+ return this.notSupported("getFulfillmentOptions");
8796
+ }
8797
+ // ============================================
8798
+ // Cart Operations (unsupported — STEL is ERP, not storefront)
8799
+ // ============================================
8800
+ createCart(_options) {
8801
+ return this.notSupported("createCart");
8802
+ }
8803
+ getCart(_cartId) {
8804
+ return this.notSupported("getCart");
8805
+ }
8806
+ addToCart(_cartId, _lines) {
8807
+ return this.notSupported("addToCart");
8808
+ }
8809
+ removeFromCart(_cartId, _lineIds) {
8810
+ return this.notSupported("removeFromCart");
8811
+ }
8812
+ updateCart(_cartId, _lines) {
8813
+ return this.notSupported("updateCart");
8814
+ }
8815
+ // ============================================
8816
+ // Checkout Operations (unsupported)
8817
+ // ============================================
8818
+ completeCheckout(_cartId) {
8819
+ return this.notSupported("completeCheckout");
8820
+ }
8821
+ getRegionCountries(_regionId) {
8822
+ return this.notSupported("getRegionCountries");
8823
+ }
8824
+ addShippingMethod(_cartId, _methodId) {
8825
+ return this.notSupported("addShippingMethod");
8826
+ }
8827
+ initiatePaymentSession(_cartId, _providerId) {
8828
+ return this.notSupported("initiatePaymentSession");
8829
+ }
8830
+ applyDiscountCode(_cartId, _code) {
8831
+ return this.notSupported("applyDiscountCode");
8832
+ }
8833
+ removeDiscountCode(_cartId, _code) {
8834
+ return this.notSupported("removeDiscountCode");
8835
+ }
8836
+ // ============================================
8837
+ // Payment Methods
8838
+ // ============================================
8839
+ async getPaymentMethods(_options) {
8840
+ this.logger.debug("getPaymentMethods");
8841
+ try {
8842
+ const rawOptions = await this.client.list("paymentOptions");
8843
+ return rawOptions.filter((o) => !o.deleted).map(transformStelPaymentOption);
8844
+ } catch (error) {
8845
+ this.logger.error("getPaymentMethods failed", { error });
8846
+ throw this.wrapError("getPaymentMethods", error);
8847
+ }
8848
+ }
8849
+ // ============================================
8850
+ // Shipping / Delivery Methods
8851
+ // ============================================
8852
+ async getShippingMethods(_cartId) {
8853
+ this.logger.debug("getShippingMethods (delivery options listing)");
8854
+ try {
8855
+ const rawOptions = await this.client.list("deliveryOptions");
8856
+ return rawOptions.filter((o) => !o.deleted).map((o) => transformStelDeliveryOption(o, this.currencyCode));
8857
+ } catch (error) {
8858
+ this.logger.error("getShippingMethods failed", { error });
8859
+ throw this.wrapError("getShippingMethods", error);
8860
+ }
8861
+ }
8862
+ // ============================================
8863
+ // Customer Operations (optional)
8864
+ // ============================================
8865
+ async getCustomer(customerId) {
8866
+ this.logger.debug("getCustomer", { customerId });
8867
+ try {
8868
+ const raw = await this.client.getOne("clients", customerId);
8869
+ return raw ? transformStelClient(raw) : void 0;
8870
+ } catch (error) {
8871
+ this.logger.error("getCustomer failed", { customerId, error });
8872
+ throw this.wrapError("getCustomer", error);
8873
+ }
8874
+ }
8875
+ async getCustomers(options) {
8876
+ this.logger.debug("getCustomers", { options });
8877
+ try {
8878
+ if (options?.customFetcher) {
8879
+ return options.customFetcher(options);
8880
+ }
8881
+ const query = {};
8882
+ if (options?.limit) {
8883
+ query.limit = options.limit;
8884
+ }
8885
+ if (options?.offset) {
8886
+ query.start = options.offset;
8887
+ }
8888
+ const rawClients = await this.client.list("clients", query);
8889
+ let customers = rawClients.filter((c) => !c.deleted).map(transformStelClient);
8890
+ if (options?.search) {
8891
+ const needle = options.search.toLowerCase();
8892
+ customers = customers.filter(
8893
+ (c) => c.email.toLowerCase().includes(needle) || (c.firstName ?? "").toLowerCase().includes(needle) || (c.lastName ?? "").toLowerCase().includes(needle)
8894
+ );
8895
+ }
8896
+ return customers;
8897
+ } catch (error) {
8898
+ this.logger.error("getCustomers failed", { options, error });
8899
+ throw this.wrapError("getCustomers", error);
8900
+ }
8901
+ }
8902
+ async updateCustomer(customerId, data) {
8903
+ this.logger.debug("updateCustomer", { customerId, data });
8904
+ try {
8905
+ const stelPayload = {};
8906
+ if (data.firstName || data.lastName) {
8907
+ stelPayload.name = [data.firstName, data.lastName].filter(Boolean).join(" ");
8908
+ }
8909
+ if (data.email) {
8910
+ stelPayload.email = data.email;
8911
+ }
8912
+ if (data.phone) {
8913
+ stelPayload.phone = data.phone;
8914
+ }
8915
+ const raw = await this.client.update("clients", customerId, stelPayload);
8916
+ return transformStelClient(raw);
8917
+ } catch (error) {
8918
+ this.logger.error("updateCustomer failed", { customerId, error });
8919
+ throw this.wrapError("updateCustomer", error);
8920
+ }
8921
+ }
8922
+ // ============================================
8923
+ // Order Operations (optional)
8924
+ // ============================================
8925
+ async getOrder(orderId) {
8926
+ this.logger.debug("getOrder", { orderId });
8927
+ try {
8928
+ const raw = await this.client.getOne("salesOrders", orderId);
8929
+ return raw ? transformStelSalesOrder(raw, this.currencyCode) : void 0;
8930
+ } catch (error) {
8931
+ this.logger.error("getOrder failed", { orderId, error });
8932
+ throw this.wrapError("getOrder", error);
8933
+ }
8934
+ }
8935
+ async getOrders(options) {
8936
+ this.logger.debug("getOrders", { options });
8937
+ try {
8938
+ if (options?.customFetcher) {
8939
+ return options.customFetcher(options);
8940
+ }
8941
+ const query = {};
8942
+ if (options?.limit) {
8943
+ query.limit = options.limit;
8944
+ }
8945
+ if (options?.offset) {
8946
+ query.start = options.offset;
8947
+ }
8948
+ if (options?.customerId) {
8949
+ query["client-id"] = options.customerId;
8950
+ }
8951
+ const rawOrders = await this.client.list("salesOrders", query);
8952
+ return rawOrders.filter((o) => !o.deleted).map((o) => transformStelSalesOrder(o, this.currencyCode));
8953
+ } catch (error) {
8954
+ this.logger.error("getOrders failed", { options, error });
8955
+ throw this.wrapError("getOrders", error);
8956
+ }
8957
+ }
8958
+ async getAdminOrders(options) {
8959
+ this.logger.debug("getAdminOrders", { options });
8960
+ try {
8961
+ const query = {};
8962
+ if (options?.limit) {
8963
+ query.limit = options.limit;
8964
+ }
8965
+ if (options?.offset) {
8966
+ query.start = options.offset;
8967
+ }
8968
+ const rawOrders = await this.client.list("salesOrders", query);
8969
+ let orders = rawOrders.filter((o) => !o.deleted).map((o) => transformStelSalesOrder(o, this.currencyCode));
8970
+ if (options?.search) {
8971
+ const needle = options.search.toLowerCase();
8972
+ orders = orders.filter(
8973
+ (o) => o.orderNumber.toLowerCase().includes(needle) || o.email.toLowerCase().includes(needle)
8974
+ );
8975
+ }
8976
+ if (options?.status) {
8977
+ const statuses = Array.isArray(options.status) ? options.status : [options.status];
8978
+ orders = orders.filter((o) => statuses.includes(o.status));
8979
+ }
8980
+ return { orders, count: orders.length };
8981
+ } catch (error) {
8982
+ this.logger.error("getAdminOrders failed", { options, error });
8983
+ throw this.wrapError("getAdminOrders", error);
8984
+ }
8985
+ }
8986
+ cancelOrder(_orderId) {
8987
+ return this.notSupported("cancelOrder");
8988
+ }
8989
+ createFulfillment(_orderId, _items) {
8990
+ return this.notSupported("createFulfillment");
8991
+ }
8992
+ createRefund(_orderId, _amount, _reason) {
8993
+ return this.notSupported("createRefund");
8994
+ }
8995
+ // ============================================
8996
+ // Storefront Context
8997
+ // ============================================
8998
+ async getStorefrontContext() {
8999
+ return {
9000
+ id: this.storefrontId,
9001
+ name: this.companyName,
9002
+ platformType: "stelorder",
9003
+ requiresProductScoping: false,
9004
+ currencyCode: this.currencyCode,
9005
+ metadata: {
9006
+ apiBaseUrl: this.client.apiBaseUrl,
9007
+ singleCompany: true,
9008
+ providerVersion: this.version
9009
+ }
9010
+ };
9011
+ }
9012
+ isStorefrontRequired() {
9013
+ return false;
9014
+ }
9015
+ // ============================================
9016
+ // Internal helpers
9017
+ // ============================================
9018
+ notSupported(operation) {
9019
+ return Promise.reject(
9020
+ new ProviderAPIError(
9021
+ `Stel Order does not support \`${operation}\`. STEL is an ERP adapter without cart/checkout/auth capabilities.`,
9022
+ "stelorder",
9023
+ 501
9024
+ )
9025
+ );
9026
+ }
9027
+ wrapError(operation, error) {
9028
+ if (error instanceof ProviderAPIError) {
9029
+ return error;
9030
+ }
9031
+ const message = error instanceof Error ? error.message : String(error);
9032
+ return new ProviderAPIError(
9033
+ `Stel Order \`${operation}\` failed: ${message}`,
9034
+ "stelorder",
9035
+ 500
9036
+ );
9037
+ }
9038
+ };
9039
+
9040
+ // src/providers/mock/mock.ts
9041
+ var FIXTURE_TIMESTAMP = "2026-01-01T00:00:00.000Z";
9042
+ var DEFAULT_SITE_URL = "https://mock.thorcommerce.local";
9043
+ var regionFixtures = [
9044
+ {
9045
+ id: "mock-region-us",
9046
+ name: "United States",
9047
+ currencyCode: "USD",
9048
+ locale: "en-US",
9049
+ taxRate: 0.08,
9050
+ countries: [{ code: "US", name: "United States" }]
9051
+ },
9052
+ {
9053
+ id: "mock-region-eu",
9054
+ name: "Europe",
9055
+ currencyCode: "EUR",
9056
+ locale: "en-ES",
9057
+ taxRate: 0.21,
9058
+ countries: [
9059
+ { code: "ES", name: "Spain" },
9060
+ { code: "FR", name: "France" },
9061
+ { code: "DE", name: "Germany" }
9062
+ ]
9063
+ }
9064
+ ];
9065
+ var collectionFixtures = [
9066
+ {
9067
+ id: "mock-collection-new-arrivals",
9068
+ handle: "new-arrivals",
9069
+ title: "New Arrivals",
9070
+ description: "Fresh mock catalog items for layout and merchandising flows."
9071
+ },
9072
+ {
9073
+ id: "mock-collection-best-sellers",
9074
+ handle: "best-sellers",
9075
+ title: "Best Sellers",
9076
+ description: "High-performing mock products used to design hero grids and featured sections."
9077
+ },
9078
+ {
9079
+ id: "mock-collection-studio-essentials",
9080
+ handle: "studio-essentials",
9081
+ title: "Studio Essentials",
9082
+ description: "A balanced fixture set for mock storefront navigation and detail pages."
9083
+ }
9084
+ ];
9085
+ var categoryFixtures = [
9086
+ {
9087
+ id: "mock-category-jackets",
9088
+ handle: "jackets",
9089
+ name: "Jackets",
9090
+ description: "Outerwear and layering pieces."
9091
+ },
9092
+ {
9093
+ id: "mock-category-dresses",
9094
+ handle: "dresses",
9095
+ name: "Dresses",
9096
+ description: "Editorial silhouettes for seasonal collections."
9097
+ },
9098
+ {
9099
+ id: "mock-category-home",
9100
+ handle: "home",
9101
+ name: "Home",
9102
+ description: "Decor and living objects for lifestyle layouts."
9103
+ },
9104
+ {
9105
+ id: "mock-category-accessories",
9106
+ handle: "accessories",
9107
+ name: "Accessories",
9108
+ description: "Complementary products for cart and bundle flows."
9109
+ }
9110
+ ];
9111
+ var productFixtures = [
9112
+ {
9113
+ id: "mock-product-aurora-jacket",
9114
+ handle: "aurora-jacket",
9115
+ title: "Aurora Quilted Jacket",
9116
+ description: "Lightweight quilted outerwear with tonal hardware and a soft structured collar.",
9117
+ imageLabel: "Aurora Jacket",
9118
+ imageHue: 222,
9119
+ collectionHandles: ["new-arrivals", "best-sellers"],
9120
+ categoryHandle: "jackets",
9121
+ productType: "outerwear",
9122
+ vendor: "Thor Atelier",
9123
+ tags: ["outerwear", "quilted", "winter"],
9124
+ options: [
9125
+ { id: "aurora-size", name: "Size", values: ["S", "M", "L"] },
9126
+ { id: "aurora-color", name: "Color", values: ["Midnight"] }
9127
+ ],
9128
+ variants: [
9129
+ {
9130
+ id: "mock-variant-aurora-s",
9131
+ title: "S / Midnight",
9132
+ price: 129,
9133
+ compareAtPrice: 159,
9134
+ quantityAvailable: 8,
9135
+ selectedOptions: [
9136
+ { name: "Size", value: "S" },
9137
+ { name: "Color", value: "Midnight" }
9138
+ ]
9139
+ },
9140
+ {
9141
+ id: "mock-variant-aurora-m",
9142
+ title: "M / Midnight",
9143
+ price: 129,
9144
+ compareAtPrice: 159,
9145
+ quantityAvailable: 12,
9146
+ selectedOptions: [
9147
+ { name: "Size", value: "M" },
9148
+ { name: "Color", value: "Midnight" }
9149
+ ]
9150
+ }
9151
+ ]
9152
+ },
9153
+ {
9154
+ id: "mock-product-solis-dress",
9155
+ handle: "solis-dress",
9156
+ title: "Solis Pleated Dress",
9157
+ description: "A fluid pleated dress with a clean neckline designed for hero storytelling.",
9158
+ imageLabel: "Solis Dress",
9159
+ imageHue: 18,
9160
+ collectionHandles: ["new-arrivals", "studio-essentials"],
9161
+ categoryHandle: "dresses",
9162
+ productType: "dress",
9163
+ vendor: "Thor Atelier",
9164
+ tags: ["dress", "occasion", "pleated"],
9165
+ options: [
9166
+ { id: "solis-size", name: "Size", values: ["XS", "S", "M"] },
9167
+ { id: "solis-color", name: "Color", values: ["Clay"] }
9168
+ ],
9169
+ variants: [
9170
+ {
9171
+ id: "mock-variant-solis-xs",
9172
+ title: "XS / Clay",
9173
+ price: 164,
9174
+ quantityAvailable: 4,
9175
+ selectedOptions: [
9176
+ { name: "Size", value: "XS" },
9177
+ { name: "Color", value: "Clay" }
9178
+ ]
9179
+ },
9180
+ {
9181
+ id: "mock-variant-solis-s",
9182
+ title: "S / Clay",
9183
+ price: 164,
9184
+ quantityAvailable: 9,
9185
+ selectedOptions: [
9186
+ { name: "Size", value: "S" },
9187
+ { name: "Color", value: "Clay" }
9188
+ ]
9189
+ }
9190
+ ]
9191
+ },
9192
+ {
9193
+ id: "mock-product-helios-lamp",
9194
+ handle: "helios-lamp",
9195
+ title: "Helios Table Lamp",
9196
+ description: "Warm ambient lamp with sculptural proportions for lifestyle and home grids.",
9197
+ imageLabel: "Helios Lamp",
9198
+ imageHue: 45,
9199
+ collectionHandles: ["best-sellers", "studio-essentials"],
9200
+ categoryHandle: "home",
9201
+ productType: "lighting",
9202
+ vendor: "Thor Home",
9203
+ tags: ["home", "lighting", "decor"],
9204
+ options: [{ id: "helios-finish", name: "Finish", values: ["Brass"] }],
9205
+ variants: [
9206
+ {
9207
+ id: "mock-variant-helios-brass",
9208
+ title: "Brass",
9209
+ price: 96,
9210
+ quantityAvailable: 15,
9211
+ selectedOptions: [{ name: "Finish", value: "Brass" }]
9212
+ }
9213
+ ]
9214
+ },
9215
+ {
9216
+ id: "mock-product-luna-bag",
9217
+ handle: "luna-bag",
9218
+ title: "Luna Crossbody Bag",
9219
+ description: "Compact everyday bag for accessory rails, checkout add-ons, and bundle modules.",
9220
+ imageLabel: "Luna Bag",
9221
+ imageHue: 306,
9222
+ collectionHandles: ["studio-essentials"],
9223
+ categoryHandle: "accessories",
9224
+ productType: "bag",
9225
+ vendor: "Thor Atelier",
9226
+ tags: ["bag", "accessory", "everyday"],
9227
+ options: [{ id: "luna-color", name: "Color", values: ["Berry"] }],
9228
+ variants: [
9229
+ {
9230
+ id: "mock-variant-luna-berry",
9231
+ title: "Berry",
9232
+ price: 82,
9233
+ quantityAvailable: 18,
9234
+ selectedOptions: [{ name: "Color", value: "Berry" }]
9235
+ }
9236
+ ]
9237
+ }
9238
+ ];
9239
+ var stockLocationFixture = {
9240
+ id: "mock-stock-primary",
9241
+ name: "Mock Main Warehouse",
9242
+ address: {
9243
+ address1: "100 Mock Avenue",
9244
+ city: "Design City",
9245
+ countryCode: "US",
9246
+ postalCode: "10001",
9247
+ province: "NY"
9248
+ },
9249
+ metadata: {
9250
+ timezone: "America/New_York"
9251
+ }
9252
+ };
9253
+ var cartStore = /* @__PURE__ */ new Map();
9254
+ var orderStore = /* @__PURE__ */ new Map();
9255
+ var sequence = 0;
9256
+ function nextId(prefix) {
9257
+ sequence += 1;
9258
+ return `${prefix}-${sequence}`;
9259
+ }
9260
+ function createMoney(amount, currencyCode) {
9261
+ return {
9262
+ amount: amount.toFixed(2),
9263
+ currencyCode
9264
+ };
9265
+ }
9266
+ function createImage(label, hue) {
9267
+ const svg = `
9268
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 1200" role="img" aria-label="${label}">
9269
+ <defs>
9270
+ <linearGradient id="g" x1="0" x2="1" y1="0" y2="1">
9271
+ <stop offset="0%" stop-color="hsl(${hue}, 72%, 72%)" />
9272
+ <stop offset="100%" stop-color="hsl(${(hue + 48) % 360}, 62%, 42%)" />
9273
+ </linearGradient>
9274
+ </defs>
9275
+ <rect width="1200" height="1200" fill="url(#g)" rx="48" />
9276
+ <circle cx="910" cy="280" r="180" fill="rgba(255,255,255,0.22)" />
9277
+ <text x="90" y="990" fill="white" font-family="Arial, sans-serif" font-size="96" font-weight="700">${label}</text>
9278
+ </svg>
9279
+ `.trim();
9280
+ return {
9281
+ url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svg)}`,
9282
+ altText: label,
9283
+ width: 1200,
9284
+ height: 1200
9285
+ };
9286
+ }
9287
+ function getRegionFixture(regionId) {
9288
+ if (!regionId) {
9289
+ return regionFixtures[0];
9290
+ }
9291
+ return regionFixtures.find((region) => region.id === regionId) ?? regionFixtures[0];
9292
+ }
9293
+ function createProductImageSet(label, hue) {
9294
+ const featuredImage = createImage(label, hue);
9295
+ return {
9296
+ featuredImage,
9297
+ images: [featuredImage, createImage(`${label} Detail`, (hue + 18) % 360)]
9298
+ };
9299
+ }
9300
+ function buildCollections() {
9301
+ return collectionFixtures.map((collection) => ({
9302
+ id: collection.id,
9303
+ handle: collection.handle,
9304
+ title: collection.title,
9305
+ description: collection.description,
9306
+ path: `/collections/${collection.handle}`,
9307
+ updatedAt: FIXTURE_TIMESTAMP
9308
+ }));
9309
+ }
9310
+ function buildCategories() {
9311
+ return categoryFixtures.map((category) => ({
9312
+ id: category.id,
9313
+ handle: category.handle,
9314
+ name: category.name,
9315
+ description: category.description,
9316
+ parentCategoryId: category.parentCategoryId,
9317
+ productCount: productFixtures.filter((product) => product.categoryHandle === category.handle).length,
9318
+ image: createImage(category.name, 180).url
9319
+ }));
9320
+ }
9321
+ function buildProducts(currencyCode) {
9322
+ const collections = buildCollections();
9323
+ return productFixtures.map((product) => {
9324
+ const { featuredImage, images } = createProductImageSet(product.imageLabel, product.imageHue);
9325
+ const variants = product.variants.map((variant) => ({
9326
+ id: variant.id,
9327
+ title: variant.title,
9328
+ availableForSale: variant.quantityAvailable > 0,
9329
+ selectedOptions: variant.selectedOptions,
9330
+ price: createMoney(variant.price, currencyCode),
9331
+ compareAtPrice: variant.compareAtPrice ? createMoney(variant.compareAtPrice, currencyCode) : void 0,
9332
+ quantityAvailable: variant.quantityAvailable,
9333
+ image: featuredImage
9334
+ }));
9335
+ const prices = product.variants.map((variant) => variant.price);
9336
+ return {
9337
+ id: product.id,
9338
+ handle: product.handle,
9339
+ title: product.title,
9340
+ description: product.description,
9341
+ availableForSale: variants.some((variant) => variant.availableForSale),
9342
+ options: product.options,
9343
+ variants,
9344
+ featuredImage,
9345
+ images,
9346
+ priceRange: {
9347
+ minVariantPrice: createMoney(Math.min(...prices), currencyCode),
9348
+ maxVariantPrice: createMoney(Math.max(...prices), currencyCode)
9349
+ },
9350
+ collections: product.collectionHandles.map((handle) => collections.find((collection) => collection.handle === handle)).filter((collection) => Boolean(collection)).map((collection) => ({
9351
+ id: collection.id,
9352
+ title: collection.title,
9353
+ handle: collection.handle
9354
+ })),
9355
+ productType: product.productType,
9356
+ vendor: product.vendor,
9357
+ tags: product.tags,
9358
+ createdAt: FIXTURE_TIMESTAMP,
9359
+ updatedAt: FIXTURE_TIMESTAMP,
9360
+ metadata: {
9361
+ categoryHandle: product.categoryHandle,
9362
+ collectionHandles: product.collectionHandles
9363
+ }
9364
+ };
9365
+ });
9366
+ }
9367
+ function filterProducts(products, options) {
9368
+ const query = options.query?.trim().toLowerCase();
9369
+ const categoryIds = new Set(options.categoryIds ?? []);
9370
+ const collectionIds = new Set(options.collectionIds ?? []);
9371
+ return products.filter((product) => {
9372
+ if (query) {
9373
+ const matchesQuery = [product.title, product.description, ...product.tags ?? []].join(" ").toLowerCase().includes(query);
9374
+ if (!matchesQuery) {
9375
+ return false;
9376
+ }
9377
+ }
9378
+ if (categoryIds.size > 0) {
9379
+ const categoryHandle = String(product.metadata?.categoryHandle ?? "");
9380
+ const category = categoryFixtures.find((item) => item.handle === categoryHandle);
9381
+ const matchesCategory = category ? categoryIds.has(category.id) || categoryIds.has(category.handle) : false;
9382
+ if (!matchesCategory) {
9383
+ return false;
9384
+ }
9385
+ }
9386
+ if (collectionIds.size > 0) {
9387
+ const productCollections = (product.collections ?? []).map((collection) => collection.handle);
9388
+ const matchesCollection = (product.collections ?? []).some(
9389
+ (collection) => collectionIds.has(collection.id) || collectionIds.has(collection.handle)
9390
+ ) || productCollections.some((handle) => collectionIds.has(handle));
9391
+ if (!matchesCollection) {
9392
+ return false;
9393
+ }
9394
+ }
9395
+ return true;
9396
+ });
9397
+ }
9398
+ function sortProducts(products, sortKey, reverse) {
9399
+ const sorted = [...products];
9400
+ switch (sortKey) {
9401
+ case "price":
9402
+ case "price-asc":
9403
+ case "price-desc":
9404
+ sorted.sort(
9405
+ (left, right) => Number(left.priceRange.minVariantPrice.amount) - Number(right.priceRange.minVariantPrice.amount)
9406
+ );
9407
+ break;
9408
+ case "created_at":
9409
+ case "createdAt":
9410
+ case "newest":
9411
+ sorted.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
9412
+ break;
9413
+ case "title":
9414
+ case "name":
9415
+ default:
9416
+ sorted.sort((left, right) => left.title.localeCompare(right.title));
9417
+ break;
9418
+ }
9419
+ const shouldReverse = reverse || sortKey === "price-desc" || sortKey === "newest";
9420
+ return shouldReverse ? sorted.reverse() : sorted;
9421
+ }
9422
+ function paginateProducts(products, skip, first) {
9423
+ const start = Math.max(0, skip ?? 0);
9424
+ const end = first ? start + first : void 0;
9425
+ return products.slice(start, end);
9426
+ }
9427
+ function resolveVariant(currencyCode, merchandiseId) {
9428
+ const products = buildProducts(currencyCode);
9429
+ for (const product of products) {
9430
+ const variant = product.variants.find((item) => item.id === merchandiseId);
9431
+ if (variant) {
9432
+ return { product, variant };
9433
+ }
9434
+ }
9435
+ return void 0;
9436
+ }
9437
+ function getShippingPrice(methodId) {
9438
+ switch (methodId) {
9439
+ case "mock-shipping-express":
9440
+ return 18;
9441
+ case "mock-shipping-standard":
9442
+ return 8;
9443
+ default:
9444
+ return 0;
9445
+ }
9446
+ }
9447
+ function buildExternalCart(state, currencyCode, siteUrl) {
9448
+ const region = getRegionFixture(state.regionId);
9449
+ const regionCurrency = region.currencyCode || currencyCode;
9450
+ const lines = state.lines.flatMap((line) => {
9451
+ const resolved = resolveVariant(regionCurrency, line.merchandiseId);
9452
+ if (!resolved || !resolved.product.featuredImage) {
9453
+ return [];
9454
+ }
9455
+ const lineTotal = Number(resolved.variant.price.amount) * line.quantity;
9456
+ const stockStatus = resolved.variant.quantityAvailable && resolved.variant.quantityAvailable > 0 ? "in_stock" : "out_of_stock";
9457
+ return [{
9458
+ id: line.id,
9459
+ quantity: line.quantity,
9460
+ stockStatus,
9461
+ cost: {
9462
+ totalAmount: createMoney(lineTotal, regionCurrency)
9463
+ },
9464
+ merchandise: {
9465
+ id: resolved.variant.id,
9466
+ title: resolved.variant.title,
9467
+ selectedOptions: resolved.variant.selectedOptions,
9468
+ product: {
9469
+ id: resolved.product.id,
9470
+ handle: resolved.product.handle,
9471
+ title: resolved.product.title,
9472
+ featuredImage: resolved.product.featuredImage
9473
+ }
9474
+ }
9475
+ }];
9476
+ });
9477
+ const subtotal = lines.reduce(
9478
+ (sum, line) => sum + Number(line.cost.totalAmount.amount),
9479
+ 0
9480
+ );
9481
+ const shipping = getShippingPrice(state.shippingMethodId);
9482
+ const discount = state.discountCode ? subtotal * 0.1 : 0;
9483
+ const taxableBase = Math.max(subtotal + shipping - discount, 0);
9484
+ const totalTax = region.taxRate ? taxableBase * region.taxRate : 0;
9485
+ const total = taxableBase + totalTax;
9486
+ return {
9487
+ id: state.id,
9488
+ checkoutUrl: `${siteUrl}/checkout?cart=${state.id}`,
9489
+ cost: {
9490
+ subtotalAmount: createMoney(subtotal, regionCurrency),
9491
+ totalAmount: createMoney(total, regionCurrency),
9492
+ totalTaxAmount: createMoney(totalTax, regionCurrency)
9493
+ },
9494
+ lines,
9495
+ totalQuantity: lines.reduce((sum, line) => sum + line.quantity, 0),
9496
+ completedAt: state.completedAt
9497
+ };
9498
+ }
9499
+ function buildOrderFromCart(state, currencyCode, siteUrl) {
9500
+ const cart = buildExternalCart(state, currencyCode, siteUrl);
9501
+ return {
9502
+ id: `mock-order-${state.id}`,
9503
+ orderNumber: `${1e3 + sequence}`,
9504
+ email: "mock-customer@thorprovider.dev",
9505
+ status: "completed",
9506
+ paymentStatus: state.paymentProviderId ? "paid" : "pending",
9507
+ fulfillmentStatus: state.shippingMethodId ? "fulfilled" : "unfulfilled",
9508
+ items: cart.lines.map((line) => ({
9509
+ id: line.id ?? nextId("mock-order-line"),
9510
+ title: line.merchandise.product.title,
9511
+ variantTitle: line.merchandise.title,
9512
+ quantity: line.quantity,
9513
+ price: line.merchandise.product.featuredImage ? createMoney(Number(line.cost.totalAmount.amount) / Math.max(line.quantity, 1), cart.cost.totalAmount.currencyCode) : createMoney(0, cart.cost.totalAmount.currencyCode),
9514
+ total: line.cost.totalAmount,
9515
+ productId: line.merchandise.product.id,
9516
+ variantId: line.merchandise.id,
9517
+ image: line.merchandise.product.featuredImage
9518
+ })),
9519
+ subtotal: cart.cost.subtotalAmount,
9520
+ total: cart.cost.totalAmount,
9521
+ tax: cart.cost.totalTaxAmount,
9522
+ shipping: createMoney(getShippingPrice(state.shippingMethodId), cart.cost.totalAmount.currencyCode),
9523
+ discount: createMoney(state.discountCode ? Number(cart.cost.subtotalAmount.amount) * 0.1 : 0, cart.cost.totalAmount.currencyCode),
9524
+ createdAt: FIXTURE_TIMESTAMP,
9525
+ updatedAt: FIXTURE_TIMESTAMP,
9526
+ completedAt: state.completedAt,
9527
+ metadata: {
9528
+ provider: "mock",
9529
+ checkoutUrl: cart.checkoutUrl
9530
+ }
9531
+ };
9532
+ }
9533
+ function getMockCollections() {
9534
+ return buildCollections();
9535
+ }
9536
+ function getMockCategories() {
9537
+ return buildCategories();
9538
+ }
9539
+ function getMockProducts(options) {
9540
+ const region = getRegionFixture(options?.regionId);
9541
+ const currencyCode = options?.currencyCode ?? region.currencyCode;
9542
+ const products = buildProducts(currencyCode);
9543
+ const filtered = filterProducts(products, {
9544
+ query: options?.query,
9545
+ categoryIds: options?.categoryIds,
9546
+ collectionIds: options?.collectionIds
9547
+ });
9548
+ const sorted = sortProducts(filtered, options?.sortKey, options?.reverse);
9549
+ return paginateProducts(sorted, options?.skip, options?.first);
9550
+ }
9551
+ function getMockProduct(handle, regionId) {
9552
+ const region = getRegionFixture(regionId);
9553
+ return buildProducts(region.currencyCode).find(
9554
+ (product) => product.handle === handle || product.id === handle
9555
+ );
9556
+ }
9557
+ function getMockProductRecommendations(productId, regionId) {
9558
+ const product = getMockProduct(productId, regionId) ?? buildProducts(getRegionFixture(regionId).currencyCode).find((item) => item.id === productId);
9559
+ if (!product) {
9560
+ return [];
9561
+ }
9562
+ const collectionHandles = new Set((product.collections ?? []).map((collection) => collection.handle));
9563
+ return buildProducts(getRegionFixture(regionId).currencyCode).filter((candidate) => candidate.id !== product.id).filter(
9564
+ (candidate) => (candidate.collections ?? []).some((collection) => collectionHandles.has(collection.handle))
9565
+ ).slice(0, 4);
9566
+ }
9567
+ function getMockCollection(handle) {
9568
+ return buildCollections().find(
9569
+ (collection) => collection.handle === handle || collection.id === handle
9570
+ );
9571
+ }
9572
+ function getMockCategory(idOrHandle) {
9573
+ return buildCategories().find(
9574
+ (category) => category.handle === idOrHandle || category.id === idOrHandle
9575
+ );
9576
+ }
9577
+ function getMockRegions() {
9578
+ return regionFixtures.map((region) => ({
9579
+ id: region.id,
9580
+ name: region.name,
9581
+ currency_code: region.currencyCode,
9582
+ countries: region.countries.map((country) => ({
9583
+ id: `country-${country.code.toLowerCase()}`,
9584
+ iso_2: country.code.toLowerCase(),
9585
+ name: country.name,
9586
+ display_name: country.name
9587
+ }))
9588
+ }));
9589
+ }
9590
+ function getMockAdminRegions() {
9591
+ return regionFixtures.map((region) => ({
9592
+ id: region.id,
9593
+ name: region.name,
9594
+ countryCodes: region.countries.map((country) => country.code),
9595
+ currency: region.currencyCode,
9596
+ taxRate: region.taxRate,
9597
+ isEnabled: true
9598
+ }));
9599
+ }
9600
+ function getMockRegionCountries(regionId) {
9601
+ const region = regionFixtures.find((item) => item.id === regionId);
9602
+ return region?.countries ?? [];
9603
+ }
9604
+ function createMockCart(regionId) {
9605
+ const cart = {
9606
+ id: nextId("mock-cart"),
9607
+ regionId: regionId ?? regionFixtures[0].id,
9608
+ lines: []
9609
+ };
9610
+ cartStore.set(cart.id, cart);
9611
+ return cart;
9612
+ }
9613
+ function getMockCartState(cartId) {
9614
+ return cartStore.get(cartId);
9615
+ }
9616
+ function saveMockCartState(cart) {
9617
+ cartStore.set(cart.id, cart);
9618
+ return cart;
9619
+ }
9620
+ function buildMockCart(cart, currencyCode, siteUrl) {
9621
+ return buildExternalCart(
9622
+ cart,
9623
+ currencyCode ?? getRegionFixture(cart.regionId).currencyCode,
9624
+ siteUrl ?? DEFAULT_SITE_URL
9625
+ );
9626
+ }
9627
+ function getMockShippingMethods(regionId) {
9628
+ const currencyCode = getRegionFixture(regionId).currencyCode;
9629
+ return [
9630
+ {
9631
+ id: "mock-shipping-standard",
9632
+ name: "Standard Shipping",
9633
+ description: "Fixture shipping option for checkout and cart layouts.",
9634
+ price: createMoney(8, currencyCode),
9635
+ estimatedDays: "3-5 business days"
9636
+ },
9637
+ {
9638
+ id: "mock-shipping-express",
9639
+ name: "Express Shipping",
9640
+ description: "Faster fixture shipping option for premium checkout flows.",
9641
+ price: createMoney(18, currencyCode),
9642
+ estimatedDays: "1-2 business days"
9643
+ }
9644
+ ];
9645
+ }
9646
+ function getMockPaymentMethods(currencyCode) {
9647
+ return [
9648
+ {
9649
+ id: "mock-card",
9650
+ name: "Mock Card",
9651
+ type: "card",
9652
+ isEnabled: true,
9653
+ requiresSetup: true,
9654
+ description: `Fixture card checkout for ${currencyCode}.`
9655
+ },
9656
+ {
9657
+ id: "mock-cash",
9658
+ name: "Cash on Delivery",
9659
+ type: "cash_on_delivery",
9660
+ isEnabled: true,
9661
+ requiresSetup: false,
9662
+ description: "Mock cash payment option for checkout prototypes."
9663
+ }
9664
+ ];
9665
+ }
9666
+ function getMockStockLocations() {
9667
+ return [stockLocationFixture];
9668
+ }
9669
+ function getMockInventoryLevels(variantId) {
9670
+ for (const region of regionFixtures) {
9671
+ const resolved = resolveVariant(region.currencyCode, variantId);
9672
+ if (resolved) {
9673
+ return [{
9674
+ locationId: stockLocationFixture.id,
9675
+ locationName: stockLocationFixture.name,
9676
+ availableQuantity: resolved.variant.quantityAvailable ?? 0,
9677
+ reservedQuantity: 0,
9678
+ stockedQuantity: resolved.variant.quantityAvailable ?? 0
9679
+ }];
9680
+ }
9681
+ }
9682
+ return [];
9683
+ }
9684
+ function validateMockCartStock(cart) {
9685
+ const currencyCode = getRegionFixture(cart.regionId).currencyCode;
9686
+ const unavailableItems = cart.lines.flatMap((line) => {
9687
+ const resolved = resolveVariant(currencyCode, line.merchandiseId);
9688
+ if (!resolved) {
9689
+ return [];
9690
+ }
9691
+ const availableQuantity = resolved.variant.quantityAvailable ?? 0;
9692
+ if (line.quantity <= availableQuantity) {
9693
+ return [];
9694
+ }
9695
+ return [{
9696
+ variantId: resolved.variant.id,
9697
+ productName: resolved.product.title,
9698
+ requestedQuantity: line.quantity,
9699
+ availableQuantity
9700
+ }];
9701
+ });
9702
+ return {
9703
+ allAvailable: unavailableItems.length === 0,
9704
+ unavailableItems
9705
+ };
9706
+ }
9707
+ function getMockFulfillmentOptions(regionId) {
9708
+ return getMockShippingMethods(regionId).map((method) => ({
9709
+ id: method.id,
9710
+ providerId: "mock-fulfillment",
9711
+ name: method.name,
9712
+ description: method.description,
9713
+ price: method.price,
9714
+ estimatedDays: method.estimatedDays,
9715
+ stockLocation: stockLocationFixture
9716
+ }));
9717
+ }
9718
+ function completeMockCheckout(cart, currencyCode, siteUrl) {
9719
+ const completedAt = (/* @__PURE__ */ new Date()).toISOString();
9720
+ const nextCart = {
9721
+ ...cart,
9722
+ completedAt
9723
+ };
9724
+ cartStore.set(nextCart.id, nextCart);
9725
+ const order = buildOrderFromCart(
9726
+ nextCart,
9727
+ currencyCode ?? getRegionFixture(nextCart.regionId).currencyCode,
9728
+ siteUrl ?? DEFAULT_SITE_URL
9729
+ );
9730
+ orderStore.set(order.id, order);
9731
+ return order;
9732
+ }
9733
+ function getMockAdminOrders() {
9734
+ const orders = Array.from(orderStore.values()).sort(
9735
+ (left, right) => right.createdAt.localeCompare(left.createdAt)
9736
+ );
9737
+ return {
9738
+ orders,
9739
+ count: orders.length
9740
+ };
9741
+ }
9742
+ function getMockOrder(orderId) {
9743
+ return orderStore.get(orderId);
9744
+ }
9745
+ function saveMockOrder(order) {
9746
+ orderStore.set(order.id, order);
9747
+ return order;
9748
+ }
9749
+
9750
+ // src/providers/mock/index.ts
9751
+ var MockProvider = class {
9752
+ name = "mock";
9753
+ version = "1.0.0";
9754
+ capabilities = MOCK_CAPABILITIES;
9755
+ isMock = true;
9756
+ currencyCode;
9757
+ siteUrl;
9758
+ constructor(config = {}) {
9759
+ this.currencyCode = config.currencyCode ?? "USD";
9760
+ this.siteUrl = config.siteUrl ?? "https://mock.thorcommerce.local";
9761
+ }
9762
+ hasVariant(merchandiseId, regionId) {
9763
+ return getMockProducts({
9764
+ currencyCode: this.currencyCode,
9765
+ regionId
9766
+ }).some(
9767
+ (product) => product.variants.some((variant) => variant.id === merchandiseId)
9768
+ );
9769
+ }
9770
+ async getProduct(handle, options) {
9771
+ return getMockProduct(handle, options?.regionId);
9772
+ }
9773
+ async getProducts(options) {
9774
+ return getMockProducts({
9775
+ currencyCode: this.currencyCode,
9776
+ query: options?.query,
9777
+ sortKey: options?.sortKey,
9778
+ reverse: options?.reverse,
9779
+ first: options?.first,
9780
+ skip: options?.skip,
9781
+ categoryIds: options?.categoryIds,
9782
+ collectionIds: options?.collectionIds,
9783
+ regionId: options?.regionId
9784
+ });
9785
+ }
9786
+ async getProductRecommendations(productId) {
9787
+ return getMockProductRecommendations(productId);
9788
+ }
9789
+ async getCollection(handle) {
9790
+ return getMockCollection(handle);
9791
+ }
9792
+ async getCollections(options) {
9793
+ const collections = getMockCollections();
9794
+ const query = options?.query?.trim().toLowerCase();
9795
+ const filtered = query ? collections.filter(
9796
+ (collection) => [collection.title, collection.description, collection.handle].join(" ").toLowerCase().includes(query)
9797
+ ) : collections;
9798
+ return filtered.slice(0, options?.limit ?? filtered.length);
9799
+ }
9800
+ async getCollectionProducts(handle, options) {
9801
+ const collection = getMockCollection(handle);
9802
+ if (!collection) {
9803
+ return [];
9804
+ }
9805
+ return getMockProducts({
9806
+ currencyCode: this.currencyCode,
9807
+ collectionIds: [collection.id],
9808
+ sortKey: options?.sortKey,
9809
+ reverse: options?.reverse,
9810
+ first: options?.first
9811
+ });
9812
+ }
9813
+ async getCategory(idOrHandle) {
9814
+ return getMockCategory(idOrHandle);
9815
+ }
9816
+ async getCategories(options) {
9817
+ const categories = getMockCategories();
9818
+ const query = options?.query?.trim().toLowerCase();
9819
+ let filtered = query ? categories.filter(
9820
+ (category) => [category.name, category.description ?? "", category.handle].join(" ").toLowerCase().includes(query)
9821
+ ) : categories;
9822
+ if (options?.parentCategoryId) {
9823
+ filtered = filtered.filter((category) => category.parentCategoryId === options.parentCategoryId);
9824
+ }
9825
+ return filtered.slice(0, options?.limit ?? filtered.length);
9826
+ }
9827
+ async getCategoryProducts(handle, options) {
9828
+ const category = getMockCategory(handle);
9829
+ if (!category) {
9830
+ return [];
9831
+ }
9832
+ return getMockProducts({
9833
+ currencyCode: this.currencyCode,
9834
+ categoryIds: [category.id],
9835
+ sortKey: options?.sortKey,
9836
+ reverse: options?.reverse,
9837
+ first: options?.first
9838
+ });
9839
+ }
9840
+ async createCart(options) {
9841
+ const cart = createMockCart(options?.regionId);
9842
+ return buildMockCart(cart, this.currencyCode, this.siteUrl);
9843
+ }
9844
+ async getCart(cartId) {
9845
+ const cart = getMockCartState(cartId);
9846
+ return cart ? buildMockCart(cart, this.currencyCode, this.siteUrl) : void 0;
9847
+ }
9848
+ async addToCart(cartId, lines) {
9849
+ const cart = getMockCartState(cartId);
9850
+ if (!cart) {
9851
+ throw new ResourceNotFoundError("cart", cartId);
9852
+ }
9853
+ for (const line of lines) {
9854
+ if (!this.hasVariant(line.merchandiseId, cart.regionId)) {
9855
+ throw new ResourceNotFoundError("variant", line.merchandiseId);
9856
+ }
9857
+ }
9858
+ const nextLines = [...cart.lines];
9859
+ for (const line of lines) {
9860
+ const existing = nextLines.find((item) => item.merchandiseId === line.merchandiseId);
9861
+ if (existing) {
9862
+ existing.quantity += line.quantity;
9863
+ } else {
9864
+ nextLines.push({
9865
+ id: `mock-line-${line.merchandiseId}`,
9866
+ merchandiseId: line.merchandiseId,
9867
+ quantity: line.quantity
9868
+ });
9869
+ }
9870
+ }
9871
+ const saved = saveMockCartState({ ...cart, lines: nextLines });
9872
+ return buildMockCart(saved, this.currencyCode, this.siteUrl);
9873
+ }
9874
+ async removeFromCart(cartId, lineIds) {
9875
+ const cart = getMockCartState(cartId);
9876
+ if (!cart) {
9877
+ throw new ResourceNotFoundError("cart", cartId);
9878
+ }
9879
+ const saved = saveMockCartState({
9880
+ ...cart,
9881
+ lines: cart.lines.filter((line) => !lineIds.includes(line.id))
9882
+ });
9883
+ return buildMockCart(saved, this.currencyCode, this.siteUrl);
9884
+ }
9885
+ async updateCart(cartId, lines) {
9886
+ const cart = getMockCartState(cartId);
9887
+ if (!cart) {
9888
+ throw new ResourceNotFoundError("cart", cartId);
9889
+ }
9890
+ for (const line of lines) {
9891
+ if (!this.hasVariant(line.merchandiseId, cart.regionId)) {
9892
+ throw new ResourceNotFoundError("variant", line.merchandiseId);
9893
+ }
9894
+ }
9895
+ const updates = new Map(lines.map((line) => [line.id, line]));
9896
+ const nextLines = cart.lines.map((line) => {
9897
+ const update = updates.get(line.id);
9898
+ if (!update) {
9899
+ return line;
9900
+ }
9901
+ return {
9902
+ ...line,
9903
+ merchandiseId: update.merchandiseId,
9904
+ quantity: update.quantity
9905
+ };
9906
+ }).filter((line) => line.quantity > 0);
9907
+ const saved = saveMockCartState({ ...cart, lines: nextLines });
9908
+ return buildMockCart(saved, this.currencyCode, this.siteUrl);
9909
+ }
9910
+ async getRegions() {
9911
+ return getMockRegions();
9912
+ }
9913
+ async completeCheckout(cartId) {
9914
+ const cart = getMockCartState(cartId);
9915
+ if (!cart) {
9916
+ throw new ResourceNotFoundError("cart", cartId);
9917
+ }
9918
+ const order = completeMockCheckout(cart, this.currencyCode, this.siteUrl);
9919
+ return order;
9920
+ }
9921
+ async getShippingMethods(cartId) {
9922
+ const cart = getMockCartState(cartId);
9923
+ return getMockShippingMethods(cart?.regionId);
9924
+ }
9925
+ async getRegionCountries(regionId) {
9926
+ return getMockRegionCountries(regionId);
9927
+ }
9928
+ async addShippingMethod(cartId, methodId) {
9929
+ const cart = getMockCartState(cartId);
9930
+ if (!cart) {
9931
+ throw new ResourceNotFoundError("cart", cartId);
9932
+ }
9933
+ const allowed = getMockShippingMethods(cart.regionId).some((method) => method.id === methodId);
9934
+ if (!allowed) {
9935
+ throw new ProviderAPIError(`Unknown mock shipping method: ${methodId}`, "mock", 400);
9936
+ }
9937
+ const saved = saveMockCartState({ ...cart, shippingMethodId: methodId });
9938
+ return buildMockCart(saved, this.currencyCode, this.siteUrl);
9939
+ }
9940
+ async initiatePaymentSession(cartId, providerId) {
9941
+ const cart = getMockCartState(cartId);
9942
+ if (!cart) {
9943
+ throw new ResourceNotFoundError("cart", cartId);
9944
+ }
9945
+ const allowed = getMockPaymentMethods(this.currencyCode).some((method) => method.id === providerId);
9946
+ if (!allowed) {
9947
+ throw new ProviderAPIError(`Unknown mock payment method: ${providerId}`, "mock", 400);
9948
+ }
9949
+ saveMockCartState({ ...cart, paymentProviderId: providerId });
9950
+ }
9951
+ async applyDiscountCode(cartId, code) {
9952
+ const cart = getMockCartState(cartId);
9953
+ if (!cart) {
9954
+ throw new ResourceNotFoundError("cart", cartId);
9955
+ }
9956
+ const normalized = code.trim();
9957
+ if (!normalized) {
9958
+ throw new ProviderAPIError("Discount code is required.", "mock", 400);
9959
+ }
9960
+ const saved = saveMockCartState({ ...cart, discountCode: normalized });
9961
+ return buildMockCart(saved, this.currencyCode, this.siteUrl);
9962
+ }
9963
+ async removeDiscountCode(cartId, _code) {
9964
+ const cart = getMockCartState(cartId);
9965
+ if (!cart) {
9966
+ throw new ResourceNotFoundError("cart", cartId);
9967
+ }
9968
+ const saved = saveMockCartState({ ...cart, discountCode: void 0 });
9969
+ return buildMockCart(saved, this.currencyCode, this.siteUrl);
9970
+ }
9971
+ async getOrders(_options) {
9972
+ return getMockAdminOrders().orders;
9973
+ }
9974
+ async getPaymentMethods(options) {
9975
+ return getMockPaymentMethods(options.currencyCode ?? this.currencyCode);
9976
+ }
9977
+ async getStockLocations() {
9978
+ return getMockStockLocations();
9979
+ }
9980
+ async checkInventoryLevels(variantId) {
9981
+ return getMockInventoryLevels(variantId);
9982
+ }
9983
+ async validateCartStock(cartId) {
9984
+ const cart = getMockCartState(cartId);
9985
+ if (!cart) {
9986
+ throw new ResourceNotFoundError("cart", cartId);
9987
+ }
9988
+ return validateMockCartStock(cart);
9989
+ }
9990
+ async getFulfillmentOptions(cartId, _salesChannelId) {
9991
+ const cart = getMockCartState(cartId);
9992
+ return getMockFulfillmentOptions(cart?.regionId);
9993
+ }
9994
+ async cancelOrder(orderId) {
9995
+ const order = getMockOrder(orderId);
9996
+ if (!order) {
9997
+ throw new ResourceNotFoundError("order", orderId);
9998
+ }
9999
+ return saveMockOrder({
10000
+ ...order,
10001
+ status: "cancelled",
10002
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
10003
+ cancelledAt: (/* @__PURE__ */ new Date()).toISOString()
10004
+ });
10005
+ }
10006
+ async createFulfillment(_orderId, _items) {
10007
+ return;
10008
+ }
10009
+ async createRefund(orderId, _amount, _reason) {
10010
+ const order = getMockOrder(orderId);
10011
+ if (!order) {
10012
+ throw new ResourceNotFoundError("order", orderId);
10013
+ }
10014
+ saveMockOrder({
10015
+ ...order,
10016
+ status: "refunded",
10017
+ paymentStatus: "refunded",
10018
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
10019
+ });
10020
+ }
10021
+ async getAdminOrders() {
10022
+ return getMockAdminOrders();
10023
+ }
10024
+ async getAdminRegions() {
10025
+ return getMockAdminRegions();
10026
+ }
10027
+ async getStorefrontContext() {
10028
+ return {
10029
+ id: "mock-storefront",
10030
+ name: "Mock Storefront",
10031
+ platformType: "mock",
10032
+ requiresProductScoping: false,
10033
+ currencyCode: this.currencyCode,
10034
+ locale: "en-US",
10035
+ metadata: {
10036
+ mode: "design"
10037
+ }
10038
+ };
10039
+ }
10040
+ isStorefrontRequired() {
10041
+ return false;
10042
+ }
10043
+ };
10044
+
7955
10045
  // src/factory/index.ts
7956
10046
  function createProvider(options) {
7957
10047
  if (!options || !options.provider) {
@@ -7962,8 +10052,12 @@ function createProvider(options) {
7962
10052
  }
7963
10053
  const config = options.config;
7964
10054
  switch (options.provider) {
10055
+ case "mock":
10056
+ return new MockProvider(config);
7965
10057
  case "medusa":
7966
10058
  return new MedusaProvider(config);
10059
+ case "stelorder":
10060
+ return new StelOrderProvider(config);
7967
10061
  case "shopify":
7968
10062
  return new ShopifyProvider(config);
7969
10063
  case "bigcommerce":
@@ -7996,17 +10090,21 @@ export {
7996
10090
  ConfigurationError,
7997
10091
  MAGENTO_CAPABILITIES,
7998
10092
  MEDUSA_CAPABILITIES,
10093
+ MOCK_CAPABILITIES,
7999
10094
  MagentoProvider,
8000
10095
  MedusaMetadataAdapter,
8001
10096
  MedusaProvider,
8002
10097
  MetricsService,
10098
+ MockProvider,
8003
10099
  ProviderAPIError,
8004
10100
  ProviderNotFoundError,
8005
10101
  ResourceNotFoundError,
8006
10102
  SHOPIFY_CAPABILITIES,
8007
10103
  SPREE_CAPABILITIES,
10104
+ STELORDER_CAPABILITIES,
8008
10105
  ShopifyProvider,
8009
10106
  SpreeProvider,
10107
+ StelOrderProvider,
8010
10108
  StorefrontConfigError2 as StorefrontConfigError,
8011
10109
  WOOCOMMERCE_CAPABILITIES,
8012
10110
  WooCommerceProvider,