@thorprovider/adapters 4.2.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
@@ -71,6 +71,41 @@ var MEDUSA_CAPABILITIES = {
71
71
  loyaltyProgram: false
72
72
  // Requires custom implementation
73
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
+ };
74
109
  var SHOPIFY_CAPABILITIES = {
75
110
  // Profile Management
76
111
  updateProfile: true,
@@ -7977,6 +8012,1031 @@ var MagentoProvider = class {
7977
8012
  }
7978
8013
  };
7979
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
+
7980
9040
  // src/providers/mock/mock.ts
7981
9041
  var FIXTURE_TIMESTAMP = "2026-01-01T00:00:00.000Z";
7982
9042
  var DEFAULT_SITE_URL = "https://mock.thorcommerce.local";
@@ -8996,6 +10056,8 @@ function createProvider(options) {
8996
10056
  return new MockProvider(config);
8997
10057
  case "medusa":
8998
10058
  return new MedusaProvider(config);
10059
+ case "stelorder":
10060
+ return new StelOrderProvider(config);
8999
10061
  case "shopify":
9000
10062
  return new ShopifyProvider(config);
9001
10063
  case "bigcommerce":
@@ -9039,8 +10101,10 @@ export {
9039
10101
  ResourceNotFoundError,
9040
10102
  SHOPIFY_CAPABILITIES,
9041
10103
  SPREE_CAPABILITIES,
10104
+ STELORDER_CAPABILITIES,
9042
10105
  ShopifyProvider,
9043
10106
  SpreeProvider,
10107
+ StelOrderProvider,
9044
10108
  StorefrontConfigError2 as StorefrontConfigError,
9045
10109
  WOOCOMMERCE_CAPABILITIES,
9046
10110
  WooCommerceProvider,