opencloud-platform-sdk 1.2.0 → 2.0.0

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/README.md CHANGED
@@ -1,209 +1,191 @@
1
- # @opencloud/sdk
1
+ # opencloud-platform-sdk
2
2
 
3
- Official SDK for **OpenCloud** - The AI App Marketplace with pay-per-use model.
3
+ Official SDK for **OpenCloud** - Monetize your AI apps with ease.
4
4
 
5
- Build AI-powered apps that automatically handle payments and AI API calls through OpenCloud's platform.
5
+ **You control the AI, we handle the payments.**
6
6
 
7
- ## Features
7
+ ## What's New in v2.0
8
8
 
9
- - Call 100+ AI models (GPT-4, Claude, Gemini, Llama, etc.) via OpenRouter
10
- - Automatic payment processing (70% to creators, 30% to platform)
11
- - No API keys needed - OpenCloud handles everything
12
- - ✅ TypeScript support with full type definitions
13
- - ✅ Works in browsers and Node.js
14
- - ✅ Zero dependencies
9
+ - **Use your own AI** - OpenAI, Anthropic, your own model, whatever you want
10
+ - **Set your own price** - Charge what you want per use
11
+ - **85/15 split** - You keep 85%, platform takes 15%
15
12
 
16
13
  ## Installation
17
14
 
18
15
  ```bash
19
- npm install @opencloud/sdk
20
- # or
21
- pnpm add @opencloud/sdk
22
- # or
23
- yarn add @opencloud/sdk
16
+ npm install opencloud-platform-sdk
24
17
  ```
25
18
 
26
19
  ## Quick Start
27
20
 
28
- ### For React/Next.js Apps
29
-
30
21
  ```typescript
31
- import { opencloud } from '@opencloud/sdk';
22
+ import { opencloud } from 'opencloud-platform-sdk';
32
23
 
33
- // Initialize with your app ID
24
+ // 1. Initialize with your app ID
34
25
  opencloud.init({ appId: 'your-app-slug' });
35
26
 
36
- // Call AI models
37
- const response = await opencloud.callAI({
38
- model: 'openai/gpt-4',
39
- prompt: 'Write a tagline for my startup'
40
- });
41
-
42
- console.log(response.text); // AI-generated response
43
- console.log(response.cost); // $0.10 (or your app's price per use)
44
- ```
45
-
46
- ### For HTML/Vanilla JS
47
-
48
- ```html
49
- <script src="https://opencloud.com/sdk/platform-sdk.js"></script>
50
-
51
- <script>
52
- PlatformSDK.init({ appId: 'your-app-slug' });
27
+ // 2. Check if user can afford
28
+ const canUse = await opencloud.canAfford();
29
+ if (!canUse) {
30
+ opencloud.requestTopUp();
31
+ return;
32
+ }
53
33
 
54
- async function generate() {
55
- const result = await PlatformSDK.callAI({
56
- model: 'anthropic/claude-3-5-sonnet',
57
- prompt: 'Generate a logo description'
58
- });
34
+ // 3. Call YOUR OWN AI (you control this)
35
+ const response = await fetch('https://api.openai.com/v1/chat/completions', {
36
+ method: 'POST',
37
+ headers: { 'Authorization': 'Bearer YOUR_API_KEY' },
38
+ body: JSON.stringify({
39
+ model: 'gpt-4',
40
+ messages: [{ role: 'user', content: 'Hello!' }]
41
+ })
42
+ });
59
43
 
60
- console.log(result.text);
61
- }
62
- </script>
44
+ // 4. Charge the user
45
+ const result = await opencloud.trackUsage({ action: 'chat' });
46
+ console.log('Charged:', result.charged);
47
+ console.log('User balance:', result.userBalance);
63
48
  ```
64
49
 
65
50
  ## API Reference
66
51
 
67
52
  ### `opencloud.init(config)`
68
53
 
69
- Initialize the SDK with your app configuration.
54
+ Initialize the SDK.
70
55
 
