@cshah18/sdk
v1.0.0
Published
CoBuy Embedded SDK for browser JavaScript integration
Downloads
96
Readme
CoBuy Embedded SDK
A lightweight, production-ready TypeScript SDK for embedding CoBuy's collaborative purchasing widget in your web applications. The SDK exposes a global window.CoBuy object that can be loaded via a <script> tag.
Features
- 📦 Lightweight: ~7.5 KB (ESM, minified)
- 🎯 Type-Safe: Full TypeScript support with comprehensive type definitions
- 🚀 Easy Integration: Simple
<script>tag integration - ⚙️ Configurable: Support for multiple environments and theme customization
- 🔧 Well-Tested: ESLint + TypeScript strict mode
- 📝 Documented: Comprehensive JSDoc comments and examples
Installation
Via Script Tag (Browser)
<script src="https://cdn.cobuy.app/cobuy-sdk.umd.js"></script>
<script>
window.CoBuy.init({
merchantKey: "your-merchant-key",
env: "production",
});
window.CoBuy.renderWidget({
productId: "prod_123",
container: "#cobuy-widget",
});
</script>Via NPM (for Module Bundlers)
npm install @cobuy/sdkimport CoBuy from "@cobuy/sdk";
CoBuy.init({
merchantKey: "your-merchant-key",
env: "production",
});
CoBuy.renderWidget({
productId: "prod_123",
container: "#cobuy-widget",
});Quick Start
1. Initialize the SDK
CoBuy.init({
merchantKey: "your-unique-merchant-key",
env: "production", // or "local" for localhost:9000
debug: false,
theme: {
primaryColor: "#4f46e5",
textColor: "#1f2937",
},
});2. Render the Widget
CoBuy.renderWidget({
productId: "prod_123",
container: "#widget-container", // CSS selector or HTMLElement
onCheckout: (data) => {
console.log("Checkout initiated:", data);
},
onError: (error) => {
console.error("Widget error:", error);
},
onOpen: () => {
console.log("Widget opened");
},
onClose: () => {
console.log("Widget closed");
},
});API Reference
CoBuy.init(options: CoBuyInitOptions): void
Initializes the SDK with configuration.
Parameters:
interface CoBuyInitOptions {
merchantKey: string; // Required: Your unique merchant key
env?: "production" | "local"; // Default: "production" (use "local" for localhost:9000)
theme?: {
primaryColor?: string; // e.g., "#4f46e5"
secondaryColor?: string;
textColor?: string;
borderRadius?: string;
fontFamily?: string;
};
debug?: boolean; // Default: false
}Example:
CoBuy.init({
merchantKey: "pk_live_abc123xyz",
env: "production",
debug: false,
theme: {
primaryColor: "#4f46e5",
borderRadius: "8px",
},
});CoBuy.renderWidget(options: RenderWidgetOptions): void
Renders the CoBuy widget into a DOM container.
Parameters:
interface RenderWidgetOptions {
productId: string; // Required: The product to display
container: string | HTMLElement; // CSS selector or element
onCheckout?: (data: { groupId: string; productId: string }) => void;
onError?: (error: unknown) => void;
onOpen?: () => void;
onClose?: () => void;
}Example:
CoBuy.renderWidget({
productId: "prod_456",
container: "#cobuy-widget",
onCheckout: (data) => {
console.log(`Group ${data.groupId} checking out product ${data.productId}`);
},
onError: (error) => {
console.error("Checkout failed:", error);
},
});CoBuy.version: string
Returns the SDK version.
console.log(CoBuy.version); // "1.0.0"CoBuy.getApiClient(): ApiClient | null
Returns the initialized API client instance for making direct API calls.
Example:
const apiClient = CoBuy.getApiClient();
if (apiClient) {
const rewardResponse = await apiClient.getProductReward("prod_123");
if (rewardResponse.success) {
console.log("Reward:", rewardResponse.data.reward);
}
}ApiClient.getProductReward(productId: string): Promise<ApiResponse<ProductRewardData>>
Retrieves reward information for a specific product.
Response Structure:
interface ProductRewardData {
productId: string;
reward: {
id: string;
name: string;
type: "percentage" | "fixed" | "points" | "cashback";
value: string;
description: string | null;
remaining_quantity: number;
total_quantity: number;
valid_from: string; // ISO 8601 date
valid_to: string; // ISO 8601 date
status: "active" | "inactive" | "expired";
};
eligibility: {
isEligible: boolean;
reason?: string;
};
}Example:
const apiClient = CoBuy.getApiClient();
const response = await apiClient.getProductReward("prod_123");
if (response.success) {
const { reward, eligibility } = response.data;
if (eligibility.isEligible) {
console.log(`${reward.value}% ${reward.name}`);
console.log(`Valid until: ${reward.valid_to}`);
}
} else {
console.error("Error:", response.error.message);
}API Base URLs
The SDK automatically selects the appropriate API endpoint based on the env parameter:
| Environment | API URL |
| ------------ | ------------------------------- |
| production | https://api.cobuyza.co.za/api |
| local | http://localhost:9000/api |
The backend URLs are managed internally by the SDK for security.
Error Handling
The SDK includes custom error classes:
CoBuyNotInitializedError
Thrown when attempting to use the SDK before calling init().
try {
CoBuy.renderWidget({
/* ... */
});
} catch (error) {
if (error instanceof CoBuyNotInitializedError) {
console.error("SDK not initialized");
}
}CoBuyInvalidConfigError
Thrown when invalid configuration is provided to init().
try {
CoBuy.init({ merchantKey: "" }); // Invalid
} catch (error) {
if (error instanceof CoBuyInvalidConfigError) {
console.error("Invalid configuration:", error.message);
}
}Debugging
Enable debug logging to monitor SDK operations:
CoBuy.init({
merchantKey: "your-key",
debug: true, // Enables console logging
});When debug mode is enabled, the SDK logs:
- SDK initialization details
- Environment and API base URL
- Widget rendering operations
Project Structure
cobuy-sdk/
├── src/
│ ├── index.ts # Entry point, window.CoBuy export
│ ├── core/
│ │ ├── cobuy.ts # Main SDK implementation
│ │ ├── config.ts # Configuration manager
│ │ ├── logger.ts # Logging utility
│ │ ├── types.ts # TypeScript type definitions
│ │ └── errors.ts # Custom error classes
│ └── ui/
│ └── widget/
│ └── widget-root.ts # Widget rendering logic
├── dist/ # Compiled output
│ ├── cobuy-sdk.esm.js # ES Module format
│ ├── cobuy-sdk.esm.js.map # Source map
│ ├── cobuy-sdk.umd.js # UMD format (browser globals)
│ └── cobuy-sdk.umd.js.map # Source map
├── package.json
├── tsconfig.json
├── rollup.config.mjs
└── eslint.config.jsDevelopment
Prerequisites
- Node.js 16+
- npm or yarn
Setup
npm installScripts
# Build the SDK
npm run build
# Watch mode (rebuilds on file changes)
npm run build:watch
# Run ESLint
npm run lint
# Fix ESLint issues
npm run lint:fix
# Type check + lint
npm run checkCode Quality
This project uses:
- TypeScript: Strict mode enabled for type safety
- ESLint: Enforces code standards
- Prettier: Automatic code formatting
- Rollup: Module bundler for optimized output
Building
The SDK is built with Rollup and produces:
- ESM Bundle (
cobuy-sdk.esm.js): For use with modern module bundlers - UMD Bundle (
cobuy-sdk.umd.js): For direct browser inclusion via<script>tag
Type definitions are generated automatically and included in the dist/types/ directory.
Browser Support
- Modern browsers with ES2017+ support
- Chrome 51+
- Firefox 54+
- Safari 10+
- Edge 15+
TypeScript Support
The SDK includes full TypeScript definitions. When using with TypeScript:
import CoBuy from "@cobuy/sdk";
import type { CoBuySDK, CoBuyInitOptions, RenderWidgetOptions } from "@cobuy/sdk";
// All types are available for import
const options: CoBuyInitOptions = {
merchantKey: "key",
env: "production",
};
CoBuy.init(options);Configuration Examples
Minimal Configuration
CoBuy.init({
merchantKey: "pk_live_123abc",
});Full Configuration
CoBuy.init({
merchantKey: "pk_live_123abc",
env: "production",
theme: {
primaryColor: "#4f46e5",
secondaryColor: "#e5e7eb",
textColor: "#1f2937",
borderRadius: "8px",
fontFamily: "'Inter', sans-serif",
},
debug: true,
});With Event Handlers
CoBuy.renderWidget({
productId: "prod_789",
container: "#my-widget",
onOpen: () => {
// Track analytics
analytics.track("cobuy_widget_opened");
},
onCheckout: (data) => {
// Send to your backend
api.post("/order/initiate", data);
},
onError: (error) => {
// Handle errors gracefully
showErrorNotification(error.message);
},
onClose: () => {
// Cleanup
console.log("Widget closed");
},
});License
MIT
Support
For issues, feature requests, or questions, please contact [email protected] or create an issue in the repository.
Version: 1.0.0
Last Updated: December 2025
