arky-sdk 0.3.3 → 0.3.5

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.cjs CHANGED
@@ -165,13 +165,6 @@ var createEshopApi = (apiConfig) => {
165
165
  }
166
166
  );
167
167
  },
168
- async getProductBySlug(params, options) {
169
- const { businessId, slug } = params;
170
- return apiConfig.httpClient.get(
171
- `/v1/businesses/${encodeURIComponent(businessId)}/products/slug/${encodeURIComponent(businessId)}/${encodeURIComponent(slug)}`,
172
- options
173
- );
174
- },
175
168
  // ===== ORDERS =====
176
169
  async createOrder(params, options) {
177
170
  return apiConfig.httpClient.post(
@@ -226,7 +219,7 @@ var createEshopApi = (apiConfig) => {
226
219
  }));
227
220
  const payload = {
228
221
  businessId: apiConfig.businessId,
229
- market: params.market,
222
+ market: apiConfig.market,
230
223
  currency: params.currency,
231
224
  paymentMethod: params.paymentMethod,
232
225
  lines,
@@ -238,7 +231,7 @@ var createEshopApi = (apiConfig) => {
238
231
  async checkout(params, options) {
239
232
  const payload = {
240
233
  businessId: apiConfig.businessId,
241
- market: params.market,
234
+ market: apiConfig.market,
242
235
  paymentMethod: params.paymentMethod,
243
236
  shippingMethodId: params.shippingMethodId,
244
237
  items: params.items,
@@ -276,8 +269,8 @@ var createReservationApi = (apiConfig) => {
276
269
  async checkout(params, options) {
277
270
  const payload = {
278
271
  businessId: apiConfig.businessId,
272
+ market: apiConfig.market,
279
273
  blocks: params.blocks || [],
280
- market: params.market || "US",
281
274
  parts: params.parts,
282
275
  ...params.paymentMethod && { paymentMethod: params.paymentMethod },
283
276
  ...params.promoCode && { promoCode: params.promoCode }
@@ -321,7 +314,7 @@ var createReservationApi = (apiConfig) => {
321
314
  }));
322
315
  const payload = {
323
316
  businessId: apiConfig.businessId,
324
- market: params.market,
317
+ market: apiConfig.market,
325
318
  currency: params.currency,
326
319
  paymentMethod: params.paymentMethod,
327
320
  lines,
@@ -484,7 +477,7 @@ var createNewsletterApi = (apiConfig) => {
484
477
  const payload = {
485
478
  newsletterId,
486
479
  email,
487
- market: "US",
480
+ market: apiConfig.market,
488
481
  ...customerId && { customerId },
489
482
  ...payment && { payment }
490
483
  };
@@ -1368,11 +1361,14 @@ function getMarketPrice(prices, marketId, businessMarkets, options = {}) {
1368
1361
  showSymbols = true,
1369
1362
  decimalPlaces = 2,
1370
1363
  showCompareAt = true,
1371
- fallbackMarket = "US"
1364
+ fallbackMarket
1372
1365
  } = options;
1373
1366
  let price = prices.find((p) => p.market === marketId);
1367
+ if (!price && fallbackMarket) {
1368
+ price = prices.find((p) => p.market === fallbackMarket);
1369
+ }
1374
1370
  if (!price) {
1375
- price = prices.find((p) => p.market === fallbackMarket) || prices[0];
1371
+ price = prices[0];
1376
1372
  }
1377
1373
  if (!price) return "";
1378
1374
  let currency;
@@ -1405,9 +1401,15 @@ function getMarketPrice(prices, marketId, businessMarkets, options = {}) {
1405
1401
  }
1406
1402
  return formattedPrice;
1407
1403
  }
1408
- function getPriceAmount(prices, marketId, fallbackMarket = "US") {
1404
+ function getPriceAmount(prices, marketId, fallbackMarket) {
1409
1405
  if (!prices || prices.length === 0) return 0;
1410
- const price = prices.find((p) => p.market === marketId) || prices.find((p) => p.market === fallbackMarket) || prices[0];
1406
+ let price = prices.find((p) => p.market === marketId);
1407
+ if (!price && fallbackMarket) {
1408
+ price = prices.find((p) => p.market === fallbackMarket);
1409
+ }
1410
+ if (!price) {
1411
+ price = prices[0];
1412
+ }
1411
1413
  return price?.amount || 0;
1412
1414
  }
1413
1415
  function createPaymentForCheckout(subtotalMinor, marketId, currency, paymentMethod, options = {}) {
@@ -1620,6 +1622,39 @@ function validateRequired(value, fieldName = "This field") {
1620
1622
  // src/services/createHttpClient.ts
1621
1623
  function createHttpClient(cfg) {
1622
1624
  const refreshEndpoint = `${cfg.baseUrl}/v1/users/refresh-access-token`;
1625
+ let refreshPromise = null;
1626
+ async function ensureFreshToken() {
1627
+ if (refreshPromise) {
1628
+ return refreshPromise;
1629
+ }
1630
+ refreshPromise = (async () => {
1631
+ const { refreshToken, provider } = await cfg.getToken();
1632
+ if (!refreshToken) {
1633
+ cfg.logout();
1634
+ const err = new Error("No refresh token available");
1635
+ err.name = "ApiError";
1636
+ err.statusCode = 401;
1637
+ throw err;
1638
+ }
1639
+ const refRes = await fetch(refreshEndpoint, {
1640
+ method: "POST",
1641
+ headers: { Accept: "application/json", "Content-Type": "application/json" },
1642
+ body: JSON.stringify({ provider, refreshToken })
1643
+ });
1644
+ if (!refRes.ok) {
1645
+ cfg.logout();
1646
+ const err = new Error("Token refresh failed");
1647
+ err.name = "ApiError";
1648
+ err.statusCode = 401;
1649
+ throw err;
1650
+ }
1651
+ const data = await refRes.json();
1652
+ cfg.setToken(data);
1653
+ })().finally(() => {
1654
+ refreshPromise = null;
1655
+ });
1656
+ return refreshPromise;
1657
+ }
1623
1658
  async function request(method, path, body, options) {
1624
1659
  if (options?.transformRequest) {
1625
1660
  body = options.transformRequest(body);
@@ -1629,33 +1664,12 @@ function createHttpClient(cfg) {
1629
1664
  "Content-Type": "application/json",
1630
1665
  ...options?.headers || {}
1631
1666
  };
1632
- let { accessToken, refreshToken, provider, expiresAt } = await cfg.getTokens();
1667
+ let { accessToken, expiresAt } = await cfg.getToken();
1633
1668
  const nowSec = Date.now() / 1e3;
1634
1669
  if (expiresAt && nowSec > expiresAt) {
1635
- if (refreshToken) {
1636
- const refRes = await fetch(refreshEndpoint, {
1637
- method: "POST",
1638
- headers: { Accept: "application/json", "Content-Type": "application/json" },
1639
- body: JSON.stringify({ provider, refreshToken })
1640
- });
1641
- if (refRes.ok) {
1642
- const data2 = await refRes.json();
1643
- cfg.setTokens(data2);
1644
- accessToken = data2.accessToken;
1645
- } else {
1646
- cfg.logout();
1647
- const err = new Error("Error refreshing token");
1648
- err.name = "ApiError";
1649
- err.statusCode = 401;
1650
- throw err;
1651
- }
1652
- } else {
1653
- cfg.logout();
1654
- const err = new Error("No refresh token");
1655
- err.name = "ApiError";
1656
- err.statusCode = 401;
1657
- throw err;
1658
- }
1670
+ await ensureFreshToken();
1671
+ const tokens = await cfg.getToken();
1672
+ accessToken = tokens.accessToken;
1659
1673
  }
1660
1674
  if (accessToken) {
1661
1675
  headers["Authorization"] = `Bearer ${accessToken}`;
@@ -1665,15 +1679,42 @@ function createHttpClient(cfg) {
1665
1679
  if (!["GET", "DELETE"].includes(method) && body !== void 0) {
1666
1680
  fetchOpts.body = JSON.stringify(body);
1667
1681
  }
1682
+ const fullUrl = `${cfg.baseUrl}${finalPath}`;
1668
1683
  let res;
1669
1684
  let data;
1670
1685
  try {
1671
- const fullUrl = `${cfg.baseUrl}${finalPath}`;
1672
1686
  res = await fetch(fullUrl, fetchOpts);
1673
- data = await res.json();
1674
1687
  } catch (error) {
1675
1688
  const err = new Error(error instanceof Error ? error.message : "Network request failed");
1676
1689
  err.name = "NetworkError";
1690
+ err.method = method;
1691
+ err.url = fullUrl;
1692
+ throw err;
1693
+ }
1694
+ if (res.status === 401 && !options?.["_retried"]) {
1695
+ try {
1696
+ await ensureFreshToken();
1697
+ const tokens = await cfg.getToken();
1698
+ headers["Authorization"] = `Bearer ${tokens.accessToken}`;
1699
+ fetchOpts.headers = headers;
1700
+ return request(method, path, body, { ...options, _retried: true });
1701
+ } catch (refreshError) {
1702
+ }
1703
+ }
1704
+ try {
1705
+ const contentLength = res.headers.get("content-length");
1706
+ const contentType = res.headers.get("content-type");
1707
+ if (res.status === 204 || contentLength === "0" || !contentType?.includes("application/json")) {
1708
+ data = {};
1709
+ } else {
1710
+ data = await res.json();
1711
+ }
1712
+ } catch (error) {
1713
+ const err = new Error("Failed to parse response");
1714
+ err.name = "ParseError";
1715
+ err.method = method;
1716
+ err.url = fullUrl;
1717
+ err.status = res.status;
1677
1718
  throw err;
1678
1719
  }
1679
1720
  if (!res.ok) {
@@ -1684,8 +1725,12 @@ function createHttpClient(cfg) {
1684
1725
  }
1685
1726
  const err = new Error(serverErr.message || "Request failed");
1686
1727
  err.name = "ApiError";
1687
- err.statusCode = serverErr.statusCode;
1728
+ err.statusCode = serverErr.statusCode || res.status;
1688
1729
  err.validationErrors = reqErr.validationErrors;
1730
+ err.method = method;
1731
+ err.url = fullUrl;
1732
+ const requestId = res.headers.get("x-request-id") || res.headers.get("request-id");
1733
+ if (requestId) err.requestId = requestId;
1689
1734
  throw err;
1690
1735
  }
1691
1736
  if (options?.successMessage && cfg.notify) {
@@ -1703,9 +1748,18 @@ function createHttpClient(cfg) {
1703
1748
  }
1704
1749
 
1705
1750
  // src/index.ts
1706
- var SDK_VERSION = "0.3.3";
1707
- var SUPPORTED_FRAMEWORKS = ["astro", "react", "vue", "svelte", "vanilla"];
1751
+ var SDK_VERSION = "0.3.5";
1752
+ var SUPPORTED_FRAMEWORKS = [
1753
+ "astro",
1754
+ "react",
1755
+ "vue",
1756
+ "svelte",
1757
+ "vanilla"
1758
+ ];
1708
1759
  function createArkySDK(config) {
1760
+ console.log(
1761
+ `[bruda2 Arky SDK v${SDK_VERSION}] Initializing with market: ${config.market}, businessId: ${config.businessId}`
1762
+ );
1709
1763
  const httpClient = createHttpClient(config);
1710
1764
  const storageUrl = config.storageUrl || "https://storage.arky.io/dev";
1711
1765
  const apiConfig = {
@@ -1713,9 +1767,9 @@ function createArkySDK(config) {
1713
1767
  businessId: config.businessId,
1714
1768
  storageUrl,
1715
1769
  baseUrl: config.baseUrl,
1716
- market: config.market || "US",
1717
- setTokens: config.setTokens,
1718
- getTokens: config.getTokens
1770
+ market: config.market,
1771
+ setTokens: config.setToken,
1772
+ getTokens: config.getToken
1719
1773
  };
1720
1774
  const userApi = createUserApi(apiConfig);
1721
1775
  const autoGuest = config.autoGuest !== void 0 ? config.autoGuest : true;
@@ -1736,9 +1790,13 @@ function createArkySDK(config) {
1736
1790
  apiConfig.businessId = businessId;
1737
1791
  },
1738
1792
  getBusinessId: () => apiConfig.businessId,
1793
+ setMarket: (market) => {
1794
+ apiConfig.market = market;
1795
+ },
1796
+ getMarket: () => apiConfig.market,
1739
1797
  isAuthenticated: config.isAuthenticated || (() => false),
1740
1798
  logout: config.logout,
1741
- setTokens: config.setTokens,
1799
+ setToken: config.setToken,
1742
1800
  utils: {
1743
1801
  getImageUrl: (imageBlock, isBlock = true) => getImageUrl(imageBlock, isBlock, storageUrl),
1744
1802
  thumbnailUrl: (service) => thumbnailUrl(service, storageUrl),
@@ -1757,10 +1815,13 @@ function createArkySDK(config) {
1757
1815
  if (autoGuest) {
1758
1816
  Promise.resolve().then(async () => {
1759
1817
  try {
1760
- const tokens = await config.getTokens();
1818
+ const tokens = await config.getToken();
1761
1819
  if (!tokens.accessToken && !tokens.refreshToken) {
1762
1820
  const guestToken = await userApi.getGuestToken({});
1763
- console.log("[SDK Init] Created guest token:", guestToken ? "Success" : "Failed");
1821
+ console.log(
1822
+ "[SDK Init] Created guest token:",
1823
+ guestToken ? "Success" : "Failed"
1824
+ );
1764
1825
  } else {
1765
1826
  console.log("[SDK Init] Using existing token from storage");
1766
1827
  }