71
56
  ```typescript
72
57
  opencloud.init({
73
- appId: 'your-app-slug', // Required: Your app's unique identifier
74
- apiUrl: 'https://opencloud.com' // Optional: Platform URL (defaults to current origin)
58
+ appId: 'your-app-slug', // Required
59
+ apiUrl: 'https://opencloud.app' // Optional
75
60
  });
76
61
  ```
77
62
 
78
- ### `opencloud.callAI(params)`
63
+ ### `opencloud.canAfford()`
79
64
 
80
- Call an AI model through OpenCloud's platform.
65
+ Check if user has enough balance.
81
66
 
82
67
  ```typescript
83
- const response = await opencloud.callAI({
84
- model: 'openai/gpt-4', // Required: Model identifier
85
- prompt: 'Your prompt here', // Required: The prompt to send
86
- options: { // Optional: Additional model parameters
87
- temperature: 0.7,
88
- max_tokens: 1000
89
- }
68
+ const canUse = await opencloud.canAfford();
69
+ if (!canUse) {
70
+ opencloud.requestTopUp();
71
+ return;
72
+ }
73
+ ```
74
+
75
+ ### `opencloud.trackUsage(options)`
76
+
77
+ Charge the user. This is the main method to monetize your app.
78
+
79
+ ```typescript
80
+ const result = await opencloud.trackUsage({
81
+ action: 'chat_message', // Optional: for analytics
82
+ metadata: { model: 'gpt-4' } // Optional: extra data
90
83
  });
91
84
 
92
- // Response structure:
85
+ // Response:
93
86
  {
94
87
  success: true,
95
- text: "AI-generated response...",
96
- usage: {
97
- promptTokens: 10,
98
- completionTokens: 50,
99
- totalTokens: 60
100
- },
101
- cost: 0.10, // Amount charged to user
102
- model: "openai/gpt-4"
88
+ charged: 0.10,
89
+ userBalance: 4.90,
90
+ transactionId: 'tx_abc123'
103
91
  }
104
92
  ```
105
93
 
106
- ### `opencloud.getBalance()`
94
+ ### `opencloud.withUsage(fn, options)` (Optional)
107
95
 
108
- Get the current user's token balance.
96
+ Convenience method that combines canAfford + your code + trackUsage.
109
97
 
110
98
  ```typescript
111
- const balance = await opencloud.getBalance();
112
- console.log(`Balance: $${balance}`);
99
+ const response = await opencloud.withUsage(async () => {
100
+ // Your AI call here - only runs if user can pay
101
+ return await myAICall();
102
+ }, { action: 'chat' });
113
103
  ```
114
104
 
115
- ### `opencloud.requestTopUp()`
105
+ ### `opencloud.getBalance()`
116
106
 
117
- Request the user to purchase more tokens (opens payment dialog).
107
+ Get user's current balance.
118
108
 
119
109
  ```typescript
120
- try {
121
- await opencloud.callAI({...});
122
- } catch (error) {
123
- if (error.message.includes('Insufficient balance')) {
124
- await opencloud.requestTopUp();
125
- }
126
- }
110
+ const balance = await opencloud.getBalance();
111
+ console.log(`Balance: $${balance}`);
127
112
  ```
128
113
 
129
- ## Supported AI Models
114
+ ### `opencloud.getAppPrice()`
130
115
 
131
- OpenCloud uses OpenRouter, giving you access to 100+ models:
116
+ Get your app's price per use.
132
117
 
133
- **OpenAI:**
134
- - `openai/gpt-4`
135
- - `openai/gpt-4-turbo`
136
- - `openai/gpt-3.5-turbo`
137
-
138
- **Anthropic:**
139
- - `anthropic/claude-3-5-sonnet`
140
- - `anthropic/claude-3-haiku`
141
- - `anthropic/claude-3-opus`
118
+ ```typescript
119
+ const price = await opencloud.getAppPrice();
120
+ console.log(`Price: $${price}`);
121
+ ```
142
122
 
143
- **Google:**
144
- - `google/gemini-pro`
145
- - `google/gemini-pro-vision`
123
+ ### `opencloud.requestTopUp()`
146
124
 
