torque-checkout 3.0.0 → 3.1.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/CHANGELOG.md +57 -0
- package/LICENSE +21 -0
- package/README.md +224 -23
- package/dist/index.d.ts +34 -2
- package/dist/index.esm.js +70 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +70 -1
- package/dist/index.js.map +1 -1
- package/package.json +5 -6
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to the `torque-checkout` package will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [3.1.1] - 2026-04-08
|
|
9
|
+
|
|
10
|
+
### Documentation
|
|
11
|
+
- README: **Hosted API surface** table — which SDK methods map to live `app.torque.fi` routes vs. routes not yet deployed
|
|
12
|
+
- Module JSDoc: steer integrators toward `generateCartCheckoutUrl`, `validateCart`, catalog getters, and `getOrderStatus`
|
|
13
|
+
|
|
14
|
+
## [3.1.0] - 2024-12-XX
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- **Product Sync API**: New methods to programmatically sync products from Torque to your ecommerce database
|
|
18
|
+
- `getProducts(businessId?, status?)` - Fetch all products for a business
|
|
19
|
+
- `getProduct(productId)` - Get a single product by ID
|
|
20
|
+
- **New TypeScript Types**:
|
|
21
|
+
- `Product` interface - Base product type for all products (regular and subscription)
|
|
22
|
+
- Enhanced type exports for better TypeScript support
|
|
23
|
+
- **New API Routes** (backend):
|
|
24
|
+
- `GET /api/products` - List all products for a business
|
|
25
|
+
- `GET /api/products/[productId]` - Get a single product
|
|
26
|
+
- `GET /api/products/subscriptions` - Get subscription products (improved implementation)
|
|
27
|
+
- **Enhanced Documentation**:
|
|
28
|
+
- Complete Product Sync Guide with programmatic sync examples
|
|
29
|
+
- Step-by-step integration flow documentation
|
|
30
|
+
- Product matching strategies (SKU, name, ID)
|
|
31
|
+
- Sync examples for different use cases
|
|
32
|
+
|
|
33
|
+
### Improved
|
|
34
|
+
- `getSubscriptionProducts()` now properly maps `basePrice` alias for backward compatibility
|
|
35
|
+
- Better error messages for product-related operations
|
|
36
|
+
- More comprehensive API documentation
|
|
37
|
+
|
|
38
|
+
### Fixed
|
|
39
|
+
- Product type consistency across all methods
|
|
40
|
+
- Subscription product type definitions
|
|
41
|
+
|
|
42
|
+
## [3.0.0] - Previous Release
|
|
43
|
+
|
|
44
|
+
### Features
|
|
45
|
+
- React hooks (`useTorqueCheckout`, `useCart`)
|
|
46
|
+
- Next.js server utilities (`handleCheckoutRequest`, `handleWebhook`)
|
|
47
|
+
- Environment variable support (`createTorqueCheckoutFromEnv`)
|
|
48
|
+
- Enhanced error handling with `TorqueCheckoutError`
|
|
49
|
+
- Comprehensive validation utilities
|
|
50
|
+
- Multiple entry points for better tree-shaking
|
|
51
|
+
- Full TypeScript support with JSDoc
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
[3.1.1]: https://github.com/torque-fi/torque-checkout/compare/v3.1.0...v3.1.1
|
|
56
|
+
[3.1.0]: https://github.com/torque-fi/torque-checkout/compare/v3.0.0...v3.1.0
|
|
57
|
+
[3.0.0]: https://github.com/torque-fi/torque-checkout/releases/tag/v3.0.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Torque
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -35,6 +35,21 @@ The easiest way to integrate Torque checkout into your Next.js eCommerce applica
|
|
|
35
35
|
- **Subscription Support** - Built-in subscription and recurring payment management
|
|
36
36
|
- **Universal** - Works in browser, Node.js, and edge environments
|
|
37
37
|
|
|
38
|
+
### Hosted API surface (app.torque.fi)
|
|
39
|
+
|
|
40
|
+
These methods call **live** routes on the Torque app today:
|
|
41
|
+
|
|
42
|
+
| Method | Endpoint | Notes |
|
|
43
|
+
|--------|----------|--------|
|
|
44
|
+
| `generateCartCheckoutUrl` / `generateProductCheckoutUrl` / `generateSubscriptionCheckoutUrl` | `POST /api/torque-checkout` | Primary integration: returns checkout URL (Bearer API key). |
|
|
45
|
+
| `validateCart` | `POST /api/checkout/validate-cart` | Pre-validates cart lines (same API key as above). |
|
|
46
|
+
| `getProducts`, `getProduct`, `getSubscriptionProducts` | `GET /api/products` … | Catalog sync (Bearer API key). |
|
|
47
|
+
| `getOrderStatus` | `GET /api/checkout/order-status/[orderId]` | Order lookup (`businessId` query). |
|
|
48
|
+
|
|
49
|
+
The following methods are **typed for future use** but call routes that are **not deployed** on the hosted app yet (they will fail at runtime): subscription CRUD/renewals, analytics helpers (`trackCartView`, …), and `sendWebhookEvent` unless your deployment adds matching API routes. Prefer the table above for production integrations.
|
|
50
|
+
|
|
51
|
+
On-chain settlement runs in the **hosted checkout UI** after the customer opens the generated URL; the SDK does not send transactions itself.
|
|
52
|
+
|
|
38
53
|
## Installation
|
|
39
54
|
|
|
40
55
|
```bash
|
|
@@ -343,6 +358,52 @@ console.log('Payment status:', order.paymentStatus)
|
|
|
343
358
|
console.log('Items:', order.items)
|
|
344
359
|
```
|
|
345
360
|
|
|
361
|
+
##### `getProducts(businessId?, status?): Promise<Product[]>`
|
|
362
|
+
|
|
363
|
+
Get all products for a business. Use this to sync your ecommerce catalog with Torque products.
|
|
364
|
+
|
|
365
|
+
```ts
|
|
366
|
+
// Get all active products
|
|
367
|
+
const products = await torque.getProducts(undefined, 'active')
|
|
368
|
+
|
|
369
|
+
// Get all products (any status)
|
|
370
|
+
const allProducts = await torque.getProducts()
|
|
371
|
+
|
|
372
|
+
// Get products for specific business
|
|
373
|
+
const businessProducts = await torque.getProducts('business_123', 'active')
|
|
374
|
+
|
|
375
|
+
// Sync with your database
|
|
376
|
+
products.forEach(product => {
|
|
377
|
+
console.log(`Product: ${product.name} (ID: ${product.id})`)
|
|
378
|
+
// Store product.id in your database as torqueProductId
|
|
379
|
+
})
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
##### `getProduct(productId: string): Promise<Product>`
|
|
383
|
+
|
|
384
|
+
Get a single product by ID.
|
|
385
|
+
|
|
386
|
+
```ts
|
|
387
|
+
const product = await torque.getProduct('j1234567890abcdef')
|
|
388
|
+
|
|
389
|
+
console.log('Product:', product.name)
|
|
390
|
+
console.log('Price:', product.price)
|
|
391
|
+
console.log('Status:', product.status)
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
##### `getSubscriptionProducts(businessId?): Promise<SubscriptionProduct[]>`
|
|
395
|
+
|
|
396
|
+
Get all subscription products for a business.
|
|
397
|
+
|
|
398
|
+
```ts
|
|
399
|
+
const subscriptions = await torque.getSubscriptionProducts()
|
|
400
|
+
|
|
401
|
+
subscriptions.forEach(sub => {
|
|
402
|
+
console.log(`Subscription: ${sub.name}`)
|
|
403
|
+
console.log('Payment plans:', sub.paymentPlans)
|
|
404
|
+
})
|
|
405
|
+
```
|
|
406
|
+
|
|
346
407
|
### React Hooks
|
|
347
408
|
|
|
348
409
|
#### `useTorqueCheckout(options?)`
|
|
@@ -721,14 +782,17 @@ import type {
|
|
|
721
782
|
// Customer types
|
|
722
783
|
CustomerData,
|
|
723
784
|
|
|
785
|
+
// Product types
|
|
786
|
+
Product,
|
|
787
|
+
SubscriptionProduct,
|
|
788
|
+
PaymentPlan,
|
|
789
|
+
|
|
724
790
|
// Order types
|
|
725
791
|
OrderStatus,
|
|
726
792
|
CheckoutResponse,
|
|
727
793
|
|
|
728
794
|
// Subscription types
|
|
729
795
|
Subscription,
|
|
730
|
-
SubscriptionProduct,
|
|
731
|
-
PaymentPlan,
|
|
732
796
|
CreateSubscriptionData,
|
|
733
797
|
UpdateSubscriptionData,
|
|
734
798
|
|
|
@@ -1003,47 +1067,184 @@ MIT © [Torque](https://torque.fi)
|
|
|
1003
1067
|
Torque products are the **source of truth** for checkout. Similar to Stripe's Products/Prices model:
|
|
1004
1068
|
|
|
1005
1069
|
1. **Upload products to Torque** at `/business/products`
|
|
1006
|
-
2. **
|
|
1007
|
-
3. **
|
|
1008
|
-
4. **Torque
|
|
1009
|
-
5. **
|
|
1070
|
+
2. **Get Torque product IDs** (manually or programmatically)
|
|
1071
|
+
3. **Store Torque product IDs** in your ecommerce database
|
|
1072
|
+
4. **Use Torque product IDs** in cart items when calling the SDK
|
|
1073
|
+
5. **Torque validates** all products exist and are active
|
|
1074
|
+
6. **Checkout uses** product data (prices, names) from Torque database
|
|
1010
1075
|
|
|
1011
|
-
###
|
|
1076
|
+
### Step-by-Step Integration Flow
|
|
1012
1077
|
|
|
1013
|
-
**
|
|
1078
|
+
**Step 1: Add Products to Torque**
|
|
1014
1079
|
- Visit [Products Page](https://app.torque.fi/business/products)
|
|
1015
|
-
- Add products
|
|
1016
|
-
-
|
|
1080
|
+
- Add your products with name, price, description, images, etc.
|
|
1081
|
+
- Torque automatically generates a Product ID (e.g., `j1234567890abcdef`)
|
|
1082
|
+
|
|
1083
|
+
**Step 2: Sync Product IDs to Your Database**
|
|
1017
1084
|
|
|
1018
|
-
|
|
1019
|
-
- Export your product catalog (CSV/JSON)
|
|
1020
|
-
- Use Torque API to bulk create products (coming soon)
|
|
1021
|
-
- Map your product IDs to Torque product IDs
|
|
1085
|
+
You have two options:
|
|
1022
1086
|
|
|
1023
|
-
|
|
1024
|
-
- When you update a product in your catalog, update it in Torque too
|
|
1025
|
-
- When you add a new product, create it in Torque and store the ID
|
|
1026
|
-
- When you deactivate a product, set it to "inactive" in Torque
|
|
1087
|
+
#### Option A: Programmatic Sync (Recommended)
|
|
1027
1088
|
|
|
1028
|
-
|
|
1089
|
+
Use the SDK to fetch all products from Torque and sync them with your database:
|
|
1029
1090
|
|
|
1030
1091
|
```ts
|
|
1031
|
-
|
|
1092
|
+
import { createTorqueCheckoutFromEnv } from 'torque-checkout'
|
|
1093
|
+
|
|
1094
|
+
// Server-side: Sync products
|
|
1095
|
+
async function syncProducts() {
|
|
1096
|
+
const torque = createTorqueCheckoutFromEnv()
|
|
1097
|
+
|
|
1098
|
+
// Fetch all active products from Torque
|
|
1099
|
+
const torqueProducts = await torque.getProducts(undefined, 'active')
|
|
1100
|
+
|
|
1101
|
+
// Sync with your database
|
|
1102
|
+
for (const torqueProduct of torqueProducts) {
|
|
1103
|
+
// Match by SKU, name, or your internal ID
|
|
1104
|
+
await db.product.upsert({
|
|
1105
|
+
where: { sku: torqueProduct.sku }, // or match by name/ID
|
|
1106
|
+
update: {
|
|
1107
|
+
torqueProductId: torqueProduct.id, // Store Torque product ID
|
|
1108
|
+
torquePrice: torqueProduct.price,
|
|
1109
|
+
torqueStatus: torqueProduct.status,
|
|
1110
|
+
// ... other fields
|
|
1111
|
+
},
|
|
1112
|
+
create: {
|
|
1113
|
+
sku: torqueProduct.sku || `torque_${torqueProduct.id}`,
|
|
1114
|
+
name: torqueProduct.name,
|
|
1115
|
+
torqueProductId: torqueProduct.id,
|
|
1116
|
+
torquePrice: torqueProduct.price,
|
|
1117
|
+
// ... other fields
|
|
1118
|
+
}
|
|
1119
|
+
})
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
console.log(`Synced ${torqueProducts.length} products`)
|
|
1123
|
+
}
|
|
1124
|
+
```
|
|
1125
|
+
|
|
1126
|
+
**Run this sync:**
|
|
1127
|
+
- On initial setup
|
|
1128
|
+
- Periodically (cron job, webhook, or scheduled task)
|
|
1129
|
+
- After adding new products in Torque
|
|
1130
|
+
|
|
1131
|
+
#### Option B: Manual Copy-Paste
|
|
1132
|
+
|
|
1133
|
+
For small catalogs, manually copy product IDs:
|
|
1134
|
+
|
|
1135
|
+
1. Visit [Products Page](https://app.torque.fi/business/products)
|
|
1136
|
+
2. Copy each product ID (e.g., `j1234567890abcdef`)
|
|
1137
|
+
3. Store in your database: `product.torqueProductId = "j1234567890abcdef"`
|
|
1138
|
+
|
|
1139
|
+
**Step 3: Use Torque Product IDs in Checkout**
|
|
1140
|
+
|
|
1141
|
+
```tsx
|
|
1142
|
+
// Your ecommerce product
|
|
1032
1143
|
interface Product {
|
|
1033
1144
|
id: string // Your internal product ID
|
|
1034
1145
|
name: string
|
|
1035
1146
|
price: number
|
|
1036
|
-
torqueProductId: string // Torque product ID (from
|
|
1037
|
-
|
|
1147
|
+
torqueProductId: string // Torque product ID (synced from Step 2)
|
|
1148
|
+
sku?: string
|
|
1038
1149
|
}
|
|
1039
1150
|
|
|
1040
1151
|
// When customer adds to cart
|
|
1041
1152
|
const cartItem = {
|
|
1042
|
-
productId: product.torqueProductId, // Use Torque ID
|
|
1153
|
+
productId: product.torqueProductId, // ✅ Use Torque ID
|
|
1043
1154
|
quantity: 2
|
|
1155
|
+
// ❌ Don't include price - it comes from Torque
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
// Generate checkout
|
|
1159
|
+
const checkoutUrl = await torque.generateCartCheckoutUrl({
|
|
1160
|
+
items: [cartItem],
|
|
1161
|
+
customer: { email: 'customer@example.com' }
|
|
1162
|
+
})
|
|
1163
|
+
```
|
|
1164
|
+
|
|
1165
|
+
### Complete Sync Example
|
|
1166
|
+
|
|
1167
|
+
```ts
|
|
1168
|
+
// app/api/sync-products/route.ts
|
|
1169
|
+
import { createTorqueCheckoutFromEnv } from 'torque-checkout'
|
|
1170
|
+
import { NextResponse } from 'next/server'
|
|
1171
|
+
|
|
1172
|
+
export async function POST() {
|
|
1173
|
+
try {
|
|
1174
|
+
const torque = createTorqueCheckoutFromEnv()
|
|
1175
|
+
|
|
1176
|
+
// Get all active products from Torque
|
|
1177
|
+
const torqueProducts = await torque.getProducts(undefined, 'active')
|
|
1178
|
+
|
|
1179
|
+
// Sync to your database
|
|
1180
|
+
const results = await Promise.all(
|
|
1181
|
+
torqueProducts.map(async (torqueProduct) => {
|
|
1182
|
+
// Match by SKU if available, otherwise by name
|
|
1183
|
+
const matchKey = torqueProduct.sku || torqueProduct.name
|
|
1184
|
+
|
|
1185
|
+
return await db.product.upsert({
|
|
1186
|
+
where: {
|
|
1187
|
+
OR: [
|
|
1188
|
+
{ sku: matchKey },
|
|
1189
|
+
{ name: torqueProduct.name },
|
|
1190
|
+
{ torqueProductId: torqueProduct.id }
|
|
1191
|
+
]
|
|
1192
|
+
},
|
|
1193
|
+
update: {
|
|
1194
|
+
torqueProductId: torqueProduct.id,
|
|
1195
|
+
torquePrice: torqueProduct.price,
|
|
1196
|
+
torqueStatus: torqueProduct.status,
|
|
1197
|
+
torqueUpdatedAt: new Date(torqueProduct.updatedAt)
|
|
1198
|
+
},
|
|
1199
|
+
create: {
|
|
1200
|
+
name: torqueProduct.name,
|
|
1201
|
+
description: torqueProduct.description,
|
|
1202
|
+
sku: torqueProduct.sku || `torque_${torqueProduct.id}`,
|
|
1203
|
+
torqueProductId: torqueProduct.id,
|
|
1204
|
+
torquePrice: torqueProduct.price,
|
|
1205
|
+
torqueStatus: torqueProduct.status,
|
|
1206
|
+
// ... other fields
|
|
1207
|
+
}
|
|
1208
|
+
})
|
|
1209
|
+
})
|
|
1210
|
+
)
|
|
1211
|
+
|
|
1212
|
+
return NextResponse.json({
|
|
1213
|
+
success: true,
|
|
1214
|
+
synced: results.length,
|
|
1215
|
+
products: results
|
|
1216
|
+
})
|
|
1217
|
+
} catch (error) {
|
|
1218
|
+
return NextResponse.json(
|
|
1219
|
+
{ error: error instanceof Error ? error.message : 'Sync failed' },
|
|
1220
|
+
{ status: 500 }
|
|
1221
|
+
)
|
|
1222
|
+
}
|
|
1044
1223
|
}
|
|
1045
1224
|
```
|
|
1046
1225
|
|
|
1226
|
+
### Keeping Products in Sync
|
|
1227
|
+
|
|
1228
|
+
**When to sync:**
|
|
1229
|
+
- ✅ Initial setup
|
|
1230
|
+
- ✅ After adding products in Torque
|
|
1231
|
+
- ✅ Periodically (daily/weekly cron job)
|
|
1232
|
+
- ✅ After updating product prices in Torque
|
|
1233
|
+
|
|
1234
|
+
**Sync strategies:**
|
|
1235
|
+
1. **Manual trigger**: Call sync API endpoint when needed
|
|
1236
|
+
2. **Scheduled**: Set up a cron job to sync daily
|
|
1237
|
+
3. **Webhook** (coming soon): Auto-sync when products change in Torque
|
|
1238
|
+
4. **On-demand**: Sync before checkout to ensure latest prices
|
|
1239
|
+
|
|
1240
|
+
### Matching Products
|
|
1241
|
+
|
|
1242
|
+
When syncing, match Torque products to your products by:
|
|
1243
|
+
- **SKU** (recommended): Most reliable if you use SKUs
|
|
1244
|
+
- **Product name**: If names are unique
|
|
1245
|
+
- **Torque Product ID**: If already synced before
|
|
1246
|
+
- **Custom metadata**: Store your internal ID in Torque product metadata
|
|
1247
|
+
|
|
1047
1248
|
## Getting Started Checklist
|
|
1048
1249
|
|
|
1049
1250
|
- [ ] Install: `npm install torque-checkout`
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
* Torque Checkout SDK
|
|
3
3
|
* Official SDK for integrating Torque checkout into your eCommerce applications
|
|
4
4
|
*
|
|
5
|
+
* **Hosted app (app.torque.fi):** Use `generateCartCheckoutUrl`, `validateCart`, catalog getters, and `getOrderStatus`.
|
|
6
|
+
* Subscription lifecycle and analytics helpers call routes that may not exist on every deployment; see package README.
|
|
7
|
+
*
|
|
5
8
|
* @packageDocumentation
|
|
6
9
|
*/
|
|
7
10
|
export interface CartItem {
|
|
@@ -51,7 +54,7 @@ export interface PaymentPlan {
|
|
|
51
54
|
maxCycles?: number;
|
|
52
55
|
description?: string;
|
|
53
56
|
}
|
|
54
|
-
export interface
|
|
57
|
+
export interface Product {
|
|
55
58
|
id: string;
|
|
56
59
|
name: string;
|
|
57
60
|
description?: string;
|
|
@@ -62,7 +65,7 @@ export interface SubscriptionProduct {
|
|
|
62
65
|
chainId: number;
|
|
63
66
|
abi?: string;
|
|
64
67
|
};
|
|
65
|
-
|
|
68
|
+
price: number;
|
|
66
69
|
currency: string;
|
|
67
70
|
image?: string;
|
|
68
71
|
images?: string[];
|
|
@@ -84,6 +87,9 @@ export interface SubscriptionProduct {
|
|
|
84
87
|
createdAt: number;
|
|
85
88
|
updatedAt: number;
|
|
86
89
|
}
|
|
90
|
+
export interface SubscriptionProduct extends Product {
|
|
91
|
+
basePrice: number;
|
|
92
|
+
}
|
|
87
93
|
export interface Subscription {
|
|
88
94
|
id: string;
|
|
89
95
|
businessId: string;
|
|
@@ -333,12 +339,38 @@ export declare class TorqueCheckout {
|
|
|
333
339
|
* @returns Promise resolving to array of subscriptions
|
|
334
340
|
*/
|
|
335
341
|
getSubscriptionsDueForRenewal(daysAhead?: number): Promise<Subscription[]>;
|
|
342
|
+
/**
|
|
343
|
+
* Get all products for a business
|
|
344
|
+
* Use this to sync your ecommerce catalog with Torque products
|
|
345
|
+
* @param businessId - Business ID (optional, uses instance businessId if not provided)
|
|
346
|
+
* @param status - Optional status filter ('active', 'inactive', 'draft', 'archived')
|
|
347
|
+
* @returns Promise resolving to array of products
|
|
348
|
+
*
|
|
349
|
+
* @example
|
|
350
|
+
* ```ts
|
|
351
|
+
* const products = await torque.getProducts()
|
|
352
|
+
* // Sync products with your database
|
|
353
|
+
* products.forEach(product => {
|
|
354
|
+
* await db.products.update({
|
|
355
|
+
* where: { sku: product.sku },
|
|
356
|
+
* data: { torqueProductId: product.id }
|
|
357
|
+
* })
|
|
358
|
+
* })
|
|
359
|
+
* ```
|
|
360
|
+
*/
|
|
361
|
+
getProducts(businessId?: string, status?: 'active' | 'inactive' | 'draft' | 'archived'): Promise<Product[]>;
|
|
336
362
|
/**
|
|
337
363
|
* Get subscription products for a business
|
|
338
364
|
* @param businessId - Business ID (optional, uses instance businessId if not provided)
|
|
339
365
|
* @returns Promise resolving to array of subscription products
|
|
340
366
|
*/
|
|
341
367
|
getSubscriptionProducts(businessId?: string): Promise<SubscriptionProduct[]>;
|
|
368
|
+
/**
|
|
369
|
+
* Get a single product by ID
|
|
370
|
+
* @param productId - Product ID (Torque product ID)
|
|
371
|
+
* @returns Promise resolving to product
|
|
372
|
+
*/
|
|
373
|
+
getProduct(productId: string): Promise<Product>;
|
|
342
374
|
/**
|
|
343
375
|
* Get product with payment plans
|
|
344
376
|
* @param productId - Product ID
|
package/dist/index.esm.js
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
* Torque Checkout SDK
|
|
3
3
|
* Official SDK for integrating Torque checkout into your eCommerce applications
|
|
4
4
|
*
|
|
5
|
+
* **Hosted app (app.torque.fi):** Use `generateCartCheckoutUrl`, `validateCart`, catalog getters, and `getOrderStatus`.
|
|
6
|
+
* Subscription lifecycle and analytics helpers call routes that may not exist on every deployment; see package README.
|
|
7
|
+
*
|
|
5
8
|
* @packageDocumentation
|
|
6
9
|
*/
|
|
7
10
|
// ============================================================================
|
|
@@ -460,6 +463,44 @@ class TorqueCheckout {
|
|
|
460
463
|
throw new TorqueCheckoutError(error instanceof Error ? error.message : 'Failed to get subscriptions due for renewal', 'NETWORK_ERROR', 500);
|
|
461
464
|
}
|
|
462
465
|
}
|
|
466
|
+
/**
|
|
467
|
+
* Get all products for a business
|
|
468
|
+
* Use this to sync your ecommerce catalog with Torque products
|
|
469
|
+
* @param businessId - Business ID (optional, uses instance businessId if not provided)
|
|
470
|
+
* @param status - Optional status filter ('active', 'inactive', 'draft', 'archived')
|
|
471
|
+
* @returns Promise resolving to array of products
|
|
472
|
+
*
|
|
473
|
+
* @example
|
|
474
|
+
* ```ts
|
|
475
|
+
* const products = await torque.getProducts()
|
|
476
|
+
* // Sync products with your database
|
|
477
|
+
* products.forEach(product => {
|
|
478
|
+
* await db.products.update({
|
|
479
|
+
* where: { sku: product.sku },
|
|
480
|
+
* data: { torqueProductId: product.id }
|
|
481
|
+
* })
|
|
482
|
+
* })
|
|
483
|
+
* ```
|
|
484
|
+
*/
|
|
485
|
+
async getProducts(businessId, status) {
|
|
486
|
+
const bid = businessId || this.businessId;
|
|
487
|
+
const params = new URLSearchParams({ businessId: bid });
|
|
488
|
+
if (status)
|
|
489
|
+
params.append('status', status);
|
|
490
|
+
try {
|
|
491
|
+
const response = await this.makeRequest(`/api/products?${params}`);
|
|
492
|
+
if (response.error) {
|
|
493
|
+
throw new TorqueCheckoutError(response.message || 'Failed to get products', response.error || 'FETCH_FAILED', response.statusCode || 500);
|
|
494
|
+
}
|
|
495
|
+
return Array.isArray(response) ? response : [];
|
|
496
|
+
}
|
|
497
|
+
catch (error) {
|
|
498
|
+
if (error instanceof TorqueCheckoutError) {
|
|
499
|
+
throw error;
|
|
500
|
+
}
|
|
501
|
+
throw new TorqueCheckoutError(error instanceof Error ? error.message : 'Failed to get products', 'NETWORK_ERROR', 500);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
463
504
|
/**
|
|
464
505
|
* Get subscription products for a business
|
|
465
506
|
* @param businessId - Business ID (optional, uses instance businessId if not provided)
|
|
@@ -472,7 +513,12 @@ class TorqueCheckout {
|
|
|
472
513
|
if (response.error) {
|
|
473
514
|
throw new TorqueCheckoutError(response.message || 'Failed to get subscription products', response.error || 'FETCH_FAILED', response.statusCode || 500);
|
|
474
515
|
}
|
|
475
|
-
|
|
516
|
+
const products = Array.isArray(response) ? response : [];
|
|
517
|
+
// Map to SubscriptionProduct format with basePrice alias
|
|
518
|
+
return products.map(p => ({
|
|
519
|
+
...p,
|
|
520
|
+
basePrice: p.price || p.basePrice || 0
|
|
521
|
+
}));
|
|
476
522
|
}
|
|
477
523
|
catch (error) {
|
|
478
524
|
if (error instanceof TorqueCheckoutError) {
|
|
@@ -481,6 +527,29 @@ class TorqueCheckout {
|
|
|
481
527
|
throw new TorqueCheckoutError(error instanceof Error ? error.message : 'Failed to get subscription products', 'NETWORK_ERROR', 500);
|
|
482
528
|
}
|
|
483
529
|
}
|
|
530
|
+
/**
|
|
531
|
+
* Get a single product by ID
|
|
532
|
+
* @param productId - Product ID (Torque product ID)
|
|
533
|
+
* @returns Promise resolving to product
|
|
534
|
+
*/
|
|
535
|
+
async getProduct(productId) {
|
|
536
|
+
if (!productId || typeof productId !== 'string') {
|
|
537
|
+
throw new TorqueCheckoutError('Product ID is required', 'INVALID_PRODUCT_ID', 400);
|
|
538
|
+
}
|
|
539
|
+
try {
|
|
540
|
+
const response = await this.makeRequest(`/api/products/${productId}`);
|
|
541
|
+
if (response.error) {
|
|
542
|
+
throw new TorqueCheckoutError(response.message || 'Failed to get product', response.error || 'PRODUCT_NOT_FOUND', response.statusCode || 404);
|
|
543
|
+
}
|
|
544
|
+
return response;
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
if (error instanceof TorqueCheckoutError) {
|
|
548
|
+
throw error;
|
|
549
|
+
}
|
|
550
|
+
throw new TorqueCheckoutError(error instanceof Error ? error.message : 'Failed to get product', 'NETWORK_ERROR', 500);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
484
553
|
/**
|
|
485
554
|
* Get product with payment plans
|
|
486
555
|
* @param productId - Product ID
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/index.ts"],"sourcesContent":["/**\n * Torque Checkout SDK\n * Official SDK for integrating Torque checkout into your eCommerce applications\n * \n * @packageDocumentation\n */\n\n// ============================================================================\n// Type Definitions\n// ============================================================================\n\nexport interface CartItem {\n productId: string // Must be a valid Torque product ID (Convex ID format)\n quantity: number\n variant?: string // Optional variant ID if product has variants\n metadata?: Record<string, any> // Optional merchant metadata\n // Note: price is NOT included - prices come from Torque product database\n}\n\nexport interface CustomerData {\n email: string\n firstName?: string\n lastName?: string\n phone?: string\n shippingAddress?: {\n street: string\n city: string\n state: string\n zipCode: string\n country: string\n }\n billingAddress?: {\n street: string\n city: string\n state: string\n zipCode: string\n country: string\n }\n}\n\nexport interface CartOptions {\n domain?: string\n expiresIn?: number\n metadata?: Record<string, any>\n redirectUrl?: string\n}\n\nexport interface CartData {\n items: CartItem[]\n customer?: CustomerData\n options?: CartOptions\n}\n\nexport interface PaymentPlan {\n id: string\n name: string\n price: number\n interval: \"weekly\" | \"monthly\" | \"quarterly\" | \"yearly\"\n intervalCount: number\n trialDays?: number\n maxCycles?: number\n description?: string\n}\n\nexport interface SubscriptionProduct {\n id: string\n name: string\n description?: string\n isSubscription: boolean\n paymentPlans?: PaymentPlan[]\n subscriptionContract?: {\n address: string\n chainId: number\n abi?: string\n }\n basePrice: number\n currency: string\n image?: string\n images?: string[]\n requiresShipping: boolean\n shippingCost?: number\n taxRate?: number\n inventory: number\n status: 'active' | 'inactive' | 'draft' | 'archived'\n sku?: string\n category?: string\n tags?: string[]\n variants?: Array<{\n id: string\n name: string\n price: number\n inventory?: number\n }>\n metadata?: any\n createdAt: number\n updatedAt: number\n}\n\nexport interface Subscription {\n id: string\n businessId: string\n productId: string\n customerId?: string\n customerEmail: string\n customerName: string\n paymentPlanId: string\n status: \"active\" | \"cancelled\" | \"paused\" | \"expired\" | \"past_due\"\n currentPeriodStart: number\n currentPeriodEnd: number\n nextBillingDate: number\n trialStart?: number\n trialEnd?: number\n totalCycles: number\n maxCycles?: number\n lastPaymentDate?: number\n nextPaymentAmount: number\n currency: string\n contractSubscriptionId?: string\n contractAddress?: string\n billingHistory?: Array<{\n cycleNumber: number\n amount: number\n date: number\n status: \"paid\" | \"failed\" | \"pending\"\n transactionId?: string\n }>\n metadata?: any\n createdAt: number\n updatedAt: number\n}\n\nexport interface CreateSubscriptionData {\n businessId: string\n productId: string\n customerEmail: string\n customerName: string\n paymentPlanId: string\n customerId?: string\n metadata?: any\n}\n\nexport interface UpdateSubscriptionData {\n status?: \"active\" | \"cancelled\" | \"paused\" | \"expired\" | \"past_due\"\n pauseUntil?: number\n resumeDate?: number\n metadata?: any\n}\n\nexport interface TorqueConfig {\n businessId: string\n apiKey: string\n baseUrl?: string\n timeout?: number\n}\n\nexport interface BusinessCreationData {\n name: string\n description?: string\n email: string\n phone?: string\n website?: string\n currency?: string\n timezone?: string\n walletAddress: string\n logo?: string\n}\n\nexport interface BusinessProfile {\n id: string\n name: string\n email: string\n apiKey: string\n walletAddress: string\n logo?: string\n website?: string\n status: 'active' | 'pending' | 'suspended'\n}\n\nexport interface CheckoutResponse {\n success: boolean\n checkoutUrl: string\n expiresAt: string\n cartSummary: {\n itemCount: number\n productCount: number\n estimatedTotal: number\n }\n business: {\n id: string\n name: string\n logo?: string\n }\n}\n\nexport interface OrderStatus {\n orderId: string\n status: string\n customer: {\n email: string\n firstName?: string\n lastName?: string\n phone?: string\n } | null\n items: Array<{\n productId: string\n productName: string\n productImage?: string\n quantity: number\n variant?: string\n price: number\n total: number\n }>\n totals: {\n subtotal: number\n shipping: number\n tax: number\n total: number\n }\n paymentStatus: string\n shippingAddress?: any\n billingAddress?: any\n createdAt: number\n updatedAt: number\n metadata: Record<string, any>\n}\n\nexport interface CartValidation {\n valid: boolean\n errors: string[]\n warnings: string[]\n estimatedTotal: number\n}\n\nexport interface TorqueError extends Error {\n code?: string\n statusCode?: number\n details?: any\n}\n\n// ============================================================================\n// Error Classes\n// ============================================================================\n\nexport class TorqueCheckoutError extends Error implements TorqueError {\n code?: string\n statusCode?: number\n details?: any\n\n constructor(message: string, code?: string, statusCode?: number, details?: any) {\n super(message)\n this.name = 'TorqueCheckoutError'\n this.code = code\n this.statusCode = statusCode\n this.details = details\n Object.setPrototypeOf(this, TorqueCheckoutError.prototype)\n }\n}\n\n// ============================================================================\n// Validation Utilities\n// ============================================================================\n\n/**\n * Validates a Convex ID format (e.g., \"j1234567890abcdef\")\n * Convex IDs are alphanumeric strings starting with a letter\n */\nfunction isValidConvexId(id: string): boolean {\n return /^[a-z][a-z0-9]{15,}$/i.test(id)\n}\n\nexport function validateCartItem(item: CartItem): string[] {\n const errors: string[] = []\n \n if (!item.productId || typeof item.productId !== 'string' || item.productId.trim() === '') {\n errors.push('Product ID is required and must be a non-empty string')\n } else if (!isValidConvexId(item.productId)) {\n errors.push('Product ID must be a valid Torque product ID. Products must be uploaded to Torque first at /business/products')\n }\n \n if (typeof item.quantity !== 'number' || item.quantity <= 0 || !Number.isInteger(item.quantity)) {\n errors.push('Quantity must be a positive integer')\n }\n \n // Price validation removed - prices come from Torque product database\n // Prices are fetched from Torque when generating checkout URL\n \n return errors\n}\n\nexport function validateCartData(cart: CartData): string[] {\n const errors: string[] = []\n \n if (!cart.items || !Array.isArray(cart.items) || cart.items.length === 0) {\n errors.push('Cart must contain at least one item')\n return errors\n }\n \n cart.items.forEach((item, index) => {\n const itemErrors = validateCartItem(item)\n itemErrors.forEach(error => errors.push(`Item ${index + 1}: ${error}`))\n })\n \n if (cart.customer?.email && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(cart.customer.email)) {\n errors.push('Customer email must be a valid email address')\n }\n \n return errors\n}\n\nexport function validateConfig(config: TorqueConfig): string[] {\n const errors: string[] = []\n \n if (!config.businessId || typeof config.businessId !== 'string' || config.businessId.trim() === '') {\n errors.push('Business ID is required')\n }\n \n if (!config.apiKey || typeof config.apiKey !== 'string' || config.apiKey.trim() === '') {\n errors.push('API key is required')\n }\n \n if (config.timeout !== undefined && (typeof config.timeout !== 'number' || config.timeout <= 0)) {\n errors.push('Timeout must be a positive number')\n }\n \n return errors\n}\n\n// ============================================================================\n// Main SDK Class\n// ============================================================================\n\nexport class TorqueCheckout {\n private businessId: string\n private apiKey: string\n private baseUrl: string\n private timeout: number\n\n constructor(config: TorqueConfig) {\n const configErrors = validateConfig(config)\n if (configErrors.length > 0) {\n throw new TorqueCheckoutError(\n `Invalid configuration: ${configErrors.join(', ')}`,\n 'INVALID_CONFIG',\n 400,\n { errors: configErrors }\n )\n }\n\n this.businessId = config.businessId.trim()\n this.apiKey = config.apiKey.trim()\n this.baseUrl = (config.baseUrl || 'https://app.torque.fi').replace(/\\/$/, '')\n this.timeout = config.timeout || 30000\n }\n\n /**\n * Generate a cart checkout URL\n * @param cart - Cart data containing items, customer info, and options\n * @returns Promise resolving to checkout URL\n * @throws {TorqueCheckoutError} If cart validation fails or API request fails\n */\n async generateCartCheckoutUrl(cart: CartData): Promise<string> {\n const validationErrors = validateCartData(cart)\n if (validationErrors.length > 0) {\n throw new TorqueCheckoutError(\n `Cart validation failed: ${validationErrors.join(', ')}`,\n 'VALIDATION_ERROR',\n 400,\n { errors: validationErrors }\n )\n }\n\n try {\n const response = await this.makeRequest('/api/torque-checkout', {\n method: 'POST',\n body: {\n businessId: this.businessId,\n cart: {\n items: cart.items\n },\n customerData: cart.customer,\n options: cart.options\n }\n })\n\n if (!response.success) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to generate checkout URL',\n response.error || 'CHECKOUT_GENERATION_FAILED',\n response.statusCode || 500,\n response.details\n )\n }\n\n return response.checkoutUrl\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to generate checkout URL',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Generate a single product checkout URL\n * @param productId - Product ID\n * @param quantity - Quantity (default: 1)\n * @param customer - Optional customer data\n * @param options - Optional cart options\n * @returns Promise resolving to checkout URL\n */\n async generateProductCheckoutUrl(\n productId: string,\n quantity: number = 1,\n customer?: CustomerData,\n options?: CartOptions\n ): Promise<string> {\n return this.generateCartCheckoutUrl({\n items: [{ productId, quantity }],\n customer,\n options\n })\n }\n\n /**\n * Generate a subscription checkout URL\n * @param productId - Subscription product ID\n * @param paymentPlanId - Payment plan ID\n * @param customer - Optional customer data\n * @param options - Optional cart options\n * @returns Promise resolving to checkout URL\n */\n async generateSubscriptionCheckoutUrl(\n productId: string,\n paymentPlanId: string,\n customer?: CustomerData,\n options?: CartOptions\n ): Promise<string> {\n return this.generateCartCheckoutUrl({\n items: [{ \n productId, \n quantity: 1,\n metadata: { \n isSubscription: true, \n paymentPlanId \n }\n }],\n customer,\n options\n })\n }\n\n /**\n * Validate cart data before checkout\n * @param cart - Cart data to validate\n * @returns Promise resolving to validation result\n */\n async validateCart(cart: CartData): Promise<CartValidation> {\n try {\n const response = await this.makeRequest('/api/checkout/validate-cart', {\n method: 'POST',\n body: {\n businessId: this.businessId,\n cart: cart.items,\n customer: cart.customer\n }\n })\n\n return response\n } catch (error) {\n const validationErrors = validateCartData(cart)\n return {\n valid: false,\n errors: error instanceof Error \n ? [error.message, ...validationErrors]\n : ['Validation failed', ...validationErrors],\n warnings: [],\n estimatedTotal: 0\n }\n }\n }\n\n /**\n * Get order status\n * @param orderId - Order ID\n * @returns Promise resolving to order status\n * @throws {TorqueCheckoutError} If order not found or API request fails\n */\n async getOrderStatus(orderId: string): Promise<OrderStatus> {\n if (!orderId || typeof orderId !== 'string') {\n throw new TorqueCheckoutError('Order ID is required', 'INVALID_ORDER_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/checkout/order-status/${orderId}?businessId=${this.businessId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get order status',\n response.error || 'ORDER_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get order status',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Create a new subscription\n * @param data - Subscription creation data\n * @returns Promise resolving to created subscription\n */\n async createSubscription(data: CreateSubscriptionData): Promise<Subscription> {\n try {\n const response = await this.makeRequest('/api/subscriptions/create', {\n method: 'POST',\n body: data\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to create subscription',\n response.error || 'SUBSCRIPTION_CREATION_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to create subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscription by ID\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to subscription\n */\n async getSubscription(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscription',\n response.error || 'SUBSCRIPTION_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions for a business\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @param status - Optional status filter\n * @param limit - Optional limit\n * @returns Promise resolving to array of subscriptions\n */\n async getBusinessSubscriptions(businessId?: string, status?: string, limit?: number): Promise<Subscription[]> {\n const bid = businessId || this.businessId\n const params = new URLSearchParams({ businessId: bid })\n if (status) params.append('status', status)\n if (limit) params.append('limit', limit.toString())\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/business?${params}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get business subscriptions',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get business subscriptions',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions for a customer\n * @param customerEmail - Customer email\n * @returns Promise resolving to array of subscriptions\n */\n async getCustomerSubscriptions(customerEmail: string): Promise<Subscription[]> {\n if (!customerEmail || typeof customerEmail !== 'string' || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(customerEmail)) {\n throw new TorqueCheckoutError('Valid customer email is required', 'INVALID_EMAIL', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/customer/${encodeURIComponent(customerEmail)}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get customer subscriptions',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get customer subscriptions',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Update subscription status\n * @param subscriptionId - Subscription ID\n * @param data - Update data\n * @returns Promise resolving to updated subscription\n */\n async updateSubscription(subscriptionId: string, data: UpdateSubscriptionData): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/update`, {\n method: 'PUT',\n body: data\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to update subscription',\n response.error || 'UPDATE_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to update subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Cancel subscription\n * @param subscriptionId - Subscription ID\n * @param effectiveDate - Optional effective date for cancellation\n * @returns Promise resolving to cancelled subscription\n */\n async cancelSubscription(subscriptionId: string, effectiveDate?: number): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/cancel`, {\n method: 'PUT',\n body: { effectiveDate }\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to cancel subscription',\n response.error || 'CANCEL_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to cancel subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Pause subscription\n * @param subscriptionId - Subscription ID\n * @param resumeDate - Optional resume date\n * @returns Promise resolving to paused subscription\n */\n async pauseSubscription(subscriptionId: string, resumeDate?: number): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/pause`, {\n method: 'PUT',\n body: { resumeDate }\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to pause subscription',\n response.error || 'PAUSE_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to pause subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Resume subscription\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to resumed subscription\n */\n async resumeSubscription(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/resume`, {\n method: 'PUT'\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to resume subscription',\n response.error || 'RESUME_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to resume subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Process subscription renewal\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to renewed subscription\n */\n async processSubscriptionRenewal(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/renew`, {\n method: 'PUT'\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to process subscription renewal',\n response.error || 'RENEWAL_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to process subscription renewal',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions due for renewal\n * @param daysAhead - Number of days ahead to check (default: 7)\n * @returns Promise resolving to array of subscriptions\n */\n async getSubscriptionsDueForRenewal(daysAhead: number = 7): Promise<Subscription[]> {\n if (typeof daysAhead !== 'number' || daysAhead < 0) {\n throw new TorqueCheckoutError('Days ahead must be a non-negative number', 'INVALID_PARAMETER', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/due-for-renewal?daysAhead=${daysAhead}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscriptions due for renewal',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscriptions due for renewal',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscription products for a business\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @returns Promise resolving to array of subscription products\n */\n async getSubscriptionProducts(businessId?: string): Promise<SubscriptionProduct[]> {\n const bid = businessId || this.businessId\n\n try {\n const response = await this.makeRequest(`/api/products/subscriptions?businessId=${bid}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscription products',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscription products',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get product with payment plans\n * @param productId - Product ID\n * @returns Promise resolving to product with payment plans\n */\n async getProductWithPaymentPlans(productId: string): Promise<SubscriptionProduct> {\n if (!productId || typeof productId !== 'string') {\n throw new TorqueCheckoutError('Product ID is required', 'INVALID_PRODUCT_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/products/${productId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get product',\n response.error || 'PRODUCT_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get product',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Send webhook event\n * @param orderId - Order ID\n * @param status - Order status\n * @param customerData - Optional customer data\n * @param metadata - Optional metadata\n */\n async sendWebhookEvent(\n orderId: string,\n status: string,\n customerData?: any,\n metadata?: Record<string, any>\n ): Promise<void> {\n if (!orderId || typeof orderId !== 'string') {\n throw new TorqueCheckoutError('Order ID is required', 'INVALID_ORDER_ID', 400)\n }\n\n try {\n await this.makeRequest('/api/webhooks/order-update', {\n method: 'POST',\n body: {\n orderId,\n status,\n customerData,\n metadata\n }\n })\n } catch (error) {\n // Webhook events are non-critical, log but don't throw\n console.warn('Failed to send webhook event:', error)\n }\n }\n\n /**\n * Track cart view for analytics\n * @param cartId - Cart ID\n * @param cartData - Cart data\n */\n async trackCartView(cartId: string, cartData: CartData): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/cart-view', {\n method: 'POST',\n body: {\n cartId,\n businessId: this.businessId,\n cartData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track cart view:', error)\n }\n }\n\n /**\n * Track checkout completion for analytics\n * @param orderId - Order ID\n * @param checkoutData - Checkout data\n */\n async trackCheckoutComplete(orderId: string, checkoutData: any): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/checkout-complete', {\n method: 'POST',\n body: {\n orderId,\n businessId: this.businessId,\n checkoutData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track checkout completion:', error)\n }\n }\n\n /**\n * Track subscription creation for analytics\n * @param subscriptionId - Subscription ID\n * @param subscriptionData - Subscription data\n */\n async trackSubscriptionCreated(subscriptionId: string, subscriptionData: any): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/subscription-created', {\n method: 'POST',\n body: {\n subscriptionId,\n businessId: this.businessId,\n subscriptionData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track subscription creation:', error)\n }\n }\n\n /**\n * Generate cart hash for caching\n * @param cart - Cart data\n * @returns Cart hash string\n */\n generateCartHash(cart: CartData): string {\n const cartString = JSON.stringify({\n items: cart.items.sort((a, b) => a.productId.localeCompare(b.productId)),\n customer: cart.customer ? { email: cart.customer.email } : null\n })\n \n let hash = 0\n for (let i = 0; i < cartString.length; i++) {\n const char = cartString.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash // Convert to 32-bit integer\n }\n return Math.abs(hash).toString(36)\n }\n\n /**\n * Generate subscription hash for caching\n * @param subscriptionData - Subscription data\n * @returns Subscription hash string\n */\n generateSubscriptionHash(subscriptionData: CreateSubscriptionData): string {\n const subscriptionString = JSON.stringify({\n businessId: subscriptionData.businessId,\n productId: subscriptionData.productId,\n customerEmail: subscriptionData.customerEmail,\n paymentPlanId: subscriptionData.paymentPlanId\n })\n \n let hash = 0\n for (let i = 0; i < subscriptionString.length; i++) {\n const char = subscriptionString.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash\n }\n return Math.abs(hash).toString(36)\n }\n\n /**\n * Make HTTP request to Torque API\n * @private\n */\n private async makeRequest(\n endpoint: string,\n options: { method?: string; body?: any; headers?: Record<string, string> } = {}\n ): Promise<any> {\n const url = `${this.baseUrl}${endpoint}`\n \n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this.timeout)\n\n try {\n const { body, ...fetchOptions } = options\n const response = await fetch(url, {\n ...fetchOptions,\n method: options.method || 'GET',\n body: body ? JSON.stringify(body) : undefined,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n ...options.headers\n },\n signal: controller.signal\n })\n\n clearTimeout(timeoutId)\n\n const responseData = await response.json().catch(() => ({}))\n\n if (!response.ok) {\n throw new TorqueCheckoutError(\n responseData.message || `HTTP ${response.status}: ${response.statusText}`,\n responseData.error || 'API_ERROR',\n response.status,\n responseData.details\n )\n }\n\n return responseData\n } catch (error) {\n clearTimeout(timeoutId)\n \n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new TorqueCheckoutError('Request timeout', 'TIMEOUT', 408)\n }\n throw new TorqueCheckoutError(error.message, 'NETWORK_ERROR', 500)\n }\n \n throw new TorqueCheckoutError('Request failed', 'UNKNOWN_ERROR', 500)\n }\n }\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a new TorqueCheckout instance\n * @param config - Configuration object\n * @returns TorqueCheckout instance\n */\nexport function createTorqueCheckout(config: TorqueConfig): TorqueCheckout {\n return new TorqueCheckout(config)\n}\n\n/**\n * Create a TorqueCheckout instance from environment variables\n * Requires TORQUE_BUSINESS_ID and TORQUE_API_KEY environment variables\n * @param overrides - Optional configuration overrides\n * @returns TorqueCheckout instance\n */\nexport function createTorqueCheckoutFromEnv(overrides?: Partial<TorqueConfig>): TorqueCheckout {\n const businessId = process.env.TORQUE_BUSINESS_ID || overrides?.businessId\n const apiKey = process.env.TORQUE_API_KEY || overrides?.apiKey\n\n if (!businessId || !apiKey) {\n throw new TorqueCheckoutError(\n 'TORQUE_BUSINESS_ID and TORQUE_API_KEY environment variables are required',\n 'MISSING_ENV_VARS',\n 400\n )\n }\n\n return new TorqueCheckout({\n businessId,\n apiKey,\n baseUrl: process.env.TORQUE_BASE_URL || overrides?.baseUrl,\n timeout: overrides?.timeout\n })\n}\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\n// Types are already exported above as interfaces/types\n// This section is for re-exporting if needed for convenience\n// All types are available via named exports from the main module\n"],"names":[],"mappings":"AAAA;;;;;AAKG;AA0OH;AACA;AACA;AAEM,MAAO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G,CACJ;IACH;IAEA,OAAO,IAAI,cAAc,CAAC;QACxB,UAAU;QACV,MAAM;QACN,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,IAAI,SAAS,EAAE,OAAO;QAC1D,OAAO,EAAE,SAAS,EAAE;AACrB,KAAA,CAAC;AACJ;AAEA;AACA;AACA;AAEA;AACA;AACA;;;;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/index.ts"],"sourcesContent":["/**\n * Torque Checkout SDK\n * Official SDK for integrating Torque checkout into your eCommerce applications\n *\n * **Hosted app (app.torque.fi):** Use `generateCartCheckoutUrl`, `validateCart`, catalog getters, and `getOrderStatus`.\n * Subscription lifecycle and analytics helpers call routes that may not exist on every deployment; see package README.\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Type Definitions\n// ============================================================================\n\nexport interface CartItem {\n productId: string // Must be a valid Torque product ID (Convex ID format)\n quantity: number\n variant?: string // Optional variant ID if product has variants\n metadata?: Record<string, any> // Optional merchant metadata\n // Note: price is NOT included - prices come from Torque product database\n}\n\nexport interface CustomerData {\n email: string\n firstName?: string\n lastName?: string\n phone?: string\n shippingAddress?: {\n street: string\n city: string\n state: string\n zipCode: string\n country: string\n }\n billingAddress?: {\n street: string\n city: string\n state: string\n zipCode: string\n country: string\n }\n}\n\nexport interface CartOptions {\n domain?: string\n expiresIn?: number\n metadata?: Record<string, any>\n redirectUrl?: string\n}\n\nexport interface CartData {\n items: CartItem[]\n customer?: CustomerData\n options?: CartOptions\n}\n\nexport interface PaymentPlan {\n id: string\n name: string\n price: number\n interval: \"weekly\" | \"monthly\" | \"quarterly\" | \"yearly\"\n intervalCount: number\n trialDays?: number\n maxCycles?: number\n description?: string\n}\n\nexport interface Product {\n id: string // Torque product ID (Convex ID format, e.g., \"j1234567890abcdef\")\n name: string\n description?: string\n isSubscription: boolean\n paymentPlans?: PaymentPlan[]\n subscriptionContract?: {\n address: string\n chainId: number\n abi?: string\n }\n price: number // Base price (for non-subscription) or base price (for subscription)\n currency: string\n image?: string\n images?: string[]\n requiresShipping: boolean\n shippingCost?: number\n taxRate?: number\n inventory: number // -1 for unlimited\n status: 'active' | 'inactive' | 'draft' | 'archived'\n sku?: string\n category?: string\n tags?: string[]\n variants?: Array<{\n id: string\n name: string\n price: number\n inventory?: number\n }>\n metadata?: any\n createdAt: number\n updatedAt: number\n}\n\n// Alias for backward compatibility\nexport interface SubscriptionProduct extends Product {\n basePrice: number // Alias for price\n}\n\nexport interface Subscription {\n id: string\n businessId: string\n productId: string\n customerId?: string\n customerEmail: string\n customerName: string\n paymentPlanId: string\n status: \"active\" | \"cancelled\" | \"paused\" | \"expired\" | \"past_due\"\n currentPeriodStart: number\n currentPeriodEnd: number\n nextBillingDate: number\n trialStart?: number\n trialEnd?: number\n totalCycles: number\n maxCycles?: number\n lastPaymentDate?: number\n nextPaymentAmount: number\n currency: string\n contractSubscriptionId?: string\n contractAddress?: string\n billingHistory?: Array<{\n cycleNumber: number\n amount: number\n date: number\n status: \"paid\" | \"failed\" | \"pending\"\n transactionId?: string\n }>\n metadata?: any\n createdAt: number\n updatedAt: number\n}\n\nexport interface CreateSubscriptionData {\n businessId: string\n productId: string\n customerEmail: string\n customerName: string\n paymentPlanId: string\n customerId?: string\n metadata?: any\n}\n\nexport interface UpdateSubscriptionData {\n status?: \"active\" | \"cancelled\" | \"paused\" | \"expired\" | \"past_due\"\n pauseUntil?: number\n resumeDate?: number\n metadata?: any\n}\n\nexport interface TorqueConfig {\n businessId: string\n apiKey: string\n baseUrl?: string\n timeout?: number\n}\n\nexport interface BusinessCreationData {\n name: string\n description?: string\n email: string\n phone?: string\n website?: string\n currency?: string\n timezone?: string\n walletAddress: string\n logo?: string\n}\n\nexport interface BusinessProfile {\n id: string\n name: string\n email: string\n apiKey: string\n walletAddress: string\n logo?: string\n website?: string\n status: 'active' | 'pending' | 'suspended'\n}\n\nexport interface CheckoutResponse {\n success: boolean\n checkoutUrl: string\n expiresAt: string\n cartSummary: {\n itemCount: number\n productCount: number\n estimatedTotal: number\n }\n business: {\n id: string\n name: string\n logo?: string\n }\n}\n\nexport interface OrderStatus {\n orderId: string\n status: string\n customer: {\n email: string\n firstName?: string\n lastName?: string\n phone?: string\n } | null\n items: Array<{\n productId: string\n productName: string\n productImage?: string\n quantity: number\n variant?: string\n price: number\n total: number\n }>\n totals: {\n subtotal: number\n shipping: number\n tax: number\n total: number\n }\n paymentStatus: string\n shippingAddress?: any\n billingAddress?: any\n createdAt: number\n updatedAt: number\n metadata: Record<string, any>\n}\n\nexport interface CartValidation {\n valid: boolean\n errors: string[]\n warnings: string[]\n estimatedTotal: number\n}\n\nexport interface TorqueError extends Error {\n code?: string\n statusCode?: number\n details?: any\n}\n\n// ============================================================================\n// Error Classes\n// ============================================================================\n\nexport class TorqueCheckoutError extends Error implements TorqueError {\n code?: string\n statusCode?: number\n details?: any\n\n constructor(message: string, code?: string, statusCode?: number, details?: any) {\n super(message)\n this.name = 'TorqueCheckoutError'\n this.code = code\n this.statusCode = statusCode\n this.details = details\n Object.setPrototypeOf(this, TorqueCheckoutError.prototype)\n }\n}\n\n// ============================================================================\n// Validation Utilities\n// ============================================================================\n\n/**\n * Validates a Convex ID format (e.g., \"j1234567890abcdef\")\n * Convex IDs are alphanumeric strings starting with a letter\n */\nfunction isValidConvexId(id: string): boolean {\n return /^[a-z][a-z0-9]{15,}$/i.test(id)\n}\n\nexport function validateCartItem(item: CartItem): string[] {\n const errors: string[] = []\n \n if (!item.productId || typeof item.productId !== 'string' || item.productId.trim() === '') {\n errors.push('Product ID is required and must be a non-empty string')\n } else if (!isValidConvexId(item.productId)) {\n errors.push('Product ID must be a valid Torque product ID. Products must be uploaded to Torque first at /business/products')\n }\n \n if (typeof item.quantity !== 'number' || item.quantity <= 0 || !Number.isInteger(item.quantity)) {\n errors.push('Quantity must be a positive integer')\n }\n \n // Price validation removed - prices come from Torque product database\n // Prices are fetched from Torque when generating checkout URL\n \n return errors\n}\n\nexport function validateCartData(cart: CartData): string[] {\n const errors: string[] = []\n \n if (!cart.items || !Array.isArray(cart.items) || cart.items.length === 0) {\n errors.push('Cart must contain at least one item')\n return errors\n }\n \n cart.items.forEach((item, index) => {\n const itemErrors = validateCartItem(item)\n itemErrors.forEach(error => errors.push(`Item ${index + 1}: ${error}`))\n })\n \n if (cart.customer?.email && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(cart.customer.email)) {\n errors.push('Customer email must be a valid email address')\n }\n \n return errors\n}\n\nexport function validateConfig(config: TorqueConfig): string[] {\n const errors: string[] = []\n \n if (!config.businessId || typeof config.businessId !== 'string' || config.businessId.trim() === '') {\n errors.push('Business ID is required')\n }\n \n if (!config.apiKey || typeof config.apiKey !== 'string' || config.apiKey.trim() === '') {\n errors.push('API key is required')\n }\n \n if (config.timeout !== undefined && (typeof config.timeout !== 'number' || config.timeout <= 0)) {\n errors.push('Timeout must be a positive number')\n }\n \n return errors\n}\n\n// ============================================================================\n// Main SDK Class\n// ============================================================================\n\nexport class TorqueCheckout {\n private businessId: string\n private apiKey: string\n private baseUrl: string\n private timeout: number\n\n constructor(config: TorqueConfig) {\n const configErrors = validateConfig(config)\n if (configErrors.length > 0) {\n throw new TorqueCheckoutError(\n `Invalid configuration: ${configErrors.join(', ')}`,\n 'INVALID_CONFIG',\n 400,\n { errors: configErrors }\n )\n }\n\n this.businessId = config.businessId.trim()\n this.apiKey = config.apiKey.trim()\n this.baseUrl = (config.baseUrl || 'https://app.torque.fi').replace(/\\/$/, '')\n this.timeout = config.timeout || 30000\n }\n\n /**\n * Generate a cart checkout URL\n * @param cart - Cart data containing items, customer info, and options\n * @returns Promise resolving to checkout URL\n * @throws {TorqueCheckoutError} If cart validation fails or API request fails\n */\n async generateCartCheckoutUrl(cart: CartData): Promise<string> {\n const validationErrors = validateCartData(cart)\n if (validationErrors.length > 0) {\n throw new TorqueCheckoutError(\n `Cart validation failed: ${validationErrors.join(', ')}`,\n 'VALIDATION_ERROR',\n 400,\n { errors: validationErrors }\n )\n }\n\n try {\n const response = await this.makeRequest('/api/torque-checkout', {\n method: 'POST',\n body: {\n businessId: this.businessId,\n cart: {\n items: cart.items\n },\n customerData: cart.customer,\n options: cart.options\n }\n })\n\n if (!response.success) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to generate checkout URL',\n response.error || 'CHECKOUT_GENERATION_FAILED',\n response.statusCode || 500,\n response.details\n )\n }\n\n return response.checkoutUrl\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to generate checkout URL',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Generate a single product checkout URL\n * @param productId - Product ID\n * @param quantity - Quantity (default: 1)\n * @param customer - Optional customer data\n * @param options - Optional cart options\n * @returns Promise resolving to checkout URL\n */\n async generateProductCheckoutUrl(\n productId: string,\n quantity: number = 1,\n customer?: CustomerData,\n options?: CartOptions\n ): Promise<string> {\n return this.generateCartCheckoutUrl({\n items: [{ productId, quantity }],\n customer,\n options\n })\n }\n\n /**\n * Generate a subscription checkout URL\n * @param productId - Subscription product ID\n * @param paymentPlanId - Payment plan ID\n * @param customer - Optional customer data\n * @param options - Optional cart options\n * @returns Promise resolving to checkout URL\n */\n async generateSubscriptionCheckoutUrl(\n productId: string,\n paymentPlanId: string,\n customer?: CustomerData,\n options?: CartOptions\n ): Promise<string> {\n return this.generateCartCheckoutUrl({\n items: [{ \n productId, \n quantity: 1,\n metadata: { \n isSubscription: true, \n paymentPlanId \n }\n }],\n customer,\n options\n })\n }\n\n /**\n * Validate cart data before checkout\n * @param cart - Cart data to validate\n * @returns Promise resolving to validation result\n */\n async validateCart(cart: CartData): Promise<CartValidation> {\n try {\n const response = await this.makeRequest('/api/checkout/validate-cart', {\n method: 'POST',\n body: {\n businessId: this.businessId,\n cart: cart.items,\n customer: cart.customer\n }\n })\n\n return response\n } catch (error) {\n const validationErrors = validateCartData(cart)\n return {\n valid: false,\n errors: error instanceof Error \n ? [error.message, ...validationErrors]\n : ['Validation failed', ...validationErrors],\n warnings: [],\n estimatedTotal: 0\n }\n }\n }\n\n /**\n * Get order status\n * @param orderId - Order ID\n * @returns Promise resolving to order status\n * @throws {TorqueCheckoutError} If order not found or API request fails\n */\n async getOrderStatus(orderId: string): Promise<OrderStatus> {\n if (!orderId || typeof orderId !== 'string') {\n throw new TorqueCheckoutError('Order ID is required', 'INVALID_ORDER_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/checkout/order-status/${orderId}?businessId=${this.businessId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get order status',\n response.error || 'ORDER_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get order status',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Create a new subscription\n * @param data - Subscription creation data\n * @returns Promise resolving to created subscription\n */\n async createSubscription(data: CreateSubscriptionData): Promise<Subscription> {\n try {\n const response = await this.makeRequest('/api/subscriptions/create', {\n method: 'POST',\n body: data\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to create subscription',\n response.error || 'SUBSCRIPTION_CREATION_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to create subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscription by ID\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to subscription\n */\n async getSubscription(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscription',\n response.error || 'SUBSCRIPTION_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions for a business\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @param status - Optional status filter\n * @param limit - Optional limit\n * @returns Promise resolving to array of subscriptions\n */\n async getBusinessSubscriptions(businessId?: string, status?: string, limit?: number): Promise<Subscription[]> {\n const bid = businessId || this.businessId\n const params = new URLSearchParams({ businessId: bid })\n if (status) params.append('status', status)\n if (limit) params.append('limit', limit.toString())\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/business?${params}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get business subscriptions',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get business subscriptions',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions for a customer\n * @param customerEmail - Customer email\n * @returns Promise resolving to array of subscriptions\n */\n async getCustomerSubscriptions(customerEmail: string): Promise<Subscription[]> {\n if (!customerEmail || typeof customerEmail !== 'string' || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(customerEmail)) {\n throw new TorqueCheckoutError('Valid customer email is required', 'INVALID_EMAIL', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/customer/${encodeURIComponent(customerEmail)}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get customer subscriptions',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get customer subscriptions',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Update subscription status\n * @param subscriptionId - Subscription ID\n * @param data - Update data\n * @returns Promise resolving to updated subscription\n */\n async updateSubscription(subscriptionId: string, data: UpdateSubscriptionData): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/update`, {\n method: 'PUT',\n body: data\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to update subscription',\n response.error || 'UPDATE_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to update subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Cancel subscription\n * @param subscriptionId - Subscription ID\n * @param effectiveDate - Optional effective date for cancellation\n * @returns Promise resolving to cancelled subscription\n */\n async cancelSubscription(subscriptionId: string, effectiveDate?: number): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/cancel`, {\n method: 'PUT',\n body: { effectiveDate }\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to cancel subscription',\n response.error || 'CANCEL_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to cancel subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Pause subscription\n * @param subscriptionId - Subscription ID\n * @param resumeDate - Optional resume date\n * @returns Promise resolving to paused subscription\n */\n async pauseSubscription(subscriptionId: string, resumeDate?: number): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/pause`, {\n method: 'PUT',\n body: { resumeDate }\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to pause subscription',\n response.error || 'PAUSE_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to pause subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Resume subscription\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to resumed subscription\n */\n async resumeSubscription(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/resume`, {\n method: 'PUT'\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to resume subscription',\n response.error || 'RESUME_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to resume subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Process subscription renewal\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to renewed subscription\n */\n async processSubscriptionRenewal(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/renew`, {\n method: 'PUT'\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to process subscription renewal',\n response.error || 'RENEWAL_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to process subscription renewal',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions due for renewal\n * @param daysAhead - Number of days ahead to check (default: 7)\n * @returns Promise resolving to array of subscriptions\n */\n async getSubscriptionsDueForRenewal(daysAhead: number = 7): Promise<Subscription[]> {\n if (typeof daysAhead !== 'number' || daysAhead < 0) {\n throw new TorqueCheckoutError('Days ahead must be a non-negative number', 'INVALID_PARAMETER', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/due-for-renewal?daysAhead=${daysAhead}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscriptions due for renewal',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscriptions due for renewal',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get all products for a business\n * Use this to sync your ecommerce catalog with Torque products\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @param status - Optional status filter ('active', 'inactive', 'draft', 'archived')\n * @returns Promise resolving to array of products\n * \n * @example\n * ```ts\n * const products = await torque.getProducts()\n * // Sync products with your database\n * products.forEach(product => {\n * await db.products.update({\n * where: { sku: product.sku },\n * data: { torqueProductId: product.id }\n * })\n * })\n * ```\n */\n async getProducts(businessId?: string, status?: 'active' | 'inactive' | 'draft' | 'archived'): Promise<Product[]> {\n const bid = businessId || this.businessId\n const params = new URLSearchParams({ businessId: bid })\n if (status) params.append('status', status)\n\n try {\n const response = await this.makeRequest(`/api/products?${params}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get products',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get products',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscription products for a business\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @returns Promise resolving to array of subscription products\n */\n async getSubscriptionProducts(businessId?: string): Promise<SubscriptionProduct[]> {\n const bid = businessId || this.businessId\n\n try {\n const response = await this.makeRequest(`/api/products/subscriptions?businessId=${bid}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscription products',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n const products = Array.isArray(response) ? response : []\n // Map to SubscriptionProduct format with basePrice alias\n return products.map(p => ({\n ...p,\n basePrice: p.price || p.basePrice || 0\n }))\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscription products',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get a single product by ID\n * @param productId - Product ID (Torque product ID)\n * @returns Promise resolving to product\n */\n async getProduct(productId: string): Promise<Product> {\n if (!productId || typeof productId !== 'string') {\n throw new TorqueCheckoutError('Product ID is required', 'INVALID_PRODUCT_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/products/${productId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get product',\n response.error || 'PRODUCT_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get product',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get product with payment plans\n * @param productId - Product ID\n * @returns Promise resolving to product with payment plans\n */\n async getProductWithPaymentPlans(productId: string): Promise<SubscriptionProduct> {\n if (!productId || typeof productId !== 'string') {\n throw new TorqueCheckoutError('Product ID is required', 'INVALID_PRODUCT_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/products/${productId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get product',\n response.error || 'PRODUCT_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get product',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Send webhook event\n * @param orderId - Order ID\n * @param status - Order status\n * @param customerData - Optional customer data\n * @param metadata - Optional metadata\n */\n async sendWebhookEvent(\n orderId: string,\n status: string,\n customerData?: any,\n metadata?: Record<string, any>\n ): Promise<void> {\n if (!orderId || typeof orderId !== 'string') {\n throw new TorqueCheckoutError('Order ID is required', 'INVALID_ORDER_ID', 400)\n }\n\n try {\n await this.makeRequest('/api/webhooks/order-update', {\n method: 'POST',\n body: {\n orderId,\n status,\n customerData,\n metadata\n }\n })\n } catch (error) {\n // Webhook events are non-critical, log but don't throw\n console.warn('Failed to send webhook event:', error)\n }\n }\n\n /**\n * Track cart view for analytics\n * @param cartId - Cart ID\n * @param cartData - Cart data\n */\n async trackCartView(cartId: string, cartData: CartData): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/cart-view', {\n method: 'POST',\n body: {\n cartId,\n businessId: this.businessId,\n cartData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track cart view:', error)\n }\n }\n\n /**\n * Track checkout completion for analytics\n * @param orderId - Order ID\n * @param checkoutData - Checkout data\n */\n async trackCheckoutComplete(orderId: string, checkoutData: any): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/checkout-complete', {\n method: 'POST',\n body: {\n orderId,\n businessId: this.businessId,\n checkoutData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track checkout completion:', error)\n }\n }\n\n /**\n * Track subscription creation for analytics\n * @param subscriptionId - Subscription ID\n * @param subscriptionData - Subscription data\n */\n async trackSubscriptionCreated(subscriptionId: string, subscriptionData: any): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/subscription-created', {\n method: 'POST',\n body: {\n subscriptionId,\n businessId: this.businessId,\n subscriptionData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track subscription creation:', error)\n }\n }\n\n /**\n * Generate cart hash for caching\n * @param cart - Cart data\n * @returns Cart hash string\n */\n generateCartHash(cart: CartData): string {\n const cartString = JSON.stringify({\n items: cart.items.sort((a, b) => a.productId.localeCompare(b.productId)),\n customer: cart.customer ? { email: cart.customer.email } : null\n })\n \n let hash = 0\n for (let i = 0; i < cartString.length; i++) {\n const char = cartString.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash // Convert to 32-bit integer\n }\n return Math.abs(hash).toString(36)\n }\n\n /**\n * Generate subscription hash for caching\n * @param subscriptionData - Subscription data\n * @returns Subscription hash string\n */\n generateSubscriptionHash(subscriptionData: CreateSubscriptionData): string {\n const subscriptionString = JSON.stringify({\n businessId: subscriptionData.businessId,\n productId: subscriptionData.productId,\n customerEmail: subscriptionData.customerEmail,\n paymentPlanId: subscriptionData.paymentPlanId\n })\n \n let hash = 0\n for (let i = 0; i < subscriptionString.length; i++) {\n const char = subscriptionString.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash\n }\n return Math.abs(hash).toString(36)\n }\n\n /**\n * Make HTTP request to Torque API\n * @private\n */\n private async makeRequest(\n endpoint: string,\n options: { method?: string; body?: any; headers?: Record<string, string> } = {}\n ): Promise<any> {\n const url = `${this.baseUrl}${endpoint}`\n \n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this.timeout)\n\n try {\n const { body, ...fetchOptions } = options\n const response = await fetch(url, {\n ...fetchOptions,\n method: options.method || 'GET',\n body: body ? JSON.stringify(body) : undefined,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n ...options.headers\n },\n signal: controller.signal\n })\n\n clearTimeout(timeoutId)\n\n const responseData = await response.json().catch(() => ({}))\n\n if (!response.ok) {\n throw new TorqueCheckoutError(\n responseData.message || `HTTP ${response.status}: ${response.statusText}`,\n responseData.error || 'API_ERROR',\n response.status,\n responseData.details\n )\n }\n\n return responseData\n } catch (error) {\n clearTimeout(timeoutId)\n \n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new TorqueCheckoutError('Request timeout', 'TIMEOUT', 408)\n }\n throw new TorqueCheckoutError(error.message, 'NETWORK_ERROR', 500)\n }\n \n throw new TorqueCheckoutError('Request failed', 'UNKNOWN_ERROR', 500)\n }\n }\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a new TorqueCheckout instance\n * @param config - Configuration object\n * @returns TorqueCheckout instance\n */\nexport function createTorqueCheckout(config: TorqueConfig): TorqueCheckout {\n return new TorqueCheckout(config)\n}\n\n/**\n * Create a TorqueCheckout instance from environment variables\n * Requires TORQUE_BUSINESS_ID and TORQUE_API_KEY environment variables\n * @param overrides - Optional configuration overrides\n * @returns TorqueCheckout instance\n */\nexport function createTorqueCheckoutFromEnv(overrides?: Partial<TorqueConfig>): TorqueCheckout {\n const businessId = process.env.TORQUE_BUSINESS_ID || overrides?.businessId\n const apiKey = process.env.TORQUE_API_KEY || overrides?.apiKey\n\n if (!businessId || !apiKey) {\n throw new TorqueCheckoutError(\n 'TORQUE_BUSINESS_ID and TORQUE_API_KEY environment variables are required',\n 'MISSING_ENV_VARS',\n 400\n )\n }\n\n return new TorqueCheckout({\n businessId,\n apiKey,\n baseUrl: process.env.TORQUE_BASE_URL || overrides?.baseUrl,\n timeout: overrides?.timeout\n })\n}\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\n// Types are already exported above as interfaces/types\n// This section is for re-exporting if needed for convenience\n// All types are available via named exports from the main module\n"],"names":[],"mappings":"AAAA;;;;;;;;AAQG;AA+OH;AACA;AACA;AAEM,MAAO,mBAAoB,SAAQ,KAAK,CAAA;AAK5C,IAAA,WAAA,CAAY,OAAe,EAAE,IAAa,EAAE,UAAmB,EAAE,OAAa,EAAA;QAC5E,KAAK,CAAC,OAAO,CAAC;AACd,QAAA,IAAI,CAAC,IAAI,GAAG,qBAAqB;AACjC,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI;AAChB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU;AAC5B,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;QACtB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,mBAAmB,CAAC,SAAS,CAAC;IAC5D;AACD;AAED;AACA;AACA;AAEA;;;AAGG;AACH,SAAS,eAAe,CAAC,EAAU,EAAA;AACjC,IAAA,OAAO,uBAAuB,CAAC,IAAI,CAAC,EAAE,CAAC;AACzC;AAEM,SAAU,gBAAgB,CAAC,IAAc,EAAA;IAC7C,MAAM,MAAM,GAAa,EAAE;IAE3B,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,OAAO,IAAI,CAAC,SAAS,KAAK,QAAQ,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AACzF,QAAA,MAAM,CAAC,IAAI,CAAC,uDAAuD,CAAC;IACtE;SAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;AAC3C,QAAA,MAAM,CAAC,IAAI,CAAC,+GAA+G,CAAC;IAC9H;IAEA,IAAI,OAAO,IAAI,CAAC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@
|
|
|
4
4
|
* Torque Checkout SDK
|
|
5
5
|
* Official SDK for integrating Torque checkout into your eCommerce applications
|
|
6
6
|
*
|
|
7
|
+
* **Hosted app (app.torque.fi):** Use `generateCartCheckoutUrl`, `validateCart`, catalog getters, and `getOrderStatus`.
|
|
8
|
+
* Subscription lifecycle and analytics helpers call routes that may not exist on every deployment; see package README.
|
|
9
|
+
*
|
|
7
10
|
* @packageDocumentation
|
|
8
11
|
*/
|
|
9
12
|
// ============================================================================
|
|
@@ -462,6 +465,44 @@ class TorqueCheckout {
|
|
|
462
465
|
throw new TorqueCheckoutError(error instanceof Error ? error.message : 'Failed to get subscriptions due for renewal', 'NETWORK_ERROR', 500);
|
|
463
466
|
}
|
|
464
467
|
}
|
|
468
|
+
/**
|
|
469
|
+
* Get all products for a business
|
|
470
|
+
* Use this to sync your ecommerce catalog with Torque products
|
|
471
|
+
* @param businessId - Business ID (optional, uses instance businessId if not provided)
|
|
472
|
+
* @param status - Optional status filter ('active', 'inactive', 'draft', 'archived')
|
|
473
|
+
* @returns Promise resolving to array of products
|
|
474
|
+
*
|
|
475
|
+
* @example
|
|
476
|
+
* ```ts
|
|
477
|
+
* const products = await torque.getProducts()
|
|
478
|
+
* // Sync products with your database
|
|
479
|
+
* products.forEach(product => {
|
|
480
|
+
* await db.products.update({
|
|
481
|
+
* where: { sku: product.sku },
|
|
482
|
+
* data: { torqueProductId: product.id }
|
|
483
|
+
* })
|
|
484
|
+
* })
|
|
485
|
+
* ```
|
|
486
|
+
*/
|
|
487
|
+
async getProducts(businessId, status) {
|
|
488
|
+
const bid = businessId || this.businessId;
|
|
489
|
+
const params = new URLSearchParams({ businessId: bid });
|
|
490
|
+
if (status)
|
|
491
|
+
params.append('status', status);
|
|
492
|
+
try {
|
|
493
|
+
const response = await this.makeRequest(`/api/products?${params}`);
|
|
494
|
+
if (response.error) {
|
|
495
|
+
throw new TorqueCheckoutError(response.message || 'Failed to get products', response.error || 'FETCH_FAILED', response.statusCode || 500);
|
|
496
|
+
}
|
|
497
|
+
return Array.isArray(response) ? response : [];
|
|
498
|
+
}
|
|
499
|
+
catch (error) {
|
|
500
|
+
if (error instanceof TorqueCheckoutError) {
|
|
501
|
+
throw error;
|
|
502
|
+
}
|
|
503
|
+
throw new TorqueCheckoutError(error instanceof Error ? error.message : 'Failed to get products', 'NETWORK_ERROR', 500);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
465
506
|
/**
|
|
466
507
|
* Get subscription products for a business
|
|
467
508
|
* @param businessId - Business ID (optional, uses instance businessId if not provided)
|
|
@@ -474,7 +515,12 @@ class TorqueCheckout {
|
|
|
474
515
|
if (response.error) {
|
|
475
516
|
throw new TorqueCheckoutError(response.message || 'Failed to get subscription products', response.error || 'FETCH_FAILED', response.statusCode || 500);
|
|
476
517
|
}
|
|
477
|
-
|
|
518
|
+
const products = Array.isArray(response) ? response : [];
|
|
519
|
+
// Map to SubscriptionProduct format with basePrice alias
|
|
520
|
+
return products.map(p => ({
|
|
521
|
+
...p,
|
|
522
|
+
basePrice: p.price || p.basePrice || 0
|
|
523
|
+
}));
|
|
478
524
|
}
|
|
479
525
|
catch (error) {
|
|
480
526
|
if (error instanceof TorqueCheckoutError) {
|
|
@@ -483,6 +529,29 @@ class TorqueCheckout {
|
|
|
483
529
|
throw new TorqueCheckoutError(error instanceof Error ? error.message : 'Failed to get subscription products', 'NETWORK_ERROR', 500);
|
|
484
530
|
}
|
|
485
531
|
}
|
|
532
|
+
/**
|
|
533
|
+
* Get a single product by ID
|
|
534
|
+
* @param productId - Product ID (Torque product ID)
|
|
535
|
+
* @returns Promise resolving to product
|
|
536
|
+
*/
|
|
537
|
+
async getProduct(productId) {
|
|
538
|
+
if (!productId || typeof productId !== 'string') {
|
|
539
|
+
throw new TorqueCheckoutError('Product ID is required', 'INVALID_PRODUCT_ID', 400);
|
|
540
|
+
}
|
|
541
|
+
try {
|
|
542
|
+
const response = await this.makeRequest(`/api/products/${productId}`);
|
|
543
|
+
if (response.error) {
|
|
544
|
+
throw new TorqueCheckoutError(response.message || 'Failed to get product', response.error || 'PRODUCT_NOT_FOUND', response.statusCode || 404);
|
|
545
|
+
}
|
|
546
|
+
return response;
|
|
547
|
+
}
|
|
548
|
+
catch (error) {
|
|
549
|
+
if (error instanceof TorqueCheckoutError) {
|
|
550
|
+
throw error;
|
|
551
|
+
}
|
|
552
|
+
throw new TorqueCheckoutError(error instanceof Error ? error.message : 'Failed to get product', 'NETWORK_ERROR', 500);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
486
555
|
/**
|
|
487
556
|
* Get product with payment plans
|
|
488
557
|
* @param productId - Product ID
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["/**\n * Torque Checkout SDK\n * Official SDK for integrating Torque checkout into your eCommerce applications\n * \n * @packageDocumentation\n */\n\n// ============================================================================\n// Type Definitions\n// ============================================================================\n\nexport interface CartItem {\n productId: string // Must be a valid Torque product ID (Convex ID format)\n quantity: number\n variant?: string // Optional variant ID if product has variants\n metadata?: Record<string, any> // Optional merchant metadata\n // Note: price is NOT included - prices come from Torque product database\n}\n\nexport interface CustomerData {\n email: string\n firstName?: string\n lastName?: string\n phone?: string\n shippingAddress?: {\n street: string\n city: string\n state: string\n zipCode: string\n country: string\n }\n billingAddress?: {\n street: string\n city: string\n state: string\n zipCode: string\n country: string\n }\n}\n\nexport interface CartOptions {\n domain?: string\n expiresIn?: number\n metadata?: Record<string, any>\n redirectUrl?: string\n}\n\nexport interface CartData {\n items: CartItem[]\n customer?: CustomerData\n options?: CartOptions\n}\n\nexport interface PaymentPlan {\n id: string\n name: string\n price: number\n interval: \"weekly\" | \"monthly\" | \"quarterly\" | \"yearly\"\n intervalCount: number\n trialDays?: number\n maxCycles?: number\n description?: string\n}\n\nexport interface SubscriptionProduct {\n id: string\n name: string\n description?: string\n isSubscription: boolean\n paymentPlans?: PaymentPlan[]\n subscriptionContract?: {\n address: string\n chainId: number\n abi?: string\n }\n basePrice: number\n currency: string\n image?: string\n images?: string[]\n requiresShipping: boolean\n shippingCost?: number\n taxRate?: number\n inventory: number\n status: 'active' | 'inactive' | 'draft' | 'archived'\n sku?: string\n category?: string\n tags?: string[]\n variants?: Array<{\n id: string\n name: string\n price: number\n inventory?: number\n }>\n metadata?: any\n createdAt: number\n updatedAt: number\n}\n\nexport interface Subscription {\n id: string\n businessId: string\n productId: string\n customerId?: string\n customerEmail: string\n customerName: string\n paymentPlanId: string\n status: \"active\" | \"cancelled\" | \"paused\" | \"expired\" | \"past_due\"\n currentPeriodStart: number\n currentPeriodEnd: number\n nextBillingDate: number\n trialStart?: number\n trialEnd?: number\n totalCycles: number\n maxCycles?: number\n lastPaymentDate?: number\n nextPaymentAmount: number\n currency: string\n contractSubscriptionId?: string\n contractAddress?: string\n billingHistory?: Array<{\n cycleNumber: number\n amount: number\n date: number\n status: \"paid\" | \"failed\" | \"pending\"\n transactionId?: string\n }>\n metadata?: any\n createdAt: number\n updatedAt: number\n}\n\nexport interface CreateSubscriptionData {\n businessId: string\n productId: string\n customerEmail: string\n customerName: string\n paymentPlanId: string\n customerId?: string\n metadata?: any\n}\n\nexport interface UpdateSubscriptionData {\n status?: \"active\" | \"cancelled\" | \"paused\" | \"expired\" | \"past_due\"\n pauseUntil?: number\n resumeDate?: number\n metadata?: any\n}\n\nexport interface TorqueConfig {\n businessId: string\n apiKey: string\n baseUrl?: string\n timeout?: number\n}\n\nexport interface BusinessCreationData {\n name: string\n description?: string\n email: string\n phone?: string\n website?: string\n currency?: string\n timezone?: string\n walletAddress: string\n logo?: string\n}\n\nexport interface BusinessProfile {\n id: string\n name: string\n email: string\n apiKey: string\n walletAddress: string\n logo?: string\n website?: string\n status: 'active' | 'pending' | 'suspended'\n}\n\nexport interface CheckoutResponse {\n success: boolean\n checkoutUrl: string\n expiresAt: string\n cartSummary: {\n itemCount: number\n productCount: number\n estimatedTotal: number\n }\n business: {\n id: string\n name: string\n logo?: string\n }\n}\n\nexport interface OrderStatus {\n orderId: string\n status: string\n customer: {\n email: string\n firstName?: string\n lastName?: string\n phone?: string\n } | null\n items: Array<{\n productId: string\n productName: string\n productImage?: string\n quantity: number\n variant?: string\n price: number\n total: number\n }>\n totals: {\n subtotal: number\n shipping: number\n tax: number\n total: number\n }\n paymentStatus: string\n shippingAddress?: any\n billingAddress?: any\n createdAt: number\n updatedAt: number\n metadata: Record<string, any>\n}\n\nexport interface CartValidation {\n valid: boolean\n errors: string[]\n warnings: string[]\n estimatedTotal: number\n}\n\nexport interface TorqueError extends Error {\n code?: string\n statusCode?: number\n details?: any\n}\n\n// ============================================================================\n// Error Classes\n// ============================================================================\n\nexport class TorqueCheckoutError extends Error implements TorqueError {\n code?: string\n statusCode?: number\n details?: any\n\n constructor(message: string, code?: string, statusCode?: number, details?: any) {\n super(message)\n this.name = 'TorqueCheckoutError'\n this.code = code\n this.statusCode = statusCode\n this.details = details\n Object.setPrototypeOf(this, TorqueCheckoutError.prototype)\n }\n}\n\n// ============================================================================\n// Validation Utilities\n// ============================================================================\n\n/**\n * Validates a Convex ID format (e.g., \"j1234567890abcdef\")\n * Convex IDs are alphanumeric strings starting with a letter\n */\nfunction isValidConvexId(id: string): boolean {\n return /^[a-z][a-z0-9]{15,}$/i.test(id)\n}\n\nexport function validateCartItem(item: CartItem): string[] {\n const errors: string[] = []\n \n if (!item.productId || typeof item.productId !== 'string' || item.productId.trim() === '') {\n errors.push('Product ID is required and must be a non-empty string')\n } else if (!isValidConvexId(item.productId)) {\n errors.push('Product ID must be a valid Torque product ID. Products must be uploaded to Torque first at /business/products')\n }\n \n if (typeof item.quantity !== 'number' || item.quantity <= 0 || !Number.isInteger(item.quantity)) {\n errors.push('Quantity must be a positive integer')\n }\n \n // Price validation removed - prices come from Torque product database\n // Prices are fetched from Torque when generating checkout URL\n \n return errors\n}\n\nexport function validateCartData(cart: CartData): string[] {\n const errors: string[] = []\n \n if (!cart.items || !Array.isArray(cart.items) || cart.items.length === 0) {\n errors.push('Cart must contain at least one item')\n return errors\n }\n \n cart.items.forEach((item, index) => {\n const itemErrors = validateCartItem(item)\n itemErrors.forEach(error => errors.push(`Item ${index + 1}: ${error}`))\n })\n \n if (cart.customer?.email && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(cart.customer.email)) {\n errors.push('Customer email must be a valid email address')\n }\n \n return errors\n}\n\nexport function validateConfig(config: TorqueConfig): string[] {\n const errors: string[] = []\n \n if (!config.businessId || typeof config.businessId !== 'string' || config.businessId.trim() === '') {\n errors.push('Business ID is required')\n }\n \n if (!config.apiKey || typeof config.apiKey !== 'string' || config.apiKey.trim() === '') {\n errors.push('API key is required')\n }\n \n if (config.timeout !== undefined && (typeof config.timeout !== 'number' || config.timeout <= 0)) {\n errors.push('Timeout must be a positive number')\n }\n \n return errors\n}\n\n// ============================================================================\n// Main SDK Class\n// ============================================================================\n\nexport class TorqueCheckout {\n private businessId: string\n private apiKey: string\n private baseUrl: string\n private timeout: number\n\n constructor(config: TorqueConfig) {\n const configErrors = validateConfig(config)\n if (configErrors.length > 0) {\n throw new TorqueCheckoutError(\n `Invalid configuration: ${configErrors.join(', ')}`,\n 'INVALID_CONFIG',\n 400,\n { errors: configErrors }\n )\n }\n\n this.businessId = config.businessId.trim()\n this.apiKey = config.apiKey.trim()\n this.baseUrl = (config.baseUrl || 'https://app.torque.fi').replace(/\\/$/, '')\n this.timeout = config.timeout || 30000\n }\n\n /**\n * Generate a cart checkout URL\n * @param cart - Cart data containing items, customer info, and options\n * @returns Promise resolving to checkout URL\n * @throws {TorqueCheckoutError} If cart validation fails or API request fails\n */\n async generateCartCheckoutUrl(cart: CartData): Promise<string> {\n const validationErrors = validateCartData(cart)\n if (validationErrors.length > 0) {\n throw new TorqueCheckoutError(\n `Cart validation failed: ${validationErrors.join(', ')}`,\n 'VALIDATION_ERROR',\n 400,\n { errors: validationErrors }\n )\n }\n\n try {\n const response = await this.makeRequest('/api/torque-checkout', {\n method: 'POST',\n body: {\n businessId: this.businessId,\n cart: {\n items: cart.items\n },\n customerData: cart.customer,\n options: cart.options\n }\n })\n\n if (!response.success) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to generate checkout URL',\n response.error || 'CHECKOUT_GENERATION_FAILED',\n response.statusCode || 500,\n response.details\n )\n }\n\n return response.checkoutUrl\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to generate checkout URL',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Generate a single product checkout URL\n * @param productId - Product ID\n * @param quantity - Quantity (default: 1)\n * @param customer - Optional customer data\n * @param options - Optional cart options\n * @returns Promise resolving to checkout URL\n */\n async generateProductCheckoutUrl(\n productId: string,\n quantity: number = 1,\n customer?: CustomerData,\n options?: CartOptions\n ): Promise<string> {\n return this.generateCartCheckoutUrl({\n items: [{ productId, quantity }],\n customer,\n options\n })\n }\n\n /**\n * Generate a subscription checkout URL\n * @param productId - Subscription product ID\n * @param paymentPlanId - Payment plan ID\n * @param customer - Optional customer data\n * @param options - Optional cart options\n * @returns Promise resolving to checkout URL\n */\n async generateSubscriptionCheckoutUrl(\n productId: string,\n paymentPlanId: string,\n customer?: CustomerData,\n options?: CartOptions\n ): Promise<string> {\n return this.generateCartCheckoutUrl({\n items: [{ \n productId, \n quantity: 1,\n metadata: { \n isSubscription: true, \n paymentPlanId \n }\n }],\n customer,\n options\n })\n }\n\n /**\n * Validate cart data before checkout\n * @param cart - Cart data to validate\n * @returns Promise resolving to validation result\n */\n async validateCart(cart: CartData): Promise<CartValidation> {\n try {\n const response = await this.makeRequest('/api/checkout/validate-cart', {\n method: 'POST',\n body: {\n businessId: this.businessId,\n cart: cart.items,\n customer: cart.customer\n }\n })\n\n return response\n } catch (error) {\n const validationErrors = validateCartData(cart)\n return {\n valid: false,\n errors: error instanceof Error \n ? [error.message, ...validationErrors]\n : ['Validation failed', ...validationErrors],\n warnings: [],\n estimatedTotal: 0\n }\n }\n }\n\n /**\n * Get order status\n * @param orderId - Order ID\n * @returns Promise resolving to order status\n * @throws {TorqueCheckoutError} If order not found or API request fails\n */\n async getOrderStatus(orderId: string): Promise<OrderStatus> {\n if (!orderId || typeof orderId !== 'string') {\n throw new TorqueCheckoutError('Order ID is required', 'INVALID_ORDER_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/checkout/order-status/${orderId}?businessId=${this.businessId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get order status',\n response.error || 'ORDER_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get order status',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Create a new subscription\n * @param data - Subscription creation data\n * @returns Promise resolving to created subscription\n */\n async createSubscription(data: CreateSubscriptionData): Promise<Subscription> {\n try {\n const response = await this.makeRequest('/api/subscriptions/create', {\n method: 'POST',\n body: data\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to create subscription',\n response.error || 'SUBSCRIPTION_CREATION_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to create subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscription by ID\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to subscription\n */\n async getSubscription(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscription',\n response.error || 'SUBSCRIPTION_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions for a business\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @param status - Optional status filter\n * @param limit - Optional limit\n * @returns Promise resolving to array of subscriptions\n */\n async getBusinessSubscriptions(businessId?: string, status?: string, limit?: number): Promise<Subscription[]> {\n const bid = businessId || this.businessId\n const params = new URLSearchParams({ businessId: bid })\n if (status) params.append('status', status)\n if (limit) params.append('limit', limit.toString())\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/business?${params}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get business subscriptions',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get business subscriptions',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions for a customer\n * @param customerEmail - Customer email\n * @returns Promise resolving to array of subscriptions\n */\n async getCustomerSubscriptions(customerEmail: string): Promise<Subscription[]> {\n if (!customerEmail || typeof customerEmail !== 'string' || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(customerEmail)) {\n throw new TorqueCheckoutError('Valid customer email is required', 'INVALID_EMAIL', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/customer/${encodeURIComponent(customerEmail)}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get customer subscriptions',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get customer subscriptions',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Update subscription status\n * @param subscriptionId - Subscription ID\n * @param data - Update data\n * @returns Promise resolving to updated subscription\n */\n async updateSubscription(subscriptionId: string, data: UpdateSubscriptionData): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/update`, {\n method: 'PUT',\n body: data\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to update subscription',\n response.error || 'UPDATE_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to update subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Cancel subscription\n * @param subscriptionId - Subscription ID\n * @param effectiveDate - Optional effective date for cancellation\n * @returns Promise resolving to cancelled subscription\n */\n async cancelSubscription(subscriptionId: string, effectiveDate?: number): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/cancel`, {\n method: 'PUT',\n body: { effectiveDate }\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to cancel subscription',\n response.error || 'CANCEL_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to cancel subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Pause subscription\n * @param subscriptionId - Subscription ID\n * @param resumeDate - Optional resume date\n * @returns Promise resolving to paused subscription\n */\n async pauseSubscription(subscriptionId: string, resumeDate?: number): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/pause`, {\n method: 'PUT',\n body: { resumeDate }\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to pause subscription',\n response.error || 'PAUSE_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to pause subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Resume subscription\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to resumed subscription\n */\n async resumeSubscription(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/resume`, {\n method: 'PUT'\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to resume subscription',\n response.error || 'RESUME_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to resume subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Process subscription renewal\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to renewed subscription\n */\n async processSubscriptionRenewal(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/renew`, {\n method: 'PUT'\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to process subscription renewal',\n response.error || 'RENEWAL_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to process subscription renewal',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions due for renewal\n * @param daysAhead - Number of days ahead to check (default: 7)\n * @returns Promise resolving to array of subscriptions\n */\n async getSubscriptionsDueForRenewal(daysAhead: number = 7): Promise<Subscription[]> {\n if (typeof daysAhead !== 'number' || daysAhead < 0) {\n throw new TorqueCheckoutError('Days ahead must be a non-negative number', 'INVALID_PARAMETER', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/due-for-renewal?daysAhead=${daysAhead}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscriptions due for renewal',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscriptions due for renewal',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscription products for a business\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @returns Promise resolving to array of subscription products\n */\n async getSubscriptionProducts(businessId?: string): Promise<SubscriptionProduct[]> {\n const bid = businessId || this.businessId\n\n try {\n const response = await this.makeRequest(`/api/products/subscriptions?businessId=${bid}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscription products',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscription products',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get product with payment plans\n * @param productId - Product ID\n * @returns Promise resolving to product with payment plans\n */\n async getProductWithPaymentPlans(productId: string): Promise<SubscriptionProduct> {\n if (!productId || typeof productId !== 'string') {\n throw new TorqueCheckoutError('Product ID is required', 'INVALID_PRODUCT_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/products/${productId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get product',\n response.error || 'PRODUCT_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get product',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Send webhook event\n * @param orderId - Order ID\n * @param status - Order status\n * @param customerData - Optional customer data\n * @param metadata - Optional metadata\n */\n async sendWebhookEvent(\n orderId: string,\n status: string,\n customerData?: any,\n metadata?: Record<string, any>\n ): Promise<void> {\n if (!orderId || typeof orderId !== 'string') {\n throw new TorqueCheckoutError('Order ID is required', 'INVALID_ORDER_ID', 400)\n }\n\n try {\n await this.makeRequest('/api/webhooks/order-update', {\n method: 'POST',\n body: {\n orderId,\n status,\n customerData,\n metadata\n }\n })\n } catch (error) {\n // Webhook events are non-critical, log but don't throw\n console.warn('Failed to send webhook event:', error)\n }\n }\n\n /**\n * Track cart view for analytics\n * @param cartId - Cart ID\n * @param cartData - Cart data\n */\n async trackCartView(cartId: string, cartData: CartData): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/cart-view', {\n method: 'POST',\n body: {\n cartId,\n businessId: this.businessId,\n cartData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track cart view:', error)\n }\n }\n\n /**\n * Track checkout completion for analytics\n * @param orderId - Order ID\n * @param checkoutData - Checkout data\n */\n async trackCheckoutComplete(orderId: string, checkoutData: any): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/checkout-complete', {\n method: 'POST',\n body: {\n orderId,\n businessId: this.businessId,\n checkoutData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track checkout completion:', error)\n }\n }\n\n /**\n * Track subscription creation for analytics\n * @param subscriptionId - Subscription ID\n * @param subscriptionData - Subscription data\n */\n async trackSubscriptionCreated(subscriptionId: string, subscriptionData: any): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/subscription-created', {\n method: 'POST',\n body: {\n subscriptionId,\n businessId: this.businessId,\n subscriptionData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track subscription creation:', error)\n }\n }\n\n /**\n * Generate cart hash for caching\n * @param cart - Cart data\n * @returns Cart hash string\n */\n generateCartHash(cart: CartData): string {\n const cartString = JSON.stringify({\n items: cart.items.sort((a, b) => a.productId.localeCompare(b.productId)),\n customer: cart.customer ? { email: cart.customer.email } : null\n })\n \n let hash = 0\n for (let i = 0; i < cartString.length; i++) {\n const char = cartString.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash // Convert to 32-bit integer\n }\n return Math.abs(hash).toString(36)\n }\n\n /**\n * Generate subscription hash for caching\n * @param subscriptionData - Subscription data\n * @returns Subscription hash string\n */\n generateSubscriptionHash(subscriptionData: CreateSubscriptionData): string {\n const subscriptionString = JSON.stringify({\n businessId: subscriptionData.businessId,\n productId: subscriptionData.productId,\n customerEmail: subscriptionData.customerEmail,\n paymentPlanId: subscriptionData.paymentPlanId\n })\n \n let hash = 0\n for (let i = 0; i < subscriptionString.length; i++) {\n const char = subscriptionString.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash\n }\n return Math.abs(hash).toString(36)\n }\n\n /**\n * Make HTTP request to Torque API\n * @private\n */\n private async makeRequest(\n endpoint: string,\n options: { method?: string; body?: any; headers?: Record<string, string> } = {}\n ): Promise<any> {\n const url = `${this.baseUrl}${endpoint}`\n \n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this.timeout)\n\n try {\n const { body, ...fetchOptions } = options\n const response = await fetch(url, {\n ...fetchOptions,\n method: options.method || 'GET',\n body: body ? JSON.stringify(body) : undefined,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n ...options.headers\n },\n signal: controller.signal\n })\n\n clearTimeout(timeoutId)\n\n const responseData = await response.json().catch(() => ({}))\n\n if (!response.ok) {\n throw new TorqueCheckoutError(\n responseData.message || `HTTP ${response.status}: ${response.statusText}`,\n responseData.error || 'API_ERROR',\n response.status,\n responseData.details\n )\n }\n\n return responseData\n } catch (error) {\n clearTimeout(timeoutId)\n \n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new TorqueCheckoutError('Request timeout', 'TIMEOUT', 408)\n }\n throw new TorqueCheckoutError(error.message, 'NETWORK_ERROR', 500)\n }\n \n throw new TorqueCheckoutError('Request failed', 'UNKNOWN_ERROR', 500)\n }\n }\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a new TorqueCheckout instance\n * @param config - Configuration object\n * @returns TorqueCheckout instance\n */\nexport function createTorqueCheckout(config: TorqueConfig): TorqueCheckout {\n return new TorqueCheckout(config)\n}\n\n/**\n * Create a TorqueCheckout instance from environment variables\n * Requires TORQUE_BUSINESS_ID and TORQUE_API_KEY environment variables\n * @param overrides - Optional configuration overrides\n * @returns TorqueCheckout instance\n */\nexport function createTorqueCheckoutFromEnv(overrides?: Partial<TorqueConfig>): TorqueCheckout {\n const businessId = process.env.TORQUE_BUSINESS_ID || overrides?.businessId\n const apiKey = process.env.TORQUE_API_KEY || overrides?.apiKey\n\n if (!businessId || !apiKey) {\n throw new TorqueCheckoutError(\n 'TORQUE_BUSINESS_ID and TORQUE_API_KEY environment variables are required',\n 'MISSING_ENV_VARS',\n 400\n )\n }\n\n return new TorqueCheckout({\n businessId,\n apiKey,\n baseUrl: process.env.TORQUE_BASE_URL || overrides?.baseUrl,\n timeout: overrides?.timeout\n })\n}\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\n// Types are already exported above as interfaces/types\n// This section is for re-exporting if needed for convenience\n// All types are available via named exports from the main module\n"],"names":[],"mappings":";;AAAA;;;;;AAKG;AA0OH;AACA;AACA;AAEM,MAAO,mBAAoB,SAAQ,KAAK,CAAA;AAK5C,IAAA,WAAA,CAAY,OAAe,EAAE,IAAa,EAAE,UAAmB,EAAE,OAAa,EAAA;QAC5E,KAAK,CAAC,OAAO,CAAC;AACd,QAAA,IAAI,CAAC,IAAI,GAAG,qBAAqB;AACjC,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI;AAChB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU;AAC5B,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;QACtB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,mBAAmB,CAAC,SAAS,CAAC;IAC5D;AACD;AAED;AACA;AACA;AAEA;;;AAGG;AACH,SAAS,eAAe,CAAC,EAAU,EAAA;AACjC,IAAA,OAAO,uBAAuB,CAAC,IAAI,CAAC,EAAE,CAAC;AACzC;AAEM,SAAU,gBAAgB,CAAC,IAAc,EAAA;IAC7C,MAAM,MAAM,GAAa,EAAE;IAE3B,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,OAAO,IAAI,CAAC,SAAS,KAAK,QAAQ,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AACzF,QAAA,MAAM,CAAC,IAAI,CAAC,uDAAuD,CAAC;IACtE;SAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE;AAC3C,QAAA,MAAM,CAAC,IAAI,CAAC,+GAA+G,CAAC;IAC9H;IAEA,IAAI,OAAO,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI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MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,kBAAkB,IAAI,SAAS,EAAE,UAAU;IAC1E,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,SAAS,EAAE,MAAM;AAE9D,IAAA,IAAI,CAAC,UAAU,IAAI,CAAC,MAAM,EAAE;QAC1B,MAAM,IAAI,mBAAmB,CAC3B,0EAA0E,EAC1E,kBAAkB,EAClB,GAAG,CACJ;IACH;IAEA,OAAO,IAAI,cAAc,CAAC;QACxB,UAAU;QACV,MAAM;QACN,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,IAAI,SAAS,EAAE,OAAO;QAC1D,OAAO,EAAE,SAAS,EAAE;AACrB,KAAA,CAAC;AACJ;AAEA;AACA;AACA;AAEA;AACA;AACA;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["/**\n * Torque Checkout SDK\n * Official SDK for integrating Torque checkout into your eCommerce applications\n *\n * **Hosted app (app.torque.fi):** Use `generateCartCheckoutUrl`, `validateCart`, catalog getters, and `getOrderStatus`.\n * Subscription lifecycle and analytics helpers call routes that may not exist on every deployment; see package README.\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Type Definitions\n// ============================================================================\n\nexport interface CartItem {\n productId: string // Must be a valid Torque product ID (Convex ID format)\n quantity: number\n variant?: string // Optional variant ID if product has variants\n metadata?: Record<string, any> // Optional merchant metadata\n // Note: price is NOT included - prices come from Torque product database\n}\n\nexport interface CustomerData {\n email: string\n firstName?: string\n lastName?: string\n phone?: string\n shippingAddress?: {\n street: string\n city: string\n state: string\n zipCode: string\n country: string\n }\n billingAddress?: {\n street: string\n city: string\n state: string\n zipCode: string\n country: string\n }\n}\n\nexport interface CartOptions {\n domain?: string\n expiresIn?: number\n metadata?: Record<string, any>\n redirectUrl?: string\n}\n\nexport interface CartData {\n items: CartItem[]\n customer?: CustomerData\n options?: CartOptions\n}\n\nexport interface PaymentPlan {\n id: string\n name: string\n price: number\n interval: \"weekly\" | \"monthly\" | \"quarterly\" | \"yearly\"\n intervalCount: number\n trialDays?: number\n maxCycles?: number\n description?: string\n}\n\nexport interface Product {\n id: string // Torque product ID (Convex ID format, e.g., \"j1234567890abcdef\")\n name: string\n description?: string\n isSubscription: boolean\n paymentPlans?: PaymentPlan[]\n subscriptionContract?: {\n address: string\n chainId: number\n abi?: string\n }\n price: number // Base price (for non-subscription) or base price (for subscription)\n currency: string\n image?: string\n images?: string[]\n requiresShipping: boolean\n shippingCost?: number\n taxRate?: number\n inventory: number // -1 for unlimited\n status: 'active' | 'inactive' | 'draft' | 'archived'\n sku?: string\n category?: string\n tags?: string[]\n variants?: Array<{\n id: string\n name: string\n price: number\n inventory?: number\n }>\n metadata?: any\n createdAt: number\n updatedAt: number\n}\n\n// Alias for backward compatibility\nexport interface SubscriptionProduct extends Product {\n basePrice: number // Alias for price\n}\n\nexport interface Subscription {\n id: string\n businessId: string\n productId: string\n customerId?: string\n customerEmail: string\n customerName: string\n paymentPlanId: string\n status: \"active\" | \"cancelled\" | \"paused\" | \"expired\" | \"past_due\"\n currentPeriodStart: number\n currentPeriodEnd: number\n nextBillingDate: number\n trialStart?: number\n trialEnd?: number\n totalCycles: number\n maxCycles?: number\n lastPaymentDate?: number\n nextPaymentAmount: number\n currency: string\n contractSubscriptionId?: string\n contractAddress?: string\n billingHistory?: Array<{\n cycleNumber: number\n amount: number\n date: number\n status: \"paid\" | \"failed\" | \"pending\"\n transactionId?: string\n }>\n metadata?: any\n createdAt: number\n updatedAt: number\n}\n\nexport interface CreateSubscriptionData {\n businessId: string\n productId: string\n customerEmail: string\n customerName: string\n paymentPlanId: string\n customerId?: string\n metadata?: any\n}\n\nexport interface UpdateSubscriptionData {\n status?: \"active\" | \"cancelled\" | \"paused\" | \"expired\" | \"past_due\"\n pauseUntil?: number\n resumeDate?: number\n metadata?: any\n}\n\nexport interface TorqueConfig {\n businessId: string\n apiKey: string\n baseUrl?: string\n timeout?: number\n}\n\nexport interface BusinessCreationData {\n name: string\n description?: string\n email: string\n phone?: string\n website?: string\n currency?: string\n timezone?: string\n walletAddress: string\n logo?: string\n}\n\nexport interface BusinessProfile {\n id: string\n name: string\n email: string\n apiKey: string\n walletAddress: string\n logo?: string\n website?: string\n status: 'active' | 'pending' | 'suspended'\n}\n\nexport interface CheckoutResponse {\n success: boolean\n checkoutUrl: string\n expiresAt: string\n cartSummary: {\n itemCount: number\n productCount: number\n estimatedTotal: number\n }\n business: {\n id: string\n name: string\n logo?: string\n }\n}\n\nexport interface OrderStatus {\n orderId: string\n status: string\n customer: {\n email: string\n firstName?: string\n lastName?: string\n phone?: string\n } | null\n items: Array<{\n productId: string\n productName: string\n productImage?: string\n quantity: number\n variant?: string\n price: number\n total: number\n }>\n totals: {\n subtotal: number\n shipping: number\n tax: number\n total: number\n }\n paymentStatus: string\n shippingAddress?: any\n billingAddress?: any\n createdAt: number\n updatedAt: number\n metadata: Record<string, any>\n}\n\nexport interface CartValidation {\n valid: boolean\n errors: string[]\n warnings: string[]\n estimatedTotal: number\n}\n\nexport interface TorqueError extends Error {\n code?: string\n statusCode?: number\n details?: any\n}\n\n// ============================================================================\n// Error Classes\n// ============================================================================\n\nexport class TorqueCheckoutError extends Error implements TorqueError {\n code?: string\n statusCode?: number\n details?: any\n\n constructor(message: string, code?: string, statusCode?: number, details?: any) {\n super(message)\n this.name = 'TorqueCheckoutError'\n this.code = code\n this.statusCode = statusCode\n this.details = details\n Object.setPrototypeOf(this, TorqueCheckoutError.prototype)\n }\n}\n\n// ============================================================================\n// Validation Utilities\n// ============================================================================\n\n/**\n * Validates a Convex ID format (e.g., \"j1234567890abcdef\")\n * Convex IDs are alphanumeric strings starting with a letter\n */\nfunction isValidConvexId(id: string): boolean {\n return /^[a-z][a-z0-9]{15,}$/i.test(id)\n}\n\nexport function validateCartItem(item: CartItem): string[] {\n const errors: string[] = []\n \n if (!item.productId || typeof item.productId !== 'string' || item.productId.trim() === '') {\n errors.push('Product ID is required and must be a non-empty string')\n } else if (!isValidConvexId(item.productId)) {\n errors.push('Product ID must be a valid Torque product ID. Products must be uploaded to Torque first at /business/products')\n }\n \n if (typeof item.quantity !== 'number' || item.quantity <= 0 || !Number.isInteger(item.quantity)) {\n errors.push('Quantity must be a positive integer')\n }\n \n // Price validation removed - prices come from Torque product database\n // Prices are fetched from Torque when generating checkout URL\n \n return errors\n}\n\nexport function validateCartData(cart: CartData): string[] {\n const errors: string[] = []\n \n if (!cart.items || !Array.isArray(cart.items) || cart.items.length === 0) {\n errors.push('Cart must contain at least one item')\n return errors\n }\n \n cart.items.forEach((item, index) => {\n const itemErrors = validateCartItem(item)\n itemErrors.forEach(error => errors.push(`Item ${index + 1}: ${error}`))\n })\n \n if (cart.customer?.email && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(cart.customer.email)) {\n errors.push('Customer email must be a valid email address')\n }\n \n return errors\n}\n\nexport function validateConfig(config: TorqueConfig): string[] {\n const errors: string[] = []\n \n if (!config.businessId || typeof config.businessId !== 'string' || config.businessId.trim() === '') {\n errors.push('Business ID is required')\n }\n \n if (!config.apiKey || typeof config.apiKey !== 'string' || config.apiKey.trim() === '') {\n errors.push('API key is required')\n }\n \n if (config.timeout !== undefined && (typeof config.timeout !== 'number' || config.timeout <= 0)) {\n errors.push('Timeout must be a positive number')\n }\n \n return errors\n}\n\n// ============================================================================\n// Main SDK Class\n// ============================================================================\n\nexport class TorqueCheckout {\n private businessId: string\n private apiKey: string\n private baseUrl: string\n private timeout: number\n\n constructor(config: TorqueConfig) {\n const configErrors = validateConfig(config)\n if (configErrors.length > 0) {\n throw new TorqueCheckoutError(\n `Invalid configuration: ${configErrors.join(', ')}`,\n 'INVALID_CONFIG',\n 400,\n { errors: configErrors }\n )\n }\n\n this.businessId = config.businessId.trim()\n this.apiKey = config.apiKey.trim()\n this.baseUrl = (config.baseUrl || 'https://app.torque.fi').replace(/\\/$/, '')\n this.timeout = config.timeout || 30000\n }\n\n /**\n * Generate a cart checkout URL\n * @param cart - Cart data containing items, customer info, and options\n * @returns Promise resolving to checkout URL\n * @throws {TorqueCheckoutError} If cart validation fails or API request fails\n */\n async generateCartCheckoutUrl(cart: CartData): Promise<string> {\n const validationErrors = validateCartData(cart)\n if (validationErrors.length > 0) {\n throw new TorqueCheckoutError(\n `Cart validation failed: ${validationErrors.join(', ')}`,\n 'VALIDATION_ERROR',\n 400,\n { errors: validationErrors }\n )\n }\n\n try {\n const response = await this.makeRequest('/api/torque-checkout', {\n method: 'POST',\n body: {\n businessId: this.businessId,\n cart: {\n items: cart.items\n },\n customerData: cart.customer,\n options: cart.options\n }\n })\n\n if (!response.success) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to generate checkout URL',\n response.error || 'CHECKOUT_GENERATION_FAILED',\n response.statusCode || 500,\n response.details\n )\n }\n\n return response.checkoutUrl\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to generate checkout URL',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Generate a single product checkout URL\n * @param productId - Product ID\n * @param quantity - Quantity (default: 1)\n * @param customer - Optional customer data\n * @param options - Optional cart options\n * @returns Promise resolving to checkout URL\n */\n async generateProductCheckoutUrl(\n productId: string,\n quantity: number = 1,\n customer?: CustomerData,\n options?: CartOptions\n ): Promise<string> {\n return this.generateCartCheckoutUrl({\n items: [{ productId, quantity }],\n customer,\n options\n })\n }\n\n /**\n * Generate a subscription checkout URL\n * @param productId - Subscription product ID\n * @param paymentPlanId - Payment plan ID\n * @param customer - Optional customer data\n * @param options - Optional cart options\n * @returns Promise resolving to checkout URL\n */\n async generateSubscriptionCheckoutUrl(\n productId: string,\n paymentPlanId: string,\n customer?: CustomerData,\n options?: CartOptions\n ): Promise<string> {\n return this.generateCartCheckoutUrl({\n items: [{ \n productId, \n quantity: 1,\n metadata: { \n isSubscription: true, \n paymentPlanId \n }\n }],\n customer,\n options\n })\n }\n\n /**\n * Validate cart data before checkout\n * @param cart - Cart data to validate\n * @returns Promise resolving to validation result\n */\n async validateCart(cart: CartData): Promise<CartValidation> {\n try {\n const response = await this.makeRequest('/api/checkout/validate-cart', {\n method: 'POST',\n body: {\n businessId: this.businessId,\n cart: cart.items,\n customer: cart.customer\n }\n })\n\n return response\n } catch (error) {\n const validationErrors = validateCartData(cart)\n return {\n valid: false,\n errors: error instanceof Error \n ? [error.message, ...validationErrors]\n : ['Validation failed', ...validationErrors],\n warnings: [],\n estimatedTotal: 0\n }\n }\n }\n\n /**\n * Get order status\n * @param orderId - Order ID\n * @returns Promise resolving to order status\n * @throws {TorqueCheckoutError} If order not found or API request fails\n */\n async getOrderStatus(orderId: string): Promise<OrderStatus> {\n if (!orderId || typeof orderId !== 'string') {\n throw new TorqueCheckoutError('Order ID is required', 'INVALID_ORDER_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/checkout/order-status/${orderId}?businessId=${this.businessId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get order status',\n response.error || 'ORDER_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get order status',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Create a new subscription\n * @param data - Subscription creation data\n * @returns Promise resolving to created subscription\n */\n async createSubscription(data: CreateSubscriptionData): Promise<Subscription> {\n try {\n const response = await this.makeRequest('/api/subscriptions/create', {\n method: 'POST',\n body: data\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to create subscription',\n response.error || 'SUBSCRIPTION_CREATION_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to create subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscription by ID\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to subscription\n */\n async getSubscription(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscription',\n response.error || 'SUBSCRIPTION_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions for a business\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @param status - Optional status filter\n * @param limit - Optional limit\n * @returns Promise resolving to array of subscriptions\n */\n async getBusinessSubscriptions(businessId?: string, status?: string, limit?: number): Promise<Subscription[]> {\n const bid = businessId || this.businessId\n const params = new URLSearchParams({ businessId: bid })\n if (status) params.append('status', status)\n if (limit) params.append('limit', limit.toString())\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/business?${params}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get business subscriptions',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get business subscriptions',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions for a customer\n * @param customerEmail - Customer email\n * @returns Promise resolving to array of subscriptions\n */\n async getCustomerSubscriptions(customerEmail: string): Promise<Subscription[]> {\n if (!customerEmail || typeof customerEmail !== 'string' || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(customerEmail)) {\n throw new TorqueCheckoutError('Valid customer email is required', 'INVALID_EMAIL', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/customer/${encodeURIComponent(customerEmail)}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get customer subscriptions',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get customer subscriptions',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Update subscription status\n * @param subscriptionId - Subscription ID\n * @param data - Update data\n * @returns Promise resolving to updated subscription\n */\n async updateSubscription(subscriptionId: string, data: UpdateSubscriptionData): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/update`, {\n method: 'PUT',\n body: data\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to update subscription',\n response.error || 'UPDATE_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to update subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Cancel subscription\n * @param subscriptionId - Subscription ID\n * @param effectiveDate - Optional effective date for cancellation\n * @returns Promise resolving to cancelled subscription\n */\n async cancelSubscription(subscriptionId: string, effectiveDate?: number): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/cancel`, {\n method: 'PUT',\n body: { effectiveDate }\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to cancel subscription',\n response.error || 'CANCEL_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to cancel subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Pause subscription\n * @param subscriptionId - Subscription ID\n * @param resumeDate - Optional resume date\n * @returns Promise resolving to paused subscription\n */\n async pauseSubscription(subscriptionId: string, resumeDate?: number): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/pause`, {\n method: 'PUT',\n body: { resumeDate }\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to pause subscription',\n response.error || 'PAUSE_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to pause subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Resume subscription\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to resumed subscription\n */\n async resumeSubscription(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/resume`, {\n method: 'PUT'\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to resume subscription',\n response.error || 'RESUME_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to resume subscription',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Process subscription renewal\n * @param subscriptionId - Subscription ID\n * @returns Promise resolving to renewed subscription\n */\n async processSubscriptionRenewal(subscriptionId: string): Promise<Subscription> {\n if (!subscriptionId || typeof subscriptionId !== 'string') {\n throw new TorqueCheckoutError('Subscription ID is required', 'INVALID_SUBSCRIPTION_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/${subscriptionId}/renew`, {\n method: 'PUT'\n })\n\n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to process subscription renewal',\n response.error || 'RENEWAL_FAILED',\n response.statusCode || 500\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to process subscription renewal',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscriptions due for renewal\n * @param daysAhead - Number of days ahead to check (default: 7)\n * @returns Promise resolving to array of subscriptions\n */\n async getSubscriptionsDueForRenewal(daysAhead: number = 7): Promise<Subscription[]> {\n if (typeof daysAhead !== 'number' || daysAhead < 0) {\n throw new TorqueCheckoutError('Days ahead must be a non-negative number', 'INVALID_PARAMETER', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/subscriptions/due-for-renewal?daysAhead=${daysAhead}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscriptions due for renewal',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscriptions due for renewal',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get all products for a business\n * Use this to sync your ecommerce catalog with Torque products\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @param status - Optional status filter ('active', 'inactive', 'draft', 'archived')\n * @returns Promise resolving to array of products\n * \n * @example\n * ```ts\n * const products = await torque.getProducts()\n * // Sync products with your database\n * products.forEach(product => {\n * await db.products.update({\n * where: { sku: product.sku },\n * data: { torqueProductId: product.id }\n * })\n * })\n * ```\n */\n async getProducts(businessId?: string, status?: 'active' | 'inactive' | 'draft' | 'archived'): Promise<Product[]> {\n const bid = businessId || this.businessId\n const params = new URLSearchParams({ businessId: bid })\n if (status) params.append('status', status)\n\n try {\n const response = await this.makeRequest(`/api/products?${params}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get products',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n return Array.isArray(response) ? response : []\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get products',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get subscription products for a business\n * @param businessId - Business ID (optional, uses instance businessId if not provided)\n * @returns Promise resolving to array of subscription products\n */\n async getSubscriptionProducts(businessId?: string): Promise<SubscriptionProduct[]> {\n const bid = businessId || this.businessId\n\n try {\n const response = await this.makeRequest(`/api/products/subscriptions?businessId=${bid}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get subscription products',\n response.error || 'FETCH_FAILED',\n response.statusCode || 500\n )\n }\n\n const products = Array.isArray(response) ? response : []\n // Map to SubscriptionProduct format with basePrice alias\n return products.map(p => ({\n ...p,\n basePrice: p.price || p.basePrice || 0\n }))\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get subscription products',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get a single product by ID\n * @param productId - Product ID (Torque product ID)\n * @returns Promise resolving to product\n */\n async getProduct(productId: string): Promise<Product> {\n if (!productId || typeof productId !== 'string') {\n throw new TorqueCheckoutError('Product ID is required', 'INVALID_PRODUCT_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/products/${productId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get product',\n response.error || 'PRODUCT_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get product',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Get product with payment plans\n * @param productId - Product ID\n * @returns Promise resolving to product with payment plans\n */\n async getProductWithPaymentPlans(productId: string): Promise<SubscriptionProduct> {\n if (!productId || typeof productId !== 'string') {\n throw new TorqueCheckoutError('Product ID is required', 'INVALID_PRODUCT_ID', 400)\n }\n\n try {\n const response = await this.makeRequest(`/api/products/${productId}`)\n \n if (response.error) {\n throw new TorqueCheckoutError(\n response.message || 'Failed to get product',\n response.error || 'PRODUCT_NOT_FOUND',\n response.statusCode || 404\n )\n }\n\n return response\n } catch (error) {\n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n throw new TorqueCheckoutError(\n error instanceof Error ? error.message : 'Failed to get product',\n 'NETWORK_ERROR',\n 500\n )\n }\n }\n\n /**\n * Send webhook event\n * @param orderId - Order ID\n * @param status - Order status\n * @param customerData - Optional customer data\n * @param metadata - Optional metadata\n */\n async sendWebhookEvent(\n orderId: string,\n status: string,\n customerData?: any,\n metadata?: Record<string, any>\n ): Promise<void> {\n if (!orderId || typeof orderId !== 'string') {\n throw new TorqueCheckoutError('Order ID is required', 'INVALID_ORDER_ID', 400)\n }\n\n try {\n await this.makeRequest('/api/webhooks/order-update', {\n method: 'POST',\n body: {\n orderId,\n status,\n customerData,\n metadata\n }\n })\n } catch (error) {\n // Webhook events are non-critical, log but don't throw\n console.warn('Failed to send webhook event:', error)\n }\n }\n\n /**\n * Track cart view for analytics\n * @param cartId - Cart ID\n * @param cartData - Cart data\n */\n async trackCartView(cartId: string, cartData: CartData): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/cart-view', {\n method: 'POST',\n body: {\n cartId,\n businessId: this.businessId,\n cartData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track cart view:', error)\n }\n }\n\n /**\n * Track checkout completion for analytics\n * @param orderId - Order ID\n * @param checkoutData - Checkout data\n */\n async trackCheckoutComplete(orderId: string, checkoutData: any): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/checkout-complete', {\n method: 'POST',\n body: {\n orderId,\n businessId: this.businessId,\n checkoutData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track checkout completion:', error)\n }\n }\n\n /**\n * Track subscription creation for analytics\n * @param subscriptionId - Subscription ID\n * @param subscriptionData - Subscription data\n */\n async trackSubscriptionCreated(subscriptionId: string, subscriptionData: any): Promise<void> {\n try {\n await this.makeRequest('/api/analytics/subscription-created', {\n method: 'POST',\n body: {\n subscriptionId,\n businessId: this.businessId,\n subscriptionData,\n timestamp: Date.now()\n }\n })\n } catch (error) {\n // Analytics tracking is non-critical, log but don't throw\n console.warn('Failed to track subscription creation:', error)\n }\n }\n\n /**\n * Generate cart hash for caching\n * @param cart - Cart data\n * @returns Cart hash string\n */\n generateCartHash(cart: CartData): string {\n const cartString = JSON.stringify({\n items: cart.items.sort((a, b) => a.productId.localeCompare(b.productId)),\n customer: cart.customer ? { email: cart.customer.email } : null\n })\n \n let hash = 0\n for (let i = 0; i < cartString.length; i++) {\n const char = cartString.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash // Convert to 32-bit integer\n }\n return Math.abs(hash).toString(36)\n }\n\n /**\n * Generate subscription hash for caching\n * @param subscriptionData - Subscription data\n * @returns Subscription hash string\n */\n generateSubscriptionHash(subscriptionData: CreateSubscriptionData): string {\n const subscriptionString = JSON.stringify({\n businessId: subscriptionData.businessId,\n productId: subscriptionData.productId,\n customerEmail: subscriptionData.customerEmail,\n paymentPlanId: subscriptionData.paymentPlanId\n })\n \n let hash = 0\n for (let i = 0; i < subscriptionString.length; i++) {\n const char = subscriptionString.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash\n }\n return Math.abs(hash).toString(36)\n }\n\n /**\n * Make HTTP request to Torque API\n * @private\n */\n private async makeRequest(\n endpoint: string,\n options: { method?: string; body?: any; headers?: Record<string, string> } = {}\n ): Promise<any> {\n const url = `${this.baseUrl}${endpoint}`\n \n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this.timeout)\n\n try {\n const { body, ...fetchOptions } = options\n const response = await fetch(url, {\n ...fetchOptions,\n method: options.method || 'GET',\n body: body ? JSON.stringify(body) : undefined,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n ...options.headers\n },\n signal: controller.signal\n })\n\n clearTimeout(timeoutId)\n\n const responseData = await response.json().catch(() => ({}))\n\n if (!response.ok) {\n throw new TorqueCheckoutError(\n responseData.message || `HTTP ${response.status}: ${response.statusText}`,\n responseData.error || 'API_ERROR',\n response.status,\n responseData.details\n )\n }\n\n return responseData\n } catch (error) {\n clearTimeout(timeoutId)\n \n if (error instanceof TorqueCheckoutError) {\n throw error\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new TorqueCheckoutError('Request timeout', 'TIMEOUT', 408)\n }\n throw new TorqueCheckoutError(error.message, 'NETWORK_ERROR', 500)\n }\n \n throw new TorqueCheckoutError('Request failed', 'UNKNOWN_ERROR', 500)\n }\n }\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a new TorqueCheckout instance\n * @param config - Configuration object\n * @returns TorqueCheckout instance\n */\nexport function createTorqueCheckout(config: TorqueConfig): TorqueCheckout {\n return new TorqueCheckout(config)\n}\n\n/**\n * Create a TorqueCheckout instance from environment variables\n * Requires TORQUE_BUSINESS_ID and TORQUE_API_KEY environment variables\n * @param overrides - Optional configuration overrides\n * @returns TorqueCheckout instance\n */\nexport function createTorqueCheckoutFromEnv(overrides?: Partial<TorqueConfig>): TorqueCheckout {\n const businessId = process.env.TORQUE_BUSINESS_ID || overrides?.businessId\n const apiKey = process.env.TORQUE_API_KEY || overrides?.apiKey\n\n if (!businessId || !apiKey) {\n throw new TorqueCheckoutError(\n 'TORQUE_BUSINESS_ID and TORQUE_API_KEY environment variables are required',\n 'MISSING_ENV_VARS',\n 400\n )\n }\n\n return new TorqueCheckout({\n businessId,\n apiKey,\n baseUrl: process.env.TORQUE_BASE_URL || overrides?.baseUrl,\n timeout: overrides?.timeout\n })\n}\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\n// Types are already exported above as interfaces/types\n// This section is for re-exporting if needed for convenience\n// All types are available via named exports from the main module\n"],"names":[],"mappings":";;AAAA;;;;;;;;AAQG;AA+OH;AACA;AACA;AAEM,MAAO,mBAAoB,SAAQ,KAAK,CAAA;AAK5C,IAAA,WAAA,CAAY,OAAe,EAAE,IAAa,EAAE,UAAmB,EAAE,OAAa,EAAA;QAC5E,KAAK,CAAC,OAAO,CAAC;AACd,QAAA,IAAI,CAAC,IAAI,GAAG,qBAAqB;AACjC,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI;AAChB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU;AAC5B,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;QACtB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,mBAAmB,CAAC,SAAS,CAAC;IAC5D;AACD;AAED;AACA;AACA;AAEA;;;AAGG;AACH,SAAS,eAAe,CAAC,EAAU,EAAA;AACjC,IAAA,OAAO,uBAAuB,CAAC,IAAI,CAAC,EAAE,CAAC;AACzC;AAEM,SAAU,gBAAgB,CAAC,IAAc,EAAA;IAC7C,MAAM,MAAM,GAAa,EAAE;IAE3B,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,OAAO,IAAI,CAAC,S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B,EAClB,GAAG,CACJ;IACH;IAEA,OAAO,IAAI,cAAc,CAAC;QACxB,UAAU;QACV,MAAM;QACN,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,IAAI,SAAS,EAAE,OAAO;QAC1D,OAAO,EAAE,SAAS,EAAE;AACrB,KAAA,CAAC;AACJ;AAEA;AACA;AACA;AAEA;AACA;AACA;;;;;;;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "torque-checkout",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.1",
|
|
4
4
|
"description": "Official Torque checkout SDK for seamless eCommerce integrations with Next.js",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.esm.js",
|
|
@@ -26,15 +26,15 @@
|
|
|
26
26
|
"files": [
|
|
27
27
|
"dist",
|
|
28
28
|
"README.md",
|
|
29
|
-
"LICENSE"
|
|
29
|
+
"LICENSE",
|
|
30
|
+
"CHANGELOG.md"
|
|
30
31
|
],
|
|
31
32
|
"scripts": {
|
|
32
33
|
"build": "rollup -c",
|
|
33
34
|
"dev": "rollup -c -w",
|
|
34
|
-
"test": "jest",
|
|
35
35
|
"lint": "eslint src --ext .ts,.tsx",
|
|
36
36
|
"clean": "rimraf dist",
|
|
37
|
-
"prepublishOnly": "
|
|
37
|
+
"prepublishOnly": "yarn clean && yarn build"
|
|
38
38
|
},
|
|
39
39
|
"keywords": [
|
|
40
40
|
"torque",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"homepage": "https://torque.fi",
|
|
56
56
|
"repository": {
|
|
57
57
|
"type": "git",
|
|
58
|
-
"url": "https://github.com/torque-fi/torque-checkout"
|
|
58
|
+
"url": "git+https://github.com/torque-fi/torque-checkout.git"
|
|
59
59
|
},
|
|
60
60
|
"bugs": {
|
|
61
61
|
"url": "https://github.com/torque-fi/torque-checkout/issues"
|
|
@@ -67,7 +67,6 @@
|
|
|
67
67
|
"@typescript-eslint/eslint-plugin": "^6.0.0",
|
|
68
68
|
"@typescript-eslint/parser": "^6.0.0",
|
|
69
69
|
"eslint": "^8.0.0",
|
|
70
|
-
"jest": "^29.0.0",
|
|
71
70
|
"rimraf": "^5.0.0",
|
|
72
71
|
"rollup": "^4.0.0",
|
|
73
72
|
"typescript": "^5.0.0"
|