spaps-sdk 0.1.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,175 +15,929 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
- // src/index.ts
20
+ // index.ts
31
21
  var index_exports = {};
32
22
  __export(index_exports, {
33
- SPAPS: () => SPAPSClient,
34
- SPAPSClient: () => SPAPSClient,
35
- SweetPotatoSDK: () => SPAPSClient,
36
- default: () => index_default
23
+ AuthService: () => AuthService,
24
+ HttpClient: () => HttpClient,
25
+ PaymentsService: () => PaymentsService,
26
+ SweetPotatoAPIError: () => SweetPotatoAPIError,
27
+ SweetPotatoSDK: () => SweetPotatoSDK,
28
+ TokenManager: () => TokenManager,
29
+ WalletUtils: () => WalletUtils,
30
+ createSweetPotatoSDK: () => createSweetPotatoSDK,
31
+ default: () => SweetPotatoSDK
37
32
  });
38
33
  module.exports = __toCommonJS(index_exports);
39
- var import_axios = __toESM(require("axios"));
40
- var SPAPSClient = class {
41
- client;
42
- apiKey;
43
- accessToken;
44
- refreshToken;
45
- _isLocalMode = false;
46
- constructor(config = {}) {
47
- const apiUrl = config.apiUrl || process.env.SPAPS_API_URL || process.env.NEXT_PUBLIC_SPAPS_API_URL;
48
- if (!apiUrl || apiUrl.includes("localhost") || apiUrl.includes("127.0.0.1")) {
49
- this._isLocalMode = true;
50
- this.client = import_axios.default.create({
51
- baseURL: apiUrl || "http://localhost:3300",
52
- timeout: config.timeout || 1e4,
53
- headers: {
54
- "Content-Type": "application/json"
55
- }
56
- });
34
+
35
+ // types.ts
36
+ var SweetPotatoAPIError = class extends Error {
37
+ constructor(message, code, status, details) {
38
+ super(message);
39
+ this.name = "SweetPotatoAPIError";
40
+ if (code !== void 0) this.code = code;
41
+ if (status !== void 0) this.status = status;
42
+ if (details !== void 0) this.details = details;
43
+ }
44
+ };
45
+
46
+ // client.ts
47
+ function detectLocalEnvironment() {
48
+ var _a;
49
+ if (typeof process !== "undefined" && process.env) {
50
+ if (process.env.NODE_ENV === "development" || process.env.SPAPS_LOCAL_MODE === "true") {
51
+ return true;
52
+ }
53
+ }
54
+ if (typeof globalThis !== "undefined" && ((_a = globalThis.window) == null ? void 0 : _a.location)) {
55
+ const hostname = globalThis.window.location.hostname;
56
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname.endsWith(".local");
57
+ }
58
+ return false;
59
+ }
60
+ var HttpClient = class {
61
+ constructor(config) {
62
+ var _a, _b;
63
+ const localMode = (_b = config.localMode) != null ? _b : ((_a = config.apiUrl) == null ? void 0 : _a.includes("localhost")) || detectLocalEnvironment();
64
+ this.config = {
65
+ timeout: 3e4,
66
+ retries: 3,
67
+ ...config,
68
+ localMode
69
+ };
70
+ this.isLocalMode = this.config.localMode || false;
71
+ this.accessToken = void 0;
72
+ if (this.isLocalMode && typeof console !== "undefined") {
73
+ console.log("[SPAPS SDK] Running in local development mode - authentication will be automatic");
74
+ }
75
+ }
76
+ /**
77
+ * Set the access token for authenticated requests
78
+ */
79
+ setAccessToken(token) {
80
+ this.accessToken = token;
81
+ }
82
+ /**
83
+ * Clear the access token
84
+ */
85
+ clearAccessToken() {
86
+ this.accessToken = void 0;
87
+ }
88
+ /**
89
+ * Make an HTTP request with automatic retries and error handling
90
+ */
91
+ async request(options) {
92
+ var _a, _b, _c, _d;
93
+ const { method, url, data, headers = {}, requiresAuth = false } = options;
94
+ const fullUrl = url.startsWith("http") ? url : `${this.config.apiUrl.replace(/\/$/, "")}${url}`;
95
+ const requestHeaders = {
96
+ "Content-Type": "application/json",
97
+ ...headers
98
+ };
99
+ if (this.config.apiKey) {
100
+ requestHeaders["x-api-key"] = this.config.apiKey;
101
+ } else if (this.isLocalMode) {
102
+ requestHeaders["x-local-mode"] = "true";
57
103
  } else {
58
- if (!config.apiKey && !process.env.SPAPS_API_KEY) {
59
- console.warn("\u26A0\uFE0F SPAPS: No API key provided. Some features may not work.");
60
- }
61
- this.apiKey = config.apiKey || process.env.SPAPS_API_KEY;
62
- this.client = import_axios.default.create({
63
- baseURL: apiUrl,
64
- timeout: config.timeout || 1e4,
65
- headers: {
66
- "Content-Type": "application/json",
67
- ...this.apiKey && { "X-API-Key": this.apiKey }
68
- }
69
- });
104
+ console.warn("[SPAPS SDK] No API key provided and not in local mode");
70
105
  }
71
- this.client.interceptors.request.use((config2) => {
72
- if (this.accessToken && !config2.headers.Authorization) {
73
- config2.headers.Authorization = `Bearer ${this.accessToken}`;
74
- }
75
- return config2;
76
- });
77
- this.client.interceptors.response.use(
78
- (response) => response,
79
- async (error) => {
80
- if (error.response?.status === 401 && this.refreshToken) {
81
- try {
82
- const { data } = await this.refresh(this.refreshToken);
83
- this.accessToken = data.access_token;
84
- this.refreshToken = data.refresh_token;
85
- if (error.config) {
86
- error.config.headers.Authorization = `Bearer ${this.accessToken}`;
87
- return this.client.request(error.config);
88
- }
89
- } catch (refreshError) {
90
- this.accessToken = void 0;
91
- this.refreshToken = void 0;
106
+ if (requiresAuth && this.accessToken) {
107
+ requestHeaders["Authorization"] = `Bearer ${this.accessToken}`;
108
+ }
109
+ let lastError = null;
110
+ for (let attempt = 1; attempt <= this.config.retries; attempt++) {
111
+ try {
112
+ const controller = new AbortController();
113
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
114
+ const requestInit = {
115
+ method,
116
+ headers: requestHeaders,
117
+ signal: controller.signal
118
+ };
119
+ if (data && (method === "POST" || method === "PUT" || method === "PATCH")) {
120
+ requestInit.body = JSON.stringify(data);
121
+ }
122
+ const response = await fetch(fullUrl, requestInit);
123
+ clearTimeout(timeoutId);
124
+ if (!response) {
125
+ throw new Error("No response received");
126
+ }
127
+ let responseData;
128
+ const contentType = (_a = response.headers) == null ? void 0 : _a.get("content-type");
129
+ if (contentType && contentType.includes("application/json")) {
130
+ responseData = await response.json();
131
+ } else {
132
+ throw new SweetPotatoAPIError(
133
+ "Invalid response format: expected JSON",
134
+ "INVALID_RESPONSE_FORMAT",
135
+ response.status
136
+ );
137
+ }
138
+ if (!(response == null ? void 0 : response.ok)) {
139
+ throw new SweetPotatoAPIError(
140
+ ((_b = responseData.error) == null ? void 0 : _b.message) || `HTTP ${response == null ? void 0 : response.status}: ${response == null ? void 0 : response.statusText}`,
141
+ ((_c = responseData.error) == null ? void 0 : _c.code) || "HTTP_ERROR",
142
+ response == null ? void 0 : response.status,
143
+ (_d = responseData.error) == null ? void 0 : _d.details
144
+ );
145
+ }
146
+ return responseData;
147
+ } catch (error) {
148
+ lastError = error;
149
+ if (error instanceof SweetPotatoAPIError) {
150
+ if (error.status && error.status >= 400 && error.status < 500) {
151
+ throw error;
92
152
  }
93
153
  }
94
- return Promise.reject(error);
154
+ if (attempt === this.config.retries) {
155
+ break;
156
+ }
157
+ const delayMs = Math.min(1e3 * Math.pow(2, attempt - 1), 1e4);
158
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
95
159
  }
160
+ }
161
+ if (lastError instanceof SweetPotatoAPIError) {
162
+ throw lastError;
163
+ }
164
+ throw new SweetPotatoAPIError(
165
+ (lastError == null ? void 0 : lastError.message) || "Request failed after all retries",
166
+ "REQUEST_FAILED",
167
+ void 0,
168
+ { originalError: lastError }
96
169
  );
97
170
  }
98
- // Authentication Methods
99
- async login(email, password) {
100
- const response = await this.client.post("/api/auth/login", {
101
- email,
102
- password
171
+ /**
172
+ * Convenience method for GET requests
173
+ */
174
+ async get(url, requiresAuth = false) {
175
+ return this.request({
176
+ method: "GET",
177
+ url,
178
+ requiresAuth
103
179
  });
104
- this.accessToken = response.data.access_token;
105
- this.refreshToken = response.data.refresh_token;
106
- return response;
107
- }
108
- async register(email, password) {
109
- const response = await this.client.post("/api/auth/register", {
110
- email,
111
- password
180
+ }
181
+ /**
182
+ * Convenience method for POST requests
183
+ */
184
+ async post(url, data, requiresAuth = false) {
185
+ return this.request({
186
+ method: "POST",
187
+ url,
188
+ data,
189
+ requiresAuth
190
+ });
191
+ }
192
+ /**
193
+ * Convenience method for PUT requests
194
+ */
195
+ async put(url, data, requiresAuth = false) {
196
+ return this.request({
197
+ method: "PUT",
198
+ url,
199
+ data,
200
+ requiresAuth
201
+ });
202
+ }
203
+ /**
204
+ * Convenience method for DELETE requests
205
+ */
206
+ async delete(url, requiresAuth = false) {
207
+ return this.request({
208
+ method: "DELETE",
209
+ url,
210
+ requiresAuth
112
211
  });
113
- this.accessToken = response.data.access_token;
114
- this.refreshToken = response.data.refresh_token;
115
- return response;
116
212
  }
117
- async walletSignIn(walletAddress, signature, message, chainType = "solana") {
118
- const response = await this.client.post("/api/auth/wallet-sign-in", {
213
+ };
214
+
215
+ // auth.ts
216
+ var AuthService = class {
217
+ constructor(httpClient) {
218
+ this.httpClient = httpClient;
219
+ }
220
+ /**
221
+ * Get a nonce for wallet signature
222
+ * @param walletAddress - The wallet address to generate a nonce for
223
+ * @returns Promise<NonceResponse>
224
+ */
225
+ async getNonce(walletAddress) {
226
+ var _a;
227
+ const response = await this.httpClient.post("/api/auth/nonce", {
228
+ wallet_address: walletAddress
229
+ });
230
+ if (!response.success || !response.data) {
231
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to generate nonce");
232
+ }
233
+ return response.data;
234
+ }
235
+ /**
236
+ * Sign in with wallet signature
237
+ * @param request - Wallet sign-in request data
238
+ * @returns Promise<AuthResponse>
239
+ */
240
+ async signInWithWallet(request) {
241
+ var _a;
242
+ const response = await this.httpClient.post("/api/auth/wallet-sign-in", request);
243
+ if (!response.success || !response.data) {
244
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Wallet sign-in failed");
245
+ }
246
+ this.httpClient.setAccessToken(response.data.access_token);
247
+ return response.data;
248
+ }
249
+ /**
250
+ * Complete wallet authentication flow
251
+ * This is a convenience method that combines getNonce and signInWithWallet
252
+ * @param walletAddress - The wallet address
253
+ * @param signatureFunction - Function that signs the auth message
254
+ * @param chainType - Optional chain type (will be auto-detected if not provided)
255
+ * @param username - Optional username for new users
256
+ * @returns Promise<AuthResponse>
257
+ */
258
+ async authenticateWallet(walletAddress, signatureFunction, chainType, username) {
259
+ const nonceData = await this.getNonce(walletAddress);
260
+ const signature = await signatureFunction(nonceData.message);
261
+ const request = {
119
262
  wallet_address: walletAddress,
120
263
  signature,
121
- message,
122
- chain_type: chainType
123
- });
124
- this.accessToken = response.data.access_token;
125
- this.refreshToken = response.data.refresh_token;
126
- return response;
264
+ message: nonceData.message
265
+ };
266
+ if (chainType) {
267
+ request.chain_type = chainType;
268
+ }
269
+ if (username) {
270
+ request.username = username;
271
+ }
272
+ return this.signInWithWallet(request);
127
273
  }
128
- async refresh(refreshToken) {
129
- const response = await this.client.post("/api/auth/refresh", {
130
- refresh_token: refreshToken || this.refreshToken
274
+ /**
275
+ * Sign in with email and password
276
+ * @param request - Traditional login request data
277
+ * @returns Promise<AuthResponse>
278
+ */
279
+ async signInWithPassword(request) {
280
+ var _a;
281
+ const response = await this.httpClient.post("/api/auth/login", request);
282
+ if (!response.success || !response.data) {
283
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Login failed");
284
+ }
285
+ this.httpClient.setAccessToken(response.data.access_token);
286
+ return response.data;
287
+ }
288
+ /**
289
+ * Request a magic link for email authentication
290
+ * @param request - Magic link request data
291
+ * @returns Promise<void>
292
+ */
293
+ async requestMagicLink(request) {
294
+ var _a;
295
+ const response = await this.httpClient.post("/api/auth/magic-link", request);
296
+ if (!response.success) {
297
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to send magic link");
298
+ }
299
+ }
300
+ /**
301
+ * Refresh access token using refresh token
302
+ * @param refreshToken - The refresh token
303
+ * @returns Promise<TokenPair>
304
+ */
305
+ async refreshToken(refreshToken) {
306
+ var _a;
307
+ const response = await this.httpClient.post("/api/auth/refresh", {
308
+ refresh_token: refreshToken
131
309
  });
132
- this.accessToken = response.data.access_token;
133
- this.refreshToken = response.data.refresh_token;
134
- return response;
310
+ if (!response.success || !response.data) {
311
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Token refresh failed");
312
+ }
313
+ this.httpClient.setAccessToken(response.data.access_token);
314
+ return response.data;
135
315
  }
316
+ /**
317
+ * Log out and invalidate tokens
318
+ * @returns Promise<void>
319
+ */
136
320
  async logout() {
137
- await this.client.post("/api/auth/logout");
138
- this.accessToken = void 0;
139
- this.refreshToken = void 0;
321
+ var _a;
322
+ try {
323
+ const response = await this.httpClient.post("/api/auth/logout", {}, true);
324
+ if (!response.success) {
325
+ console.warn("Logout API call failed:", ((_a = response.error) == null ? void 0 : _a.message) || "Unknown error");
326
+ }
327
+ } catch (error) {
328
+ console.warn("Logout API call failed:", error);
329
+ } finally {
330
+ this.httpClient.clearAccessToken();
331
+ }
140
332
  }
141
- async getUser() {
142
- return this.client.get("/api/auth/user");
333
+ /**
334
+ * Get current user profile
335
+ * @returns Promise<User>
336
+ */
337
+ async getCurrentUser() {
338
+ var _a;
339
+ const response = await this.httpClient.get("/api/auth/user", true);
340
+ if (!response.success || !response.data) {
341
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to get user profile");
342
+ }
343
+ return response.data.user;
143
344
  }
144
- // Stripe Methods
145
- async createCheckoutSession(priceId, successUrl, cancelUrl) {
146
- return this.client.post("/api/stripe/create-checkout-session", {
147
- price_id: priceId,
148
- success_url: successUrl,
149
- cancel_url: cancelUrl
150
- });
345
+ /**
346
+ * Check if user is currently authenticated
347
+ * @returns boolean
348
+ */
349
+ isAuthenticated() {
350
+ return this.httpClient["accessToken"] !== void 0;
351
+ }
352
+ /**
353
+ * Clear authentication state (useful for client-side logout)
354
+ */
355
+ clearAuth() {
356
+ this.httpClient.clearAccessToken();
151
357
  }
152
- async getSubscription() {
153
- return this.client.get("/api/stripe/subscription");
358
+ };
359
+
360
+ // payments.ts
361
+ var PaymentsService = class {
362
+ constructor(httpClient) {
363
+ this.httpClient = httpClient;
364
+ }
365
+ // Checkout Sessions
366
+ /**
367
+ * Create a new Stripe checkout session
368
+ * @param request - Checkout session creation parameters
369
+ * @returns Promise<CheckoutSession>
370
+ */
371
+ async createCheckoutSession(request) {
372
+ var _a;
373
+ const response = await this.httpClient.post(
374
+ "/api/stripe/checkout-sessions",
375
+ request,
376
+ true
377
+ );
378
+ if (!response.success || !response.data) {
379
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create checkout session");
380
+ }
381
+ return response.data;
154
382
  }
155
- async cancelSubscription() {
156
- await this.client.delete("/api/stripe/subscription");
383
+ /**
384
+ * Retrieve a checkout session by ID
385
+ * @param sessionId - The checkout session ID
386
+ * @returns Promise<CheckoutSession>
387
+ */
388
+ async getCheckoutSession(sessionId) {
389
+ var _a;
390
+ const response = await this.httpClient.get(
391
+ `/api/stripe/checkout-sessions/${sessionId}`,
392
+ true
393
+ );
394
+ if (!response.success || !response.data) {
395
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to retrieve checkout session");
396
+ }
397
+ return response.data;
157
398
  }
158
- // Usage Methods
159
- async getUsageBalance() {
160
- return this.client.get("/api/usage/balance");
399
+ /**
400
+ * Expire a checkout session
401
+ * @param sessionId - The checkout session ID to expire
402
+ * @returns Promise<{id: string, status: string, expired: boolean}>
403
+ */
404
+ async expireCheckoutSession(sessionId) {
405
+ var _a;
406
+ const response = await this.httpClient.post(
407
+ `/api/stripe/checkout-sessions/${sessionId}/expire`,
408
+ {},
409
+ true
410
+ );
411
+ if (!response.success || !response.data) {
412
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to expire checkout session");
413
+ }
414
+ return response.data;
161
415
  }
162
- async recordUsage(feature, amount) {
163
- await this.client.post("/api/usage/record", {
164
- feature,
165
- amount
166
- });
416
+ /**
417
+ * List checkout sessions for the current user
418
+ * @param options - List options (limit, pagination)
419
+ * @returns Promise<CheckoutSessionListResponse>
420
+ */
421
+ async listCheckoutSessions(options = {}) {
422
+ var _a;
423
+ const params = new URLSearchParams();
424
+ if (options.limit) params.append("limit", options.limit.toString());
425
+ if (options.starting_after) params.append("starting_after", options.starting_after);
426
+ const url = `/api/stripe/checkout-sessions${params.toString() ? `?${params.toString()}` : ""}`;
427
+ const response = await this.httpClient.get(url, true);
428
+ if (!response.success || !response.data) {
429
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to list checkout sessions");
430
+ }
431
+ return response.data;
432
+ }
433
+ // Products
434
+ /**
435
+ * List available products
436
+ * @param request - Product list filters
437
+ * @returns Promise<ProductsListResponse>
438
+ */
439
+ async listProducts(request = {}) {
440
+ var _a;
441
+ const params = new URLSearchParams();
442
+ if (request.category) params.append("category", request.category);
443
+ if (request.active !== void 0) params.append("active", request.active.toString());
444
+ if (request.limit) params.append("limit", request.limit.toString());
445
+ if (request.starting_after) params.append("starting_after", request.starting_after);
446
+ const url = `/api/stripe/products${params.toString() ? `?${params.toString()}` : ""}`;
447
+ const response = await this.httpClient.get(url, true);
448
+ if (!response.success || !response.data) {
449
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to list products");
450
+ }
451
+ return response.data;
452
+ }
453
+ /**
454
+ * Get a specific product by ID
455
+ * @param productId - The product ID
456
+ * @param includePrices - Whether to include associated prices (default: true)
457
+ * @returns Promise<StripeProduct>
458
+ */
459
+ async getProduct(productId, includePrices = true) {
460
+ var _a;
461
+ const params = new URLSearchParams();
462
+ if (!includePrices) params.append("include_prices", "false");
463
+ const url = `/api/stripe/products/${productId}${params.toString() ? `?${params.toString()}` : ""}`;
464
+ const response = await this.httpClient.get(url, true);
465
+ if (!response.success || !response.data) {
466
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to retrieve product");
467
+ }
468
+ return response.data;
469
+ }
470
+ /**
471
+ * Create a new product (Admin only)
472
+ * @param request - Product creation parameters
473
+ * @returns Promise<StripeProduct>
474
+ */
475
+ async createProduct(request) {
476
+ var _a;
477
+ const response = await this.httpClient.post(
478
+ "/api/stripe/products",
479
+ request,
480
+ true
481
+ );
482
+ if (!response.success || !response.data) {
483
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create product");
484
+ }
485
+ return response.data;
486
+ }
487
+ /**
488
+ * Update an existing product (Admin only)
489
+ * @param productId - The product ID to update
490
+ * @param request - Product update parameters
491
+ * @returns Promise<StripeProduct>
492
+ */
493
+ async updateProduct(productId, request) {
494
+ var _a;
495
+ const response = await this.httpClient.put(
496
+ `/api/stripe/products/${productId}`,
497
+ request,
498
+ true
499
+ );
500
+ if (!response.success || !response.data) {
501
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to update product");
502
+ }
503
+ return response.data;
504
+ }
505
+ /**
506
+ * Archive a product (Admin only)
507
+ * @param productId - The product ID to archive
508
+ * @returns Promise<{id: string, archived: boolean, active: boolean}>
509
+ */
510
+ async archiveProduct(productId) {
511
+ var _a;
512
+ const response = await this.httpClient.delete(
513
+ `/api/stripe/products/${productId}`,
514
+ true
515
+ );
516
+ if (!response.success || !response.data) {
517
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to archive product");
518
+ }
519
+ return response.data;
520
+ }
521
+ /**
522
+ * Sync products from Stripe (Admin only)
523
+ * @returns Promise<{synced_count: number, message: string}>
524
+ */
525
+ async syncProducts() {
526
+ var _a;
527
+ const response = await this.httpClient.post(
528
+ "/api/stripe/products/sync",
529
+ {},
530
+ true
531
+ );
532
+ if (!response.success || !response.data) {
533
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to sync products");
534
+ }
535
+ return response.data;
536
+ }
537
+ // Prices
538
+ /**
539
+ * Create a new price for a product (Admin only)
540
+ * @param request - Price creation parameters
541
+ * @returns Promise<StripePrice>
542
+ */
543
+ async createPrice(request) {
544
+ var _a;
545
+ const response = await this.httpClient.post(
546
+ "/api/stripe/prices",
547
+ request,
548
+ true
549
+ );
550
+ if (!response.success || !response.data) {
551
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create price");
552
+ }
553
+ return response.data;
554
+ }
555
+ // Subscriptions
556
+ /**
557
+ * Create a new subscription
558
+ * @param request - Subscription creation parameters
559
+ * @returns Promise<Subscription>
560
+ */
561
+ async createSubscription(request) {
562
+ var _a;
563
+ const response = await this.httpClient.post(
564
+ "/api/stripe/subscriptions",
565
+ request,
566
+ true
567
+ );
568
+ if (!response.success || !response.data) {
569
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create subscription");
570
+ }
571
+ return response.data;
572
+ }
573
+ /**
574
+ * Get a subscription by ID
575
+ * @param subscriptionId - The subscription ID
576
+ * @returns Promise<Subscription>
577
+ */
578
+ async getSubscription(subscriptionId) {
579
+ var _a;
580
+ const response = await this.httpClient.get(
581
+ `/api/stripe/subscriptions/${subscriptionId}`,
582
+ true
583
+ );
584
+ if (!response.success || !response.data) {
585
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to retrieve subscription");
586
+ }
587
+ return response.data;
588
+ }
589
+ /**
590
+ * List subscriptions for the current user
591
+ * @param options - List options
592
+ * @returns Promise<{subscriptions: Subscription[], has_more: boolean}>
593
+ */
594
+ async listSubscriptions(options = {}) {
595
+ var _a;
596
+ const params = new URLSearchParams();
597
+ if (options.limit) params.append("limit", options.limit.toString());
598
+ if (options.starting_after) params.append("starting_after", options.starting_after);
599
+ if (options.status) params.append("status", options.status);
600
+ const url = `/api/stripe/subscriptions${params.toString() ? `?${params.toString()}` : ""}`;
601
+ const response = await this.httpClient.get(url, true);
602
+ if (!response.success || !response.data) {
603
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to list subscriptions");
604
+ }
605
+ return response.data;
606
+ }
607
+ /**
608
+ * Cancel a subscription
609
+ * @param subscriptionId - The subscription ID to cancel
610
+ * @returns Promise<Subscription>
611
+ */
612
+ async cancelSubscription(subscriptionId) {
613
+ var _a;
614
+ const response = await this.httpClient.post(
615
+ `/api/stripe/subscriptions/${subscriptionId}/cancel`,
616
+ {},
617
+ true
618
+ );
619
+ if (!response.success || !response.data) {
620
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to cancel subscription");
621
+ }
622
+ return response.data;
623
+ }
624
+ /**
625
+ * Update a subscription
626
+ * @param subscriptionId - The subscription ID to update
627
+ * @param request - Update parameters
628
+ * @returns Promise<Subscription>
629
+ */
630
+ async updateSubscription(subscriptionId, request) {
631
+ var _a;
632
+ const response = await this.httpClient.put(
633
+ `/api/stripe/subscriptions/${subscriptionId}`,
634
+ request,
635
+ true
636
+ );
637
+ if (!response.success || !response.data) {
638
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to update subscription");
639
+ }
640
+ return response.data;
641
+ }
642
+ // Customer Portal
643
+ /**
644
+ * Create a customer portal session
645
+ * @param request - Portal session parameters
646
+ * @returns Promise<CustomerPortalSession>
647
+ */
648
+ async createCustomerPortalSession(request) {
649
+ var _a;
650
+ const response = await this.httpClient.post(
651
+ "/api/stripe/customer-portal",
652
+ request,
653
+ true
654
+ );
655
+ if (!response.success || !response.data) {
656
+ throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create customer portal session");
657
+ }
658
+ return response.data;
167
659
  }
168
660
  // Utility Methods
169
- isAuthenticated() {
170
- return !!this.accessToken;
661
+ /**
662
+ * Create a one-time payment checkout session
663
+ * Convenience method for simple one-time payments
664
+ * @param params - Payment parameters
665
+ * @returns Promise<CheckoutSession>
666
+ */
667
+ async createPaymentCheckout(params) {
668
+ const lineItems = [];
669
+ if (params.price_id) {
670
+ lineItems.push({
671
+ price_id: params.price_id,
672
+ quantity: params.quantity || 1
673
+ });
674
+ } else if (params.product_name && params.amount && params.currency) {
675
+ lineItems.push({
676
+ quantity: params.quantity || 1,
677
+ price_data: {
678
+ currency: params.currency,
679
+ unit_amount: params.amount,
680
+ product_data: {
681
+ name: params.product_name
682
+ }
683
+ }
684
+ });
685
+ } else {
686
+ throw new Error("Either price_id or (product_name, amount, currency) must be provided");
687
+ }
688
+ return this.createCheckoutSession({
689
+ mode: "payment",
690
+ line_items: lineItems,
691
+ success_url: params.success_url,
692
+ cancel_url: params.cancel_url,
693
+ ...params.metadata && { metadata: params.metadata }
694
+ });
171
695
  }
172
- getAccessToken() {
173
- return this.accessToken;
696
+ /**
697
+ * Create a subscription checkout session
698
+ * Convenience method for subscription creation
699
+ * @param params - Subscription parameters
700
+ * @returns Promise<CheckoutSession>
701
+ */
702
+ async createSubscriptionCheckout(params) {
703
+ return this.createCheckoutSession({
704
+ mode: "subscription",
705
+ line_items: [{
706
+ price_id: params.price_id,
707
+ quantity: 1
708
+ }],
709
+ success_url: params.success_url,
710
+ cancel_url: params.cancel_url,
711
+ subscription_data: {
712
+ ...params.trial_period_days !== void 0 && { trial_period_days: params.trial_period_days },
713
+ ...params.metadata && { metadata: params.metadata }
714
+ }
715
+ });
174
716
  }
717
+ };
718
+
719
+ // index.ts
720
+ var SweetPotatoSDK = class {
721
+ constructor(config) {
722
+ if (!config.apiUrl) {
723
+ throw new Error("apiUrl is required");
724
+ }
725
+ this.httpClient = new HttpClient(config);
726
+ this.auth = new AuthService(this.httpClient);
727
+ this.payments = new PaymentsService(this.httpClient);
728
+ this.isLocalMode = this.httpClient["isLocalMode"] || false;
729
+ if (this.isLocalMode) {
730
+ console.log("[SPAPS SDK] Initialized in local development mode");
731
+ console.log("[SPAPS SDK] API URL:", config.apiUrl);
732
+ console.log("[SPAPS SDK] Authentication will be automatic");
733
+ }
734
+ }
735
+ /**
736
+ * Set access token for authenticated requests
737
+ * @param token - Access token
738
+ */
175
739
  setAccessToken(token) {
176
- this.accessToken = token;
740
+ this.httpClient.setAccessToken(token);
741
+ }
742
+ /**
743
+ * Clear access token
744
+ */
745
+ clearAccessToken() {
746
+ this.httpClient.clearAccessToken();
747
+ }
748
+ /**
749
+ * Get SDK configuration
750
+ */
751
+ getConfig() {
752
+ return {
753
+ apiUrl: this.httpClient["config"].apiUrl,
754
+ timeout: this.httpClient["config"].timeout,
755
+ retries: this.httpClient["config"].retries
756
+ };
757
+ }
758
+ /**
759
+ * Health check endpoint
760
+ * @returns Promise<boolean>
761
+ */
762
+ async healthCheck() {
763
+ try {
764
+ const response = await this.httpClient.get("/api/health");
765
+ return response.success;
766
+ } catch (e) {
767
+ return false;
768
+ }
769
+ }
770
+ /**
771
+ * Make a custom authenticated request
772
+ * This allows advanced users to make direct API calls not covered by the SDK
773
+ */
774
+ async request(method, url, data, requiresAuth = false) {
775
+ return this.httpClient.request({
776
+ method,
777
+ url,
778
+ data,
779
+ requiresAuth
780
+ });
781
+ }
782
+ };
783
+ function createSweetPotatoSDK(config) {
784
+ return new SweetPotatoSDK(config);
785
+ }
786
+ var _TokenManager = class _TokenManager {
787
+ /**
788
+ * Get localStorage instance (browser or test environment)
789
+ */
790
+ static getStorage() {
791
+ var _a, _b;
792
+ if (typeof globalThis !== "undefined" && globalThis.localStorage) {
793
+ return globalThis.localStorage;
794
+ }
795
+ if (typeof globalThis !== "undefined" && ((_a = globalThis.window) == null ? void 0 : _a.localStorage)) {
796
+ return globalThis.window.localStorage;
797
+ }
798
+ if (typeof global !== "undefined" && ((_b = global.window) == null ? void 0 : _b.localStorage)) {
799
+ return global.window.localStorage;
800
+ }
801
+ return null;
802
+ }
803
+ /**
804
+ * Store tokens in localStorage (browser only)
805
+ */
806
+ static storeTokens(tokens) {
807
+ const localStorage = _TokenManager.getStorage();
808
+ if (localStorage) {
809
+ localStorage.setItem(_TokenManager.ACCESS_TOKEN_KEY, tokens.access_token);
810
+ localStorage.setItem(_TokenManager.REFRESH_TOKEN_KEY, tokens.refresh_token);
811
+ localStorage.setItem(_TokenManager.USER_KEY, JSON.stringify(tokens.user));
812
+ }
813
+ }
814
+ /**
815
+ * Get stored access token (browser only)
816
+ */
817
+ static getAccessToken() {
818
+ const localStorage = _TokenManager.getStorage();
819
+ return localStorage ? localStorage.getItem(_TokenManager.ACCESS_TOKEN_KEY) : null;
177
820
  }
178
- isLocalMode() {
179
- return this._isLocalMode;
821
+ /**
822
+ * Get stored refresh token (browser only)
823
+ */
824
+ static getRefreshToken() {
825
+ const localStorage = _TokenManager.getStorage();
826
+ return localStorage ? localStorage.getItem(_TokenManager.REFRESH_TOKEN_KEY) : null;
180
827
  }
181
- async health() {
182
- return this.client.get("/health");
828
+ /**
829
+ * Get stored user data (browser only)
830
+ */
831
+ static getStoredUser() {
832
+ const localStorage = _TokenManager.getStorage();
833
+ if (localStorage) {
834
+ const userData = localStorage.getItem(_TokenManager.USER_KEY);
835
+ return userData ? JSON.parse(userData) : null;
836
+ }
837
+ return null;
838
+ }
839
+ /**
840
+ * Clear all stored tokens and user data (browser only)
841
+ */
842
+ static clearTokens() {
843
+ const localStorage = _TokenManager.getStorage();
844
+ if (localStorage) {
845
+ localStorage.removeItem(_TokenManager.ACCESS_TOKEN_KEY);
846
+ localStorage.removeItem(_TokenManager.REFRESH_TOKEN_KEY);
847
+ localStorage.removeItem(_TokenManager.USER_KEY);
848
+ }
849
+ }
850
+ /**
851
+ * Check if access token is expired (basic check, doesn't verify signature)
852
+ */
853
+ static isTokenExpired(token) {
854
+ try {
855
+ const parts = token.split(".");
856
+ if (parts.length !== 3 || !parts[1]) return true;
857
+ const payload = JSON.parse(atob(parts[1]));
858
+ const currentTime = Math.floor(Date.now() / 1e3);
859
+ return payload.exp < currentTime;
860
+ } catch (e) {
861
+ return true;
862
+ }
863
+ }
864
+ /**
865
+ * Auto-refresh token if needed
866
+ */
867
+ static async autoRefreshToken(sdk) {
868
+ const accessToken = _TokenManager.getAccessToken();
869
+ const refreshToken = _TokenManager.getRefreshToken();
870
+ if (!accessToken || !refreshToken) {
871
+ return false;
872
+ }
873
+ if (!_TokenManager.isTokenExpired(accessToken)) {
874
+ sdk.setAccessToken(accessToken);
875
+ return true;
876
+ }
877
+ try {
878
+ const newTokens = await sdk.auth.refreshToken(refreshToken);
879
+ _TokenManager.storeTokens(newTokens);
880
+ return true;
881
+ } catch (e) {
882
+ _TokenManager.clearTokens();
883
+ return false;
884
+ }
885
+ }
886
+ };
887
+ _TokenManager.ACCESS_TOKEN_KEY = "sweet_potato_access_token";
888
+ _TokenManager.REFRESH_TOKEN_KEY = "sweet_potato_refresh_token";
889
+ _TokenManager.USER_KEY = "sweet_potato_user";
890
+ var TokenManager = _TokenManager;
891
+ var WalletUtils = class _WalletUtils {
892
+ /**
893
+ * Detect chain type from wallet address
894
+ */
895
+ static detectChainType(address) {
896
+ if (/^0x[a-fA-F0-9]{40}$/.test(address)) {
897
+ return "ethereum";
898
+ }
899
+ if (/^bc1[a-z0-9]{39,59}$/.test(address)) {
900
+ return "bitcoin";
901
+ }
902
+ if (/^[1-9A-HJ-NP-Za-km-z]{32}$/.test(address) || /^[1-9A-HJ-NP-Za-km-z]{44}$/.test(address)) {
903
+ return "solana";
904
+ }
905
+ if (/^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(address) && address.length >= 26 && address.length <= 35) {
906
+ return "bitcoin";
907
+ }
908
+ if (/^[1-9A-HJ-NP-Za-km-z]{35,44}$/.test(address)) {
909
+ return "solana";
910
+ }
911
+ return null;
912
+ }
913
+ /**
914
+ * Validate wallet address format
915
+ */
916
+ static isValidAddress(address, chainType) {
917
+ if (!chainType) {
918
+ chainType = _WalletUtils.detectChainType(address) || "ethereum";
919
+ }
920
+ switch (chainType) {
921
+ case "solana":
922
+ return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
923
+ case "ethereum":
924
+ case "base":
925
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
926
+ case "bitcoin":
927
+ return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(address) || /^bc1[a-z0-9]{39,59}$/.test(address);
928
+ default:
929
+ return false;
930
+ }
183
931
  }
184
932
  };
185
- var index_default = SPAPSClient;
186
933
  // Annotate the CommonJS export names for ESM import in node:
187
934
  0 && (module.exports = {
188
- SPAPS,
189
- SPAPSClient,
190
- SweetPotatoSDK
935
+ AuthService,
936
+ HttpClient,
937
+ PaymentsService,
938
+ SweetPotatoAPIError,
939
+ SweetPotatoSDK,
940
+ TokenManager,
941
+ WalletUtils,
942
+ createSweetPotatoSDK
191
943
  });