147
- **Meta:**
148
- - `meta-llama/llama-3-70b`
149
- - `meta-llama/llama-3-8b`
125
+ Open the payment dialog for user to add credits.
150
126
 
151
- **And many more!** See [OpenRouter docs](https://openrouter.ai/docs) for full list.
127
+ ```typescript
128
+ opencloud.requestTopUp();
129
+ ```
152
130
 
153
- ## Example Apps
131
+ ### `opencloud.getUserInfo()`
154
132
 
155
- ### Text Summarizer
133
+ Get current user information.
156
134
 
157
135
  ```typescript
158
- import { opencloud } from '@opencloud/sdk';
136
+ const user = await opencloud.getUserInfo();
137
+ // { id, email, balance, username }
138
+ ```
159
139
 
160
- opencloud.init({ appId: 'text-summarizer' });
140
+ ### `opencloud.isPreview()`
161
141
 
162
- async function summarize(text: string) {
163
- const response = await opencloud.callAI({
164
- model: 'anthropic/claude-3-haiku', // Fast and cheap
165
- prompt: `Summarize this text in 3 bullet points:\n\n${text}`
166
- });
142
+ Check if running in development mode (localhost, etc).
167
143
 
168
- return response.text;
144
+ ```typescript
145
+ if (opencloud.isPreview()) {
146
+ console.log('Preview mode - no real charges');
169
147
  }
170
148
  ```
171
149
 
172
- ### Image Description Generator
150
+ ## Revenue Model
173
151
 
174
- ```typescript
175
- import { opencloud } from '@opencloud/sdk';
152
+ **85/15 split** - You keep most of what you earn!
176
153
 
177
- opencloud.init({ appId: 'image-describer' });
154
+ ```
155
+ User pays: $0.10 per use
156
+ ├─ You get: $0.085 (85%)
157
+ └─ Platform: $0.015 (15%)
158
+ ```
178
159
 
179
- async function describeImage(imageUrl: string) {
180
- const response = await opencloud.callAI({
181
- model: 'google/gemini-pro-vision',
182
- prompt: 'Describe this image in detail',
183
- options: {
184
- image: imageUrl
185
- }
186
- });
160
+ ## Error Handling
187
161
 
188
- return response.text;
162
+ ```typescript
163
+ try {
164
+ await opencloud.trackUsage({ action: 'chat' });
165
+ } catch (error) {
166
+ if (error.message === 'INSUFFICIENT_BALANCE') {
167
+ opencloud.requestTopUp();
168
+ }
189
169
  }
190
170
  ```
191
171
 
192
- ## Revenue Model
172
+ ## Preview Mode
193
173
 
194
- OpenCloud uses a **70/30 revenue split**:
174
+ When running locally (localhost, etc), the SDK automatically enters preview mode:
175
+ - `trackUsage()` doesn't charge real money
176
+ - `getBalance()` returns 999.99
177
+ - `canAfford()` always returns true
195
178
 
196
- - **70%** goes to you (the app creator)
197
- - **30%** goes to OpenCloud (platform fee)
179
+ This lets you develop without worrying about charges.
198
180
 
199
- Example:
200
- ```
201
- User pays: $0.10 per use
202
- AI cost: -$0.03 (OpenAI API)
203
- Net revenue: $0.07
204
- ├─ You get: $0.049 (70%)
205
- └─ Platform: $0.021 (30%)
206
- ```
181
+ ## Publishing Your App
182
+
183
+ 1. Deploy your app to Vercel via [opencloud.app/deploy](/deploy)
184
+ 2. Go to [opencloud.app/publish](/publish)
185
+ 3. Select your deployed project
186
+ 4. Set name, description, and **price per use**
187
+ 5. Sign the creator agreement (85/15 split)
188
+ 6. Publish!
207
189
 
208
190
  ## TypeScript Support
209
191
 
@@ -213,35 +195,17 @@ Full TypeScript definitions included:
213
195
  import {
214
196
  opencloud,
215
197
  OpenCloudSDK,
216
- AICallParams,
217
- AIResponse,
218
- OpenCloudConfig
219
- } from '@opencloud/sdk';
220
-
221
- const params: AICallParams = {
222
- model: 'openai/gpt-4',
223
- prompt: 'Hello world'
224
- };
225
-
226
- const response: AIResponse = await opencloud.callAI(params);
198
+ TrackUsageParams,
199
+ TrackUsageResponse,
200
+ UserInfo
201
+ } from 'opencloud-platform-sdk';
227
202
  ```
228
203
 
229
- ## Publishing Your App
230
-
231
- 1. Build your app with the SDK
232
- 2. Go to [opencloud.com/publish](https://opencloud.com/publish)
233
- 3. Upload your app or connect GitHub
234
- 4. Set pricing and details
235
- 5. Test with $5 free credits
236
- 6. Publish to marketplace!
237
-
238
204
  ## Support
239
205
 
240
- - 📚 [Documentation](https://opencloud.com/docs)
241
- - 💬 [Discord Community](https://discord.gg/opencloud)
242
- - 🐛 [Report Issues](https://github.com/opencloud/sdk/issues)
243
- - ✉️ support@opencloud.com
206
+ - Docs: [opencloud.app/docs](/docs)
207
+ - Issues: [github.com/opencloud/sdk](https://github.com/opencloud/sdk/issues)
244
208
 
245
209
  ## License
246
210
 
247
- MIT © OpenCloud
211
+ MIT
package/dist/index.d.mts CHANGED
@@ -1,101 +1,130 @@
1
1
  /**
2
- * opencloud-platform-sdk v1.2.0
2
+ * opencloud-platform-sdk v2.0.0
3
3
  * Official SDK for OpenCloud - AI App Marketplace
4
4
  *
5
- * Features:
6
- * - Automatic preview/production mode detection
7
- * - Works in bolt.diy/WebContainers preview
8
- * - Auto-detects API keys from bolt.diy builder
9
- * - Seamless transition to production with credits
5
+ * New Model:
6
+ * - Creators use their own AI/APIs
7
+ * - SDK only tracks usage and charges end users
8
+ * - Creators set price per use, platform takes 15% commission
10
9
  */
11
10
  interface OpenCloudConfig {
12
11
  appId: string;
13
12
  apiUrl?: string;
14
- previewApiKey?: string;
15
13
  }
16
- interface AICallParams {
17
- model: string;
18
- prompt: string;
19
- options?: Record<string, any>;
14
+ interface TrackUsageParams {
15
+ action?: string;
16
+ metadata?: Record<string, any>;
20
17
  }
21
- interface AIResponse {
18
+ interface TrackUsageResponse {
22
19
  success: boolean;
23
- text: string;
24
- usage: {
25
- promptTokens: number;
26
- completionTokens: number;
27
- totalTokens: number;
28
- };
29
- cost: number;
30
- model: string;
31
- mode: 'preview' | 'production';
20
+ charged: number;
21
+ userBalance: number;
22
+ transactionId: string;
32
23
  }
33
24
  interface UserSession {
34
25
  token: string;
35
26
  }
27
+ interface UserInfo {
28
+ id: string;
29
+ email: string;
30
+ balance: number;
31
+ username?: string;
32
+ }
36
33
  declare class OpenCloudSDK {
37
34
  private config;
38
35
  private heartbeatInterval?;
39
36
  private _isPreviewMode;
37
+ private _cachedSession;
40
38
  constructor();
41
- /**
42
- * Detect if running in preview/development mode
43
- */
44
39
  private detectPreviewMode;
45
40
  /**
46
- * Check if currently in preview mode
41
+ * Check if running in preview/development mode
47
42
  */
48
43
  isPreview(): boolean;
49
44
  /**
50
- * Initialize the SDK
45
+ * Initialize the SDK with your app ID
51
46
  */
52
47
  init(options: OpenCloudConfig): void;
53
48
  /**
54
- * Set API key for preview mode
49
+ * Track a usage event and charge the user
50
+ * Call this BEFORE or AFTER your AI/API call
51
+ *
52
+ * Example:
53
+ * ```
54
+ * // Check if user can afford it first
55
+ * const canUse = await opencloud.canAfford();
56
+ * if (!canUse) {
57
+ * opencloud.requestTopUp();
58
+ * return;
59
+ * }
60
+ *
61
+ * // Do your AI call
62
+ * const result = await myAICall();
63
+ *
64
+ * // Track the usage (charges user)
65
+ * await opencloud.trackUsage({ action: 'chat_message' });
66
+ * ```
55
67
  */
56
- setPreviewApiKey(key: string, provider?: 'openrouter' | 'anthropic' | 'openai'): void;
68
+ trackUsage(params?: TrackUsageParams): Promise<TrackUsageResponse>;
57
69
  /**
58
- * Get API key for preview mode
59
- * Checks in order: config, localStorage, bolt.diy cookies
70
+ * Check if the user can afford to use the app
71
+ * Returns true if user has enough balance
60
72
  */
61
- private getPreviewApiKey;
73
+ canAfford(): Promise<boolean>;
62
74
  /**
63
- * Call an AI model - automatically uses preview or production mode
75
+ * Get current user's balance
64
76
  */
65
- callAI(params: AICallParams): Promise<AIResponse>;
77
+ getBalance(): Promise<number>;
66
78
  /**
67
- * Call AI in preview mode (direct to OpenRouter/provider)
79
+ * Get current user info
68
80
  */
69
- private callAIPreview;
81
+ getUserInfo(): Promise<UserInfo>;
70
82
  /**
71
- * Call AI in production mode (through OpenCloud API)
83
+ * Get the price per use for this app
72
84
  */
73
- private callAIProduction;
85
+ getAppPrice(): Promise<number>;
74
86
  /**
75
- * Get current user's balance (production only)
87
+ * Request user to add more credits
88
+ * Opens the top-up modal or redirects to payment page
76
89
  */
77
- getBalance(): Promise<number>;
90
+ requestTopUp(): void;
78
91
  /**
79
- * Request user to purchase more tokens
92
+ * Check if user is authenticated
80
93
  */
81
- requestTopUp(): Promise<void>;
94
+ isAuthenticated(): Promise<boolean>;
82
95
  /**
83
- * Start sending heartbeats
96
+ * Request user to log in
84
97
  */
98
+ requestLogin(): void;
85
99
  private startHeartbeat;
86
- /**
87
- * Send heartbeat to platform
88
- */
89
100
  private sendHeartbeat;
101
+ private getUserSession;
90
102
  /**
91
- * Get user session token
103
+ * Clear cached session (call on logout)
92
104
  */
93
- private getUserSession;
105
+ clearSession(): void;
94
106
  /**
95
- * Cleanup
107
+ * Cleanup resources
96
108
  */
97
109
  destroy(): void;
110
+ /**
111
+ * Execute a function and automatically charge the user
112
+ * This is a convenience method that combines canAfford + your code + trackUsage
113
+ *
114
+ * @param fn - The async function to execute (your AI call, etc.)
115
+ * @param options - Optional tracking options
116
+ * @returns The result of your function
117
+ *
118
+ * Example:
119
+ * ```typescript
120
+ * const result = await opencloud.withUsage(async () => {
121
+ * const response = await fetch('https://api.openai.com/...', { ... });
122
+ * return await response.json();
123
+ * }, { action: 'chat_message' });
124
+ * ```
125
+ */
126
+ withUsage<T>(fn: () => Promise<T>, options?: TrackUsageParams): Promise<T>;
98
127
  }
99
128
  declare const opencloud: OpenCloudSDK;
100
129
 
101
- export { type AICallParams, type AIResponse, type OpenCloudConfig, OpenCloudSDK, type UserSession, opencloud };
130
+ export { type OpenCloudConfig, OpenCloudSDK, type TrackUsageParams, type TrackUsageResponse, type UserInfo, type UserSession, opencloud };