@betterstore/sdk
Version:
E-commerce for Developers
811 lines (798 loc) • 23.8 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/index.ts
var index_exports = {};
__export(index_exports, {
createStoreClient: () => createStoreClient,
createStoreHelpers: () => createStoreHelpers,
default: () => createBetterStore
});
module.exports = __toCommonJS(index_exports);
// src/utils/axios.ts
var import_axios = __toESM(require("axios"));
var API_BASE_URL = "https://api.betterstore.io/v1";
var createApiClient = (apiKey, proxy) => {
const client = import_axios.default.create({
baseURL: proxy != null ? proxy : API_BASE_URL,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization"
}
});
client.interceptors.response.use(
(response) => response.data,
(error) => {
var _a, _b;
const apiError = {
isError: true,
status: 500,
message: "An unexpected error occurred"
};
if (error.response) {
apiError.status = error.response.status;
apiError.message = ((_a = error.response.data) == null ? void 0 : _a.error) || "Server error occurred";
apiError.code = (_b = error.response.data) == null ? void 0 : _b.code;
apiError.details = error.response.data;
} else if (error.request) {
apiError.status = 503;
apiError.message = "Service unavailable - no response from server";
apiError.code = "SERVICE_UNAVAILABLE";
apiError.details = error;
} else {
apiError.status = 500;
apiError.message = "Request configuration error";
apiError.code = "REQUEST_SETUP_ERROR";
apiError.details = error;
}
console.error(apiError);
if (apiError.code === "REQUEST_SETUP_ERROR" || apiError.code === "SERVICE_UNAVAILABLE") {
throw apiError;
}
return apiError;
}
);
return client;
};
// src/auth/providers/otp.ts
var OTP = class {
constructor(apiClient) {
this.apiClient = apiClient;
}
signup(params) {
return __async(this, null, function* () {
const data = yield this.apiClient.post(
"/auth/otp/signup",
params
);
return data;
});
}
login(params) {
return __async(this, null, function* () {
const data = yield this.apiClient.post(
"/auth/otp/login",
params
);
return data;
});
}
verify(params) {
return __async(this, null, function* () {
const data = yield this.apiClient.post(
"/auth/otp/verify",
params
);
return data;
});
}
};
// src/auth/index.ts
var Auth = class {
constructor(apiKey, proxy) {
this.apiClient = createApiClient(apiKey, proxy);
this.otp = new OTP(this.apiClient);
}
retrieveSession(id) {
return __async(this, null, function* () {
const data = yield this.apiClient.get(
`/auth/session/${id}`
);
if ("isError" in data && data.isError || !data || !("token" in data)) {
console.error(`Customer session with id ${id} not found`);
return null;
}
return data;
});
}
};
var auth_default = Auth;
// src/checkout/index.ts
var Checkout = class {
constructor(apiKey, proxy) {
this.apiClient = createApiClient(apiKey, proxy);
}
/**
* Create a new checkout session
*/
create(params) {
return __async(this, null, function* () {
const data = yield this.apiClient.post(
"/checkout",
params
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
throw new Error("Failed to create checkout session");
}
return data;
});
}
/**
* Retrieve a checkout session by ID
*/
retrieve(checkoutId) {
return __async(this, null, function* () {
const data = yield this.apiClient.get(
`/checkout/${checkoutId}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Checkout session with id ${checkoutId} not found`);
return null;
}
return data;
});
}
/**
* Update a checkout session
*/
update(checkoutId, params) {
return __async(this, null, function* () {
const data = yield this.apiClient.put(
`/checkout/${checkoutId}`,
params
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Checkout session with id ${checkoutId} not found`);
return null;
}
return data;
});
}
/**
* Apply a discount code to a checkout session
*/
applyDiscountCode(checkoutId, discountCode) {
return __async(this, null, function* () {
const data = yield this.apiClient.post(
`/checkout/${checkoutId}/discounts/apply`,
{ code: discountCode }
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
throw new Error("Failed to apply discount code");
}
return data;
});
}
/**
* Remove a discount from a checkout session
*/
removeDiscount(checkoutId, discountId) {
return __async(this, null, function* () {
const data = yield this.apiClient.delete(
`/checkout/${checkoutId}/discounts/${discountId}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Checkout session with id ${checkoutId} not found`);
return null;
}
return data;
});
}
/**
* Revalidate a checkout session
*/
revalidateDiscounts(checkoutId) {
return __async(this, null, function* () {
const data = yield this.apiClient.get(
`/checkout/${checkoutId}/discounts/revalidate`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Checkout session with id ${checkoutId} not found`);
return null;
}
return data;
});
}
/**
* Get shipping rates for a checkout session
*/
getShippingRates(checkoutId) {
return __async(this, null, function* () {
const data = yield this.apiClient.get(
`/checkout/shipping/${checkoutId}`
);
if ("isError" in data && data.isError || !data || !Array.isArray(data)) {
return [];
}
return data;
});
}
/**
* Generate payment secret for a checkout session
*/
generatePaymentSecret(checkoutId) {
return __async(this, null, function* () {
const data = yield this.apiClient.post(`
/checkout/payment/${checkoutId}`);
if ("isError" in data && data.isError || !data || !("paymentSecret" in data)) {
throw new Error("Failed to generate payment secret");
}
return {
paymentSecret: data.paymentSecret,
publicKey: data.publicKey,
checkoutSession: data.checkoutSession
};
});
}
};
var checkout_default = Checkout;
// src/client/index.ts
var Client = class {
constructor(proxy) {
this.proxy = proxy;
}
/**
* Retrieve a checkout session by ID
*/
retrieveCheckout(clientSecret, checkoutId) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.get(
`/checkout/${checkoutId}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Checkout session with id ${checkoutId} not found`);
return null;
}
return data;
});
}
/**
* Update a checkout session
*/
updateCheckout(clientSecret, checkoutId, params) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.put(
`/checkout/${checkoutId}`,
params
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Checkout session with id ${checkoutId} not found`);
return null;
}
return data;
});
}
/**
* Apply a discount code to a checkout session
*/
applyDiscountCode(clientSecret, checkoutId, discountCode) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.post(
`/checkout/${checkoutId}/discounts/apply`,
{ code: discountCode }
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
throw new Error("Failed to apply discount code");
}
return data;
});
}
/**
* Remove a discount code from a checkout session
*/
removeDiscount(clientSecret, checkoutId, discountId) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.delete(
`/checkout/${checkoutId}/discounts/${discountId}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
throw new Error("Failed to remove discount code");
}
return data;
});
}
/**
* Revalidate a checkout session
*/
revalidateDiscounts(clientSecret, checkoutId) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.get(
`/checkout/${checkoutId}/discounts/revalidate`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Checkout session with id ${checkoutId} not found`);
return null;
}
return data;
});
}
/**
* Get shipping rates for a checkout session
*/
getCheckoutShippingRates(clientSecret, checkoutId) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.get(
`/checkout/shipping/${checkoutId}`
);
if ("isError" in data && data.isError || !data || !Array.isArray(data)) {
return [];
}
return data;
});
}
/**
* Generate payment secret for a checkout session
*/
generateCheckoutPaymentSecret(clientSecret, checkoutId) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.post(`/checkout/payment/${checkoutId}`);
if ("isError" in data && data.isError || !data || !("paymentSecret" in data)) {
throw new Error("Failed to generate payment secret");
}
return {
paymentSecret: data.paymentSecret,
publicKey: data.publicKey,
checkoutSession: data.checkoutSession
};
});
}
/**
* Create a new customer
*/
createCustomer(clientSecret, params) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.post(
"/customer",
params
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
throw new Error("Failed to create customer");
}
return data;
});
}
/**
* Retrieve a customer by ID or email
*/
retrieveCustomer(clientSecret, idOrEmail) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.get(
`/customer/${idOrEmail}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Customer with id or email ${idOrEmail} not found`);
return null;
}
return data;
});
}
/**
* Update a customer
*/
updateCustomer(clientSecret, customerId, params) {
return __async(this, null, function* () {
const apiClient = createApiClient(clientSecret, this.proxy);
const data = yield apiClient.put(
`/customer/${customerId}`,
params
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Customer with id ${customerId} not found`);
return null;
}
return data;
});
}
};
var client_default = Client;
// src/collections/index.ts
var Collections = class {
constructor(apiKey, proxy) {
this.apiClient = createApiClient(apiKey, proxy);
}
list(params) {
return __async(this, null, function* () {
const queryParams = new URLSearchParams();
if (params) {
queryParams.set("params", JSON.stringify(params));
}
const data = yield this.apiClient.get(
`/collections?${queryParams.toString()}`
);
if (!data || !Array.isArray(data) || "isError" in data && data.isError) {
return [];
}
return data;
});
}
retrieve(params) {
return __async(this, null, function* () {
if ("seoHandle" in params) {
const data2 = yield this.apiClient.get(
`/collections/${params.seoHandle}`
);
if ("isError" in data2 && data2.isError || !data2 || !("id" in data2)) {
console.error(
`Collection with seoHandle ${params.seoHandle} not found`
);
return null;
}
return data2;
}
const data = yield this.apiClient.get(
`/collections/id/${params.id}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Collection with id ${params.id} not found`);
return null;
}
return data;
});
}
};
var collections_default = Collections;
// src/customer/index.ts
var Customer = class {
constructor(apiKey, proxy) {
this.apiClient = createApiClient(apiKey, proxy);
}
/**
* Create a new customer
*/
create(params) {
return __async(this, null, function* () {
const data = yield this.apiClient.post(
"/customer",
params
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
throw new Error("Failed to create customer");
}
return data;
});
}
/**
* Retrieve a customer by ID or email
*/
retrieve(idOrEmail) {
return __async(this, null, function* () {
const data = yield this.apiClient.get(
`/customer/${idOrEmail}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Customer with id or email ${idOrEmail} not found`);
return null;
}
return data;
});
}
/**
* Update a customer
*/
update(customerId, params) {
return __async(this, null, function* () {
const data = yield this.apiClient.put(
`/customer/${customerId}`,
params
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Customer with id ${customerId} not found`);
return null;
}
return data;
});
}
/**
* Delete a customer
*/
delete(customerId) {
return __async(this, null, function* () {
yield this.apiClient.delete(`/customer/${customerId}`);
});
}
/**
* Update a customer subscription
*/
updateCustomerSubscription(stripeSubscriptionId, params) {
return __async(this, null, function* () {
const data = yield this.apiClient.put(
`/customer/subscription/${stripeSubscriptionId}`,
params
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
return null;
}
return data;
});
}
};
var customer_default = Customer;
// src/discounts/index.ts
var Discounts = class {
constructor(apiKey, proxy) {
this.apiClient = createApiClient(apiKey, proxy);
}
list(params) {
return __async(this, null, function* () {
const queryParams = new URLSearchParams();
if (params) {
queryParams.set("params", JSON.stringify(params));
}
const data = yield this.apiClient.get(
`/discounts?${queryParams.toString()}`
);
if (!data || !Array.isArray(data) || "isError" in data && data.isError) {
return [];
}
return data;
});
}
retrieve(params) {
return __async(this, null, function* () {
if ("code" in params) {
const data2 = yield this.apiClient.get(
`/discounts/code/${params.code}`
);
if ("isError" in data2 && data2.isError || !data2 || !("id" in data2)) {
console.error(`Discount with code ${params.code} not found`);
return null;
}
return data2;
}
const data = yield this.apiClient.get(
`/discounts/id/${params.id}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Discount with id ${params.id} not found`);
return null;
}
return data;
});
}
};
var discounts_default = Discounts;
// src/helpers/index.ts
var currencyLocales = {
CZK: "cs-CZ",
// Czech Koruna
USD: "en-US",
// US Dollar
EUR: "de-DE",
// Euro (Germany locale)
GBP: "en-GB",
// British Pound
JPY: "ja-JP",
// Japanese Yen
AUD: "en-AU",
// Australian Dollar
CAD: "en-CA",
// Canadian Dollar
NZD: "en-NZ",
// New Zealand Dollar
SEK: "sv-SE",
// Swedish Krona
NOK: "nb-NO",
// Norwegian Krone
DKK: "da-DK",
// Danish Krone
CHF: "de-CH",
// Swiss Franc (German Switzerland)
HUF: "hu-HU",
// Hungarian Forint
PLN: "pl-PL",
// Polish Zloty
BGN: "bg-BG",
// Bulgarian Lev
RON: "ro-RO",
// Romanian Leu
RUB: "ru-RU",
// Russian Ruble
CNY: "zh-CN",
// Chinese Yuan
INR: "en-IN",
// Indian Rupee
BRL: "pt-BR",
// Brazilian Real
MXN: "es-MX",
// Mexican Peso
ZAR: "en-ZA",
// South African Rand
KRW: "ko-KR",
// South Korean Won
MYR: "ms-MY",
// Malaysian Ringgit
SGD: "en-SG",
// Singapore Dollar
TWD: "zh-TW",
// Taiwanese Dollar
THB: "th-TH",
// Thai Baht
IDR: "id-ID",
// Indonesian Rupiah
AED: "ar-AE",
// UAE Dirham
SAR: "ar-SA",
// Saudi Riyal
TRY: "tr-TR"
// Turkish Lira
};
var Helpers = class {
constructor(proxy) {
this.proxy = proxy;
}
formatCurrency(currency) {
var _a;
const locale = (_a = currencyLocales[currency.toUpperCase()]) != null ? _a : void 0;
const formattedCurrency = new Intl.NumberFormat(locale, {
style: "currency",
currency,
currencyDisplay: "symbol"
});
return formattedCurrency.format(0).replace(/[\d.,\s]/g, "").trim();
}
formatPrice(priceInCents, currency, exchangeRate) {
var _a;
const amount = priceInCents / 100 * (exchangeRate != null ? exchangeRate : 1);
const isWhole = amount % 1 === 0;
const locale = (_a = currencyLocales[currency.toUpperCase()]) != null ? _a : void 0;
const formattedPrice = new Intl.NumberFormat(locale, {
style: "currency",
currency,
currencyDisplay: "symbol",
minimumFractionDigits: isWhole ? 0 : 2,
maximumFractionDigits: isWhole ? 0 : 2
}).format(amount);
return formattedPrice;
}
getExchangeRate(baseCurrency, targetCurrency) {
return __async(this, null, function* () {
const apiClient = createApiClient("", this.proxy);
const { data } = yield apiClient.get(`/helpers/rates/${baseCurrency}`);
const rate = data.rates[targetCurrency];
if (!rate) {
throw new Error("Could not get exchange rate for target currency");
}
return rate;
});
}
};
var helpers_default = Helpers;
// src/products/index.ts
var Products = class {
constructor(apiKey, proxy) {
this.apiClient = createApiClient(apiKey, proxy);
}
list(params) {
return __async(this, null, function* () {
const queryParams = new URLSearchParams();
if (params) {
queryParams.set("params", JSON.stringify(params));
}
const data = yield this.apiClient.get(
`/products?${queryParams.toString()}`
);
if (!data || !Array.isArray(data) || "isError" in data && data.isError) {
return [];
}
return data;
});
}
retrieve(params) {
return __async(this, null, function* () {
if ("seoHandle" in params && typeof (params == null ? void 0 : params.seoHandle) === "string") {
const data = yield this.apiClient.get(
`/products/${params.seoHandle}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Product with seoHandle ${params.seoHandle} not found`);
return null;
}
return data;
}
if ("id" in params && typeof (params == null ? void 0 : params.id) === "string") {
const data = yield this.apiClient.get(
`/products/id/${params.id}`
);
if ("isError" in data && data.isError || !data || !("id" in data)) {
console.error(`Product with id ${params.id} not found`);
return null;
}
return data;
}
return null;
});
}
};
var products_default = Products;
// src/index.ts
function createBetterStore(config) {
if (!config.apiKey) {
throw new Error("API key is required.");
}
return {
checkout: new checkout_default(config.apiKey, config.proxy),
customer: new customer_default(config.apiKey, config.proxy),
discounts: new discounts_default(config.apiKey, config.proxy),
collections: new collections_default(config.apiKey, config.proxy),
products: new products_default(config.apiKey, config.proxy),
auth: new auth_default(config.apiKey, config.proxy)
};
}
function createStoreClient(config) {
return new client_default(config == null ? void 0 : config.proxy);
}
function createStoreHelpers(config) {
return new helpers_default(config == null ? void 0 : config.proxy);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createStoreClient,
createStoreHelpers
});