bytex-sdk 5.5.0 → 5.7.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,56 +1,45 @@
1
- # ByteX SDK
2
- > The official SDK for the ByteX Cloud Ecosystem.
1
+ # ByteX Cloud SDK 🚀
3
2
 
4
- ByteX SDK provides a powerful, easy-to-use interface for interacting with ByteX Cloud storage and infrastructure. It supports both Supabase and Firebase backends, enabling a true "Bring Your Own Cloud" (BYOC) experience.
3
+ The official SDK for the ByteX ecosystem, enabling developers to build professional "Super SaaS" products with 100% cloud sovereignty (BYOC).
5
4
 
6
- ## Features
7
- - **Multi-Provider**: Seamlessly switch between Supabase and Firebase.
8
- - **Advanced Encryption**: Built-in AES-CTR encryption for secure file storage.
9
- - **Streaming Support**: Direct streaming for media files (video/audio).
10
- - **CDN Integration**: Purge and manage global CDN cache.
11
- - **Middleware System**: Intercept and optimize uploads (e.g., auto-convert to WebP).
12
- - **Bulk Operations**: Download or export entire projects as ZIP.
5
+ ## Features
6
+ - 🔐 **Secure Authentication**: Integrated with Supabase.
7
+ - 📦 **Data Persistence**: Upload and download streams directly to your own Cloud (HuggingFace).
8
+ - 🕵️‍♂️ **X-Ray Diagnostics**: Built-in network and infrastructure health checks.
9
+ - **Lightweight**: Zero-config needed for most use cases.
13
10
 
14
- ## 📦 Installation
11
+ ## Installation
15
12
  ```bash
16
- npm install bytex-sdk
13
+ npm install @bytex/cloud-sdk
17
14
  ```
18
15
 
19
- ## 🚀 Quick Start
16
+ ## Quick Start
17
+
18
+ ### Initialize
20
19
  ```javascript
21
- import { BytexCloud } from 'bytex-sdk';
20
+ import { BytexCloud } from '@bytex/cloud-sdk';
21
+ import AsyncStorage from '@react-native-async-storage/async-storage';
22
22
 
23
- // Initialize with your API Key
24
- const bytex = new BytexCloud({
25
- apiKey: 'BTX-USER-XXXXXXXX',
26
- dbProvider: 'supabase' // or 'firebase'
23
+ const bytex = new BytexCloud({
24
+ apiKey: 'YOUR_API_KEY',
25
+ workerUrl: 'https://api.bytex.work/',
26
+ storage: AsyncStorage // for React Native
27
27
  });
28
-
29
- // Upload a file
30
- await bytex.upload('hello.txt', 'Hello World');
31
-
32
- // Get a streaming URL
33
- const streamUrl = bytex.stream('video.mp4');
34
-
35
- // List files
36
- const files = await bytex.listFiles();
37
- console.log(files);
38
28
  ```
39
29
 
40
- ## 🛠 Advanced Usage: Middleware
30
+ ### Upload Data
41
31
  ```javascript
42
- import { BytexCloud, BytexMiddlewares } from 'bytex-sdk';
43
-
44
- const bytex = new BytexCloud({ apiKey: '...' });
45
-
46
- // Automatically optimize images to WebP before upload
47
- bytex.use(BytexMiddlewares.imageOptimizer(0.8));
48
-
49
- await bytex.upload('photo.jpg', fileData); // Uploads as photo.webp
32
+ await bytex.uploadData('my_project', {
33
+ status: 'active',
34
+ users: 1000
35
+ });
50
36
  ```
51
37
 
52
- ## 🛡 Security
53
- All storage operations are authenticated via API keys. Data can be encrypted locally using standard or custom encryption keys, ensuring that your storage provider never sees raw data.
38
+ ### Infrastructure Health Check (X-Ray)
39
+ ```javascript
40
+ const report = await bytex.xray();
41
+ console.log(report.checks);
42
+ ```
54
43
 
55
- ## 📄 License
56
- ISC © ByteX Ecosystem
44
+ ## License
45
+ MIT © ByteX Guru
package/package.json CHANGED
@@ -1,18 +1,23 @@
1
1
  {
2
2
  "name": "bytex-sdk",
3
- "version": "5.5.0",
4
- "description": "Official ByteX Cloud SDK with AI (BYOM) support",
5
- "main": "index.js",
3
+ "version": "5.7.0",
4
+ "description": "The official ByteX Cloud SDK for BYOC (Bring Your Own Cloud) infrastructure management.",
5
+ "main": "src/index.js",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1",
8
- "postinstall": "node postinstall.js"
7
+ "test": "echo \"Error: no test specified\" && exit 1"
9
8
  },
9
+ "keywords": [
10
+ "bytex",
11
+ "cloud",
12
+ "saas",
13
+ "byoc",
14
+ "supabase",
15
+ "huggingface"
16
+ ],
17
+ "author": "ByteX Guru",
18
+ "license": "MIT",
10
19
  "dependencies": {
11
- "@supabase/supabase-js": "^2.105.4",
12
- "chalk": "^5.3.0"
13
- },
14
- "keywords": ["bytex", "cloud", "storage", "ai", "byom", "byoc"],
15
- "author": "ByteX Team",
16
- "license": "ISC",
17
- "type": "module"
20
+ "@supabase/supabase-js": "^2.39.0",
21
+ "react-native-url-polyfill": "^2.0.0"
22
+ }
18
23
  }
package/src/index.js ADDED
@@ -0,0 +1,183 @@
1
+ import { createClient } from '@supabase/supabase-js';
2
+
3
+ const SUPABASE_URL = 'https://vkiddclfbwmslaiyyftl.supabase.co';
4
+ const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZraWRkY2xmYndtc2xhaXl5ZnRsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzgzMDYyNjMsImV4cCI6MjA5Mzg4MjI2M30.VMtzB_I_b6WptKoxCko-vRQ5yPIBliOxNaxcRmqezSs';
5
+ const WORKER_URL = 'https://api.bytex.work/';
6
+
7
+ export class BytexCloud {
8
+ constructor(config = {}) {
9
+ this.config = config;
10
+ this.apiKey = config.apiKey || null;
11
+ this.workerUrl = config.workerUrl || WORKER_URL;
12
+
13
+ const supabaseConfig = {
14
+ auth: {
15
+ persistSession: true,
16
+ autoRefreshToken: true,
17
+ detectSessionInUrl: false
18
+ }
19
+ };
20
+ if (config.storage) {
21
+ supabaseConfig.auth.storage = config.storage;
22
+ }
23
+
24
+ this.supabase = createClient(
25
+ config.supabaseUrl || SUPABASE_URL,
26
+ config.supabaseKey || SUPABASE_ANON_KEY,
27
+ supabaseConfig
28
+ );
29
+ this._listeners = {};
30
+ }
31
+
32
+ async _execute(fn, action) {
33
+ try {
34
+ return await fn();
35
+ } catch (e) {
36
+ const diag = await this.xray();
37
+ const advice = diag.advice.length > 0 ? `\n[X-RAY Advice]: ${diag.advice.join(' ')}` : '';
38
+ throw new Error(`${action} failed: ${e.message}${advice}`);
39
+ }
40
+ }
41
+
42
+ async login(email, password) {
43
+ return this._execute(async () => {
44
+ const { data, error } = await this.supabase.auth.signInWithPassword({ email, password });
45
+ if (error) throw error;
46
+ return data.user;
47
+ }, 'Login');
48
+ }
49
+
50
+ async register(email, password) {
51
+ return this._execute(async () => {
52
+ const { data, error } = await this.supabase.auth.signUp({ email, password });
53
+ if (error) throw error;
54
+ return data.user;
55
+ }, 'Register');
56
+ }
57
+
58
+ async logout() {
59
+ await this.supabase.auth.signOut();
60
+ }
61
+
62
+ async getUser() {
63
+ const { data: { session } } = await this.supabase.auth.getSession();
64
+ return session?.user || null;
65
+ }
66
+
67
+ async upload(name, data) {
68
+ return this._execute(async () => {
69
+ this._requireKey();
70
+ const fd = new FormData();
71
+ if (data && typeof data === 'object' && data.uri) {
72
+ // React Native specific FormData file upload
73
+ const rnFile = {
74
+ uri: data.uri,
75
+ name: name, // Enforce full folder path
76
+ type: data.type || 'audio/mpeg'
77
+ };
78
+ fd.append('file', rnFile);
79
+ } else {
80
+ fd.append('file', data instanceof Blob ? data : new Blob([data]), name);
81
+ }
82
+ const { data: { session } } = await this.supabase.auth.getSession();
83
+ const res = await fetch(`${this.workerUrl}?action=upload&key=${this.apiKey}&file=${encodeURIComponent(name)}`, {
84
+ method: 'POST',
85
+ headers: { 'Authorization': `Bearer ${session?.access_token || ''}` },
86
+ body: fd
87
+ });
88
+ if (!res.ok) throw new Error(await res.text() || res.statusText);
89
+ return await res.json();
90
+ }, 'Upload');
91
+ }
92
+
93
+ async uploadData(name, data) {
94
+ return this._execute(async () => {
95
+ this._requireKey();
96
+ const streamName = name.endsWith('.btx') ? name : `${name}.stream.btx`;
97
+ const url = `${this.workerUrl}?action=upload&key=${this.apiKey}&file=${encodeURIComponent(streamName)}`;
98
+ const { data: { session } } = await this.supabase.auth.getSession();
99
+
100
+ const payload = typeof data === 'string' ? data : JSON.stringify(data);
101
+
102
+ const res = await fetch(url, {
103
+ method: 'POST',
104
+ headers: {
105
+ 'Authorization': `Bearer ${session?.access_token || ''}`,
106
+ 'Content-Type': 'application/json'
107
+ },
108
+ body: payload
109
+ });
110
+
111
+ if (!res.ok) throw new Error(`Upload failed with status ${res.status}`);
112
+ return await res.json();
113
+ }, 'Upload');
114
+ }
115
+
116
+ async downloadData(name) {
117
+ return this._execute(async () => {
118
+ this._requireKey();
119
+ const streamName = name.endsWith('.btx') ? name : `${name}.stream.btx`;
120
+ const url = `${this.workerUrl}?action=view&key=${this.apiKey}&file=${encodeURIComponent(streamName)}&_cb=${Date.now()}`;
121
+ const { data: { session } } = await this.supabase.auth.getSession();
122
+ const res = await fetch(url, {
123
+ headers: { 'Authorization': `Bearer ${session?.access_token || ''}` }
124
+ });
125
+ if (!res.ok) throw new Error(`Status ${res.status}`);
126
+ const text = await res.text();
127
+ try { return JSON.parse(text); } catch (e) { return text.split('\n').filter(Boolean).map(line => JSON.parse(line)); }
128
+ }, 'Download');
129
+ }
130
+
131
+ getStreamUrl(name) {
132
+ const streamName = name.endsWith('.btx') ? name : (name.endsWith('.stream.btx') ? name : `${name}.stream.btx`);
133
+ return `${this.workerUrl}?action=view&key=${this.apiKey}&file=${encodeURIComponent(streamName)}`;
134
+ }
135
+
136
+ async download(name) {
137
+ return this._execute(async () => {
138
+ this._requireKey();
139
+ const url = this.getStreamUrl(name);
140
+ const { data: { session } } = await this.supabase.auth.getSession();
141
+ const res = await fetch(url, {
142
+ headers: { 'Authorization': `Bearer ${session?.access_token || ''}` }
143
+ });
144
+ if (!res.ok) throw new Error(`Status ${res.status}`);
145
+ return await res.blob();
146
+ }, 'Download');
147
+ }
148
+
149
+ async delete(name) {
150
+ return this._execute(async () => {
151
+ this._requireKey();
152
+ const streamName = name.endsWith('.btx') ? name : `${name}.stream.btx`;
153
+ const { data: { session } } = await this.supabase.auth.getSession();
154
+ const res = await fetch(`${this.workerUrl}?action=delete&key=${this.apiKey}&file=${encodeURIComponent(streamName)}`, {
155
+ method: 'DELETE',
156
+ headers: { 'Authorization': `Bearer ${session?.access_token || ''}` }
157
+ });
158
+ if (!res.ok) throw new Error(`Status ${res.status}`);
159
+ return true;
160
+ }, 'Delete');
161
+ }
162
+
163
+ async xray() {
164
+ const report = { timestamp: new Date().toISOString(), checks: {}, advice: [] };
165
+ const { data: { session } } = await this.supabase.auth.getSession();
166
+
167
+ try {
168
+ const res = await fetch(`${this.workerUrl}?action=list&key=${this.apiKey}`);
169
+ report.checks.connectivity = res.ok ? 'OK' : 'ERROR';
170
+ } catch (e) {
171
+ report.checks.connectivity = 'OFFLINE';
172
+ report.advice.push('ByteX Cloud unreachable. Check internet connection.');
173
+ }
174
+
175
+ if (!this.apiKey) report.advice.push('API Key is missing.');
176
+ if (!session) report.advice.push('User is not logged in.');
177
+ if (!this.config.storage) report.advice.push('AsyncStorage engine is missing.');
178
+
179
+ return report;
180
+ }
181
+
182
+ _requireKey() { if (!this.apiKey) throw new Error('API Key required!'); }
183
+ }
package/index.js DELETED
@@ -1,930 +0,0 @@
1
- import { createClient } from '@supabase/supabase-js';
2
-
3
- const SUPABASE_URL = 'https://vkiddclfbwmslaiyyftl.supabase.co';
4
- const SUPABASE_ANON_KEY = 'sb_publishable_hXMlH9OmJG1_n1s-3lbXKg_6V-88Lj9';
5
- const WORKER_URL = 'https://api.bytex.work/';
6
-
7
- export class BytexCloud {
8
- constructor(config = {}) {
9
- this.config = config;
10
- this.apiKey = config.apiKey || null;
11
- this.workerUrl = config.workerUrl || WORKER_URL;
12
-
13
- const supabaseConfig = {
14
- auth: {
15
- persistSession: true,
16
- autoRefreshToken: true,
17
- detectSessionInUrl: false
18
- }
19
- };
20
- if (config.storage) {
21
- supabaseConfig.auth.storage = config.storage;
22
- }
23
-
24
- this.supabase = createClient(config.supabaseUrl || SUPABASE_URL, config.supabaseKey || SUPABASE_ANON_KEY, supabaseConfig);
25
- this._listeners = {};
26
- }
27
-
28
- // --- AUTO X-RAY WRAPPER ---
29
- async _execute(fn, actionName) {
30
- try {
31
- return await fn();
32
- } catch (e) {
33
- console.warn(`[ByteX SDK] Error in ${actionName}. Running Auto X-RAY...`);
34
- const diagnostic = await this.xray();
35
- const advice = diagnostic.advice.length > 0 ? `\n[X-RAY Advice]: ${diagnostic.advice.join(' ')}` : '';
36
- throw new Error(`${actionName} failed: ${e.message}${advice}`);
37
- }
38
- }
39
-
40
- // --- CORE METHODS (ENHANCED WITH AUTO X-RAY) ---
41
- async login(email, password) {
42
- return this._execute(async () => {
43
- const { data, error } = await this.supabase.auth.signInWithPassword({ email, password });
44
- if (error) throw error;
45
- return data.user;
46
- }, 'Login');
47
- }
48
-
49
- async upload(name, data) {
50
- return this._execute(async () => {
51
- this._requireKey();
52
- const fd = new FormData();
53
- fd.append('file', data instanceof Blob ? data : new Blob([data]), name);
54
- const res = await fetch(`${this.workerUrl}?action=upload&key=${this.apiKey}`, { method: 'POST', body: fd });
55
- if (!res.ok) throw new Error(await res.text() || res.statusText);
56
- return await res.json();
57
- }, 'Upload');
58
- }
59
-
60
- async downloadData(name) {
61
- return this._execute(async () => {
62
- this._requireKey();
63
- const streamName = name.endsWith('.btx') ? name : `${name}.stream.btx`;
64
- const url = `${this.workerUrl}?action=view&key=${this.apiKey}&file=${encodeURIComponent(streamName)}&_cb=${Date.now()}`;
65
- const { data: { session } } = await this.supabase.auth.getSession();
66
- const res = await fetch(url, { headers: { 'Authorization': `Bearer ${session?.access_token || ''}` } });
67
- if (!res.ok) throw new Error(`Status ${res.status}`);
68
- const text = await res.text();
69
- try { return JSON.parse(text); } catch (e) { return text.split('\n').filter(Boolean).map(line => JSON.parse(line)); }
70
- }, 'Download');
71
- }
72
-
73
- async delete(name) {
74
- return this._execute(async () => {
75
- this._requireKey();
76
- const streamName = name.endsWith('.btx') ? name : `${name}.stream.btx`;
77
- const { data: { session } } = await this.supabase.auth.getSession();
78
- const res = await fetch(`${this.workerUrl}?action=delete&key=${this.apiKey}&file=${encodeURIComponent(streamName)}`, {
79
- method: 'DELETE',
80
- headers: { 'Authorization': `Bearer ${session?.access_token || ''}` }
81
- });
82
- if (!res.ok) throw new Error(`Status ${res.status}`);
83
- return true;
84
- }, 'Delete');
85
- }
86
-
87
- /**
88
- * ByteX X-RAY v2.5 (Self-Healing Diagnostic)
89
- */
90
- async xray() {
91
- const report = { timestamp: new Date().toISOString(), sdk_version: '5.2.0', checks: {}, advice: [] };
92
- const { data: { session } } = await this.supabase.auth.getSession();
93
-
94
- // 1. Connectivity Check
95
- const start = Date.now();
96
- try {
97
- const res = await fetch(`${this.workerUrl}?action=list&key=${this.apiKey}`);
98
- report.checks.connectivity = res.ok ? 'OK' : 'ERROR';
99
- report.latency = Date.now() - start;
100
- } catch (e) {
101
- report.checks.connectivity = 'OFFLINE';
102
- report.advice.push('ByteX Cloud is unreachable. Check your internet.');
103
- }
104
-
105
- // 2. API Key Check
106
- if (!this.apiKey) {
107
- report.checks.api_key = 'MISSING';
108
- report.advice.push('No API Key detected. Please provide an apiKey in the constructor.');
109
- } else { report.checks.api_key = 'OK'; }
110
-
111
- // 3. Auth Check
112
- report.checks.auth = session ? 'AUTHENTICATED' : 'GUEST';
113
- if (!session) report.advice.push('User is not logged in. Some operations may fail.');
114
-
115
- // 4. Platform Audit (Mobile/Web)
116
- if (!this.config.storage && typeof navigator !== 'undefined') {
117
- report.advice.push('Storage engine (AsyncStorage) is missing. Sessions will not persist.');
118
- }
119
-
120
- return report;
121
- }
122
-
123
- _requireKey() { if (!this.apiKey) throw new Error('API Key required!'); }
124
-
125
- /**
126
- * Copy a file within the same project under a new name.
127
- */
128
- async copy(sourceName, destName) {
129
- return this._execute(async () => {
130
- this._requireKey();
131
- const src = sourceName.endsWith('.btx') ? sourceName : `${sourceName}.stream.btx`;
132
- const { data: { session } } = await this.supabase.auth.getSession();
133
- const res = await fetch(`${this.workerUrl}?action=view&key=${this.apiKey}&file=${encodeURIComponent(src)}&_cb=${Date.now()}`, {
134
- headers: { 'Authorization': `Bearer ${session?.access_token || ''}` }
135
- });
136
- if (!res.ok) throw new Error(`File not found: ${sourceName}`);
137
- const data = await res.arrayBuffer();
138
- const fd = new FormData();
139
- fd.append('file', new Blob([data]), destName);
140
- const upRes = await fetch(`${this.workerUrl}?action=upload&key=${this.apiKey}`, { method: 'POST', body: fd });
141
- if (!upRes.ok) throw new Error(await upRes.text());
142
- return { source: sourceName, dest: destName };
143
- }, 'Copy');
144
- }
145
-
146
- /**
147
- * Move a file to a different project (API key).
148
- * @param {string} name - File name to move
149
- * @param {string} destApiKey - Destination project's API key
150
- */
151
- async move(name, destApiKey) {
152
- return this._execute(async () => {
153
- this._requireKey();
154
- const src = name.endsWith('.btx') ? name : `${name}.stream.btx`;
155
- const { data: { session } } = await this.supabase.auth.getSession();
156
- // Download from source
157
- const res = await fetch(`${this.workerUrl}?action=view&key=${this.apiKey}&file=${encodeURIComponent(src)}&_cb=${Date.now()}`, {
158
- headers: { 'Authorization': `Bearer ${session?.access_token || ''}` }
159
- });
160
- if (!res.ok) throw new Error(`File not found: ${name}`);
161
- const data = await res.arrayBuffer();
162
- // Upload to destination
163
- const fd = new FormData();
164
- fd.append('file', new Blob([data]), name);
165
- await fetch(`${this.workerUrl}?action=upload&key=${destApiKey}`, { method: 'POST', body: fd });
166
- // Delete from source
167
- await fetch(`${this.workerUrl}?action=delete&key=${this.apiKey}&file=${encodeURIComponent(src)}`, {
168
- method: 'DELETE', headers: { 'Authorization': `Bearer ${session?.access_token || ''}` }
169
- });
170
- return { moved: name, to: destApiKey };
171
- }, 'Move');
172
- }
173
-
174
- /**
175
- * Tag a file with one or more labels.
176
- * @param {string} fileName - The file to tag
177
- * @param {string[]} tags - Array of tag strings
178
- */
179
- async tag(fileName, tags) {
180
- return this._execute(async () => {
181
- this._requireKey();
182
- const existing = await this._getMeta('tags', fileName) || [];
183
- const merged = [...new Set([...existing, ...tags])];
184
- await this._setMeta('tags', fileName, merged);
185
- return { fileName, tags: merged };
186
- }, 'Tag');
187
- }
188
-
189
- async getTags(fileName) {
190
- return this._execute(async () => {
191
- this._requireKey();
192
- return await this._getMeta('tags', fileName) || [];
193
- }, 'GetTags');
194
- }
195
-
196
- async removeTag(fileName, tag) {
197
- return this._execute(async () => {
198
- this._requireKey();
199
- const existing = await this._getMeta('tags', fileName) || [];
200
- const updated = existing.filter(t => t !== tag);
201
- await this._setMeta('tags', fileName, updated);
202
- return { fileName, tags: updated };
203
- }, 'RemoveTag');
204
- }
205
-
206
- /**
207
- * Pin a file to protect it from bulk operations.
208
- */
209
- async pin(fileName) {
210
- return this._execute(async () => {
211
- this._requireKey();
212
- const existing = await this._getMeta('pins', '__global') || [];
213
- if (!existing.includes(fileName)) {
214
- await this._setMeta('pins', '__global', [...existing, fileName]);
215
- }
216
- return { pinned: fileName };
217
- }, 'Pin');
218
- }
219
-
220
- async unpin(fileName) {
221
- return this._execute(async () => {
222
- this._requireKey();
223
- const existing = await this._getMeta('pins', '__global') || [];
224
- await this._setMeta('pins', '__global', existing.filter(f => f !== fileName));
225
- return { unpinned: fileName };
226
- }, 'Unpin');
227
- }
228
-
229
- async getPins() {
230
- return this._execute(async () => {
231
- this._requireKey();
232
- return await this._getMeta('pins', '__global') || [];
233
- }, 'GetPins');
234
- }
235
-
236
- /**
237
- * Save a versioned snapshot of a file.
238
- */
239
- async saveVersion(name) {
240
- return this._execute(async () => {
241
- this._requireKey();
242
- const ts = new Date().toISOString().replace(/[:.]/g, '-').substring(0, 19);
243
- return await this.copy(name, `__version__${ts}__${name}`);
244
- }, 'SaveVersion');
245
- }
246
-
247
- /**
248
- * List all saved versions of a file.
249
- */
250
- async listVersions(name) {
251
- return this._execute(async () => {
252
- this._requireKey();
253
- const { data: { session } } = await this.supabase.auth.getSession();
254
- const res = await fetch(`${this.workerUrl}?action=list&key=${this.apiKey}`, {
255
- headers: { 'Authorization': `Bearer ${session?.access_token || ''}` }
256
- });
257
- const text = await res.text();
258
- const files = text.trim().split('\n').filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
259
- return files.filter(f => (f.file_name || '').startsWith('__version__') && (f.file_name || '').endsWith(name));
260
- }, 'ListVersions');
261
- }
262
-
263
- /**
264
- * Register a webhook URL to receive event notifications.
265
- * Note: webhooks are stored locally/in Supabase. Your server must listen at the endpoint.
266
- */
267
- async addWebhook(url, events = ['upload', 'delete']) {
268
- return this._execute(async () => {
269
- this._requireKey();
270
- const existing = await this._getMeta('webhooks', '__global') || [];
271
- const updated = [...existing.filter(w => w.url !== url), { url, events, createdAt: new Date().toISOString() }];
272
- await this._setMeta('webhooks', '__global', updated);
273
- return { url, events };
274
- }, 'AddWebhook');
275
- }
276
-
277
- async getWebhooks() {
278
- return this._execute(async () => {
279
- this._requireKey();
280
- return await this._getMeta('webhooks', '__global') || [];
281
- }, 'GetWebhooks');
282
- }
283
-
284
- async removeWebhook(url) {
285
- return this._execute(async () => {
286
- this._requireKey();
287
- const existing = await this._getMeta('webhooks', '__global') || [];
288
- await this._setMeta('webhooks', '__global', existing.filter(w => w.url !== url));
289
- return { removed: url };
290
- }, 'RemoveWebhook');
291
- }
292
-
293
- // Internal metadata helper using Supabase
294
- async _getMeta(type, key) {
295
- try {
296
- const { data } = await this.supabase.from('bytex_metadata').select('value').eq('api_key', this.apiKey).eq('meta_type', type).eq('meta_key', key).single();
297
- return data?.value || null;
298
- } catch { return null; }
299
- }
300
-
301
- async _setMeta(type, key, value) {
302
- await this.supabase.from('bytex_metadata').upsert({ api_key: this.apiKey, meta_type: type, meta_key: key, value }, { onConflict: 'api_key,meta_type,meta_key' });
303
- }
304
- }
305
-
306
- /**
307
- * ByteX AI (BYOM) v1.1
308
- * Bring Your Own Model — connect your own AI API keys
309
- *
310
- * Usage:
311
- * const ai = new BytexAI({
312
- * openai: 'sk-...',
313
- * custom: { key: '...', endpoint: 'https://api.groq.com/openai/v1' }
314
- * });
315
- */
316
- export class BytexAI {
317
- constructor(keys = {}) {
318
- this.keys = keys;
319
- }
320
-
321
- /**
322
- * Universal chat method.
323
- * @param {'openai'|'claude'|'gemini'|'custom'} provider - The AI provider
324
- * @param {string} model - The model name
325
- * @param {Array<{role: string, content: string}>} messages - Chat messages
326
- * @param {object} options - Optional params
327
- * @returns {Promise<string>} - The AI reply text
328
- */
329
- async chat(provider, model, messages, options = {}) {
330
- switch (provider) {
331
- case 'openai': return this._openai(model, messages, options);
332
- case 'claude': return this._claude(model, messages, options);
333
- case 'gemini': return this._gemini(model, messages, options);
334
- case 'custom': return this._custom(model, messages, options);
335
- default: throw new Error(`[BytexAI] Unknown provider: "${provider}". Use 'openai', 'claude', 'gemini', or 'custom'.`);
336
- }
337
- }
338
-
339
- async _openai(model, messages, options) {
340
- return this._openaiCompatible('https://api.openai.com/v1', this.keys.openai, model || 'gpt-4o-mini', messages, options);
341
- }
342
-
343
- async _custom(model, messages, options) {
344
- const config = this.keys.custom || {};
345
- if (!config.key || !config.endpoint) {
346
- throw new Error('[BytexAI] Custom provider requires both "key" and "endpoint" (OpenAI-compatible).');
347
- }
348
- return this._openaiCompatible(config.endpoint, config.key, model, messages, options);
349
- }
350
-
351
- async _openaiCompatible(baseURL, key, model, messages, options) {
352
- if (!key) throw new Error(`[BytexAI] API key for ${baseURL} is missing.`);
353
- const url = baseURL.endsWith('/') ? `${baseURL}chat/completions` : `${baseURL}/chat/completions`;
354
- const res = await fetch(url, {
355
- method: 'POST',
356
- headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${key}` },
357
- body: JSON.stringify({
358
- model: model,
359
- messages,
360
- temperature: options.temperature ?? 0.7,
361
- max_tokens: options.maxTokens ?? 1024,
362
- })
363
- });
364
- if (!res.ok) throw new Error(`[BytexAI] API error (${baseURL}): ${await res.text()}`);
365
- const data = await res.json();
366
- return data.choices[0].message.content;
367
- }
368
-
369
- async _claude(model, messages, options) {
370
- if (!this.keys.claude) throw new Error('[BytexAI] Claude API key is missing. Pass it via: new BytexAI({ claude: "sk-ant-..." })');
371
- const system = messages.find(m => m.role === 'system')?.content;
372
- const chatMessages = messages.filter(m => m.role !== 'system');
373
- const res = await fetch('https://api.anthropic.com/v1/messages', {
374
- method: 'POST',
375
- headers: {
376
- 'Content-Type': 'application/json',
377
- 'x-api-key': this.keys.claude,
378
- 'anthropic-version': '2023-06-01'
379
- },
380
- body: JSON.stringify({
381
- model: model || 'claude-3-5-haiku-20241022',
382
- max_tokens: options.maxTokens ?? 1024,
383
- ...(system && { system }),
384
- messages: chatMessages
385
- })
386
- });
387
- if (!res.ok) throw new Error(`[BytexAI] Claude error: ${await res.text()}`);
388
- const data = await res.json();
389
- return data.content[0].text;
390
- }
391
-
392
- async _gemini(model, messages, options) {
393
- if (!this.keys.gemini) throw new Error('[BytexAI] Gemini API key is missing. Pass it via: new BytexAI({ gemini: "AIza..." })');
394
- const contents = messages
395
- .filter(m => m.role !== 'system')
396
- .map(m => ({ role: m.role === 'assistant' ? 'model' : 'user', parts: [{ text: m.content }] }));
397
- const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${model || 'gemini-1.5-flash'}:generateContent?key=${this.keys.gemini}`;
398
- const res = await fetch(endpoint, {
399
- method: 'POST',
400
- headers: { 'Content-Type': 'application/json' },
401
- body: JSON.stringify({ contents, generationConfig: { temperature: options.temperature ?? 0.7, maxOutputTokens: options.maxTokens ?? 1024 } })
402
- });
403
- if (!res.ok) throw new Error(`[BytexAI] Gemini error: ${await res.text()}`);
404
- const data = await res.json();
405
- return data.candidates[0].content.parts[0].text;
406
- }
407
- }
408
-
409
- // ════════════════════════════════════════════════════════════════
410
- // ByteX REALTIME — Database Realtime (BYOC Model)
411
- // Strategy: ALWAYS uses user's own Supabase (BYOC)
412
- // Falls back to HTTP polling if no Supabase configured
413
- // Free tier: 200 concurrent connections per USER's Supabase project
414
- // ════════════════════════════════════════════════════════════════
415
- /**
416
- * BytexRealtime — Subscribe to database changes and broadcast events.
417
- *
418
- * ⚠️ IMPORTANT: Always use BYOC (user's own Supabase), NOT ByteX's central Supabase.
419
- * ByteX's Supabase has a limit of 200 concurrent connections total.
420
- * With BYOC, EACH USER gets their own 200 free concurrent connections.
421
- *
422
- * Usage (BYOC — Recommended):
423
- * const rt = new BytexRealtime({
424
- * supabaseUrl: 'https://your-project.supabase.co',
425
- * supabaseKey: 'your-anon-key'
426
- * });
427
- *
428
- * Usage (Polling fallback — no Supabase needed):
429
- * const rt = new BytexRealtime({ pollUrl: 'https://api.bytex.work/', pollInterval: 5000 });
430
- */
431
- export class BytexRealtime {
432
- constructor(config = {}) {
433
- this._channels = new Map();
434
- this._pollers = new Map();
435
- this._mode = 'idle';
436
-
437
- // Mode 1: BYOC Supabase client passed directly (legacy support)
438
- if (config && typeof config.from === 'function') {
439
- console.warn('[BytexRealtime] ⚠️ Passing ByteX\'s own Supabase client is not recommended for production. Use BYOC credentials to avoid shared connection limits.');
440
- this.client = config;
441
- this._mode = 'supabase';
442
- return;
443
- }
444
-
445
- // Mode 2: BYOC — user provides their own Supabase credentials
446
- if (config.supabaseUrl && config.supabaseKey) {
447
- this.client = createClient(config.supabaseUrl, config.supabaseKey, {
448
- realtime: { params: { eventsPerSecond: 10 } }
449
- });
450
- this._mode = 'supabase';
451
- return;
452
- }
453
-
454
- // Mode 3: Polling fallback — no Supabase required
455
- if (config.pollUrl) {
456
- this._pollUrl = config.pollUrl;
457
- this._pollInterval = config.pollInterval || 5000;
458
- this._mode = 'polling';
459
- return;
460
- }
461
-
462
- throw new Error(
463
- '[BytexRealtime] Configuration required. Options:\n' +
464
- ' 1. BYOC (recommended): { supabaseUrl, supabaseKey } — user\'s own Supabase\n' +
465
- ' 2. Polling fallback: { pollUrl, pollInterval? } — works without Supabase'
466
- );
467
- }
468
-
469
- /**
470
- * Subscribe to realtime database changes on a table (Supabase mode only).
471
- * @param {string} table - Table name (e.g. 'messages', 'orders')
472
- * @param {function} callback - Receives { event, new, old }
473
- * @param {{ event?: 'INSERT'|'UPDATE'|'DELETE'|'*', filter?: string }} options
474
- */
475
- on(table, callback, options = {}) {
476
- if (this._mode === 'polling') {
477
- return this._pollTable(table, callback, options);
478
- }
479
-
480
- if (this._mode !== 'supabase') throw new Error('[BytexRealtime] No Supabase client. Provide supabaseUrl + supabaseKey.');
481
-
482
- const event = options.event || '*';
483
- const channelName = `bytex-rt-${table}-${Date.now()}`;
484
- const channel = this.client
485
- .channel(channelName)
486
- .on('postgres_changes', {
487
- event,
488
- schema: options.schema || 'public',
489
- table,
490
- ...(options.filter && { filter: options.filter })
491
- }, (payload) => callback(payload))
492
- .subscribe((status) => {
493
- if (status === 'CHANNEL_ERROR') {
494
- console.error(`[BytexRealtime] Channel error on table "${table}". Check your Supabase config.`);
495
- }
496
- });
497
-
498
- this._channels.set(channelName, channel);
499
- return channelName;
500
- }
501
-
502
- /**
503
- * Subscribe to a broadcast channel — acts like a room/WebSocket.
504
- * @param {string} roomName - Unique room identifier
505
- * @param {function} callback - Receives { event, payload }
506
- * @returns {{ send, leave }} - Methods to send messages or leave the room
507
- */
508
- join(roomName, callback) {
509
- if (this._mode !== 'supabase') {
510
- throw new Error('[BytexRealtime] Broadcast channels require Supabase. Provide supabaseUrl + supabaseKey.');
511
- }
512
-
513
- const channel = this.client.channel(`bytex-room-${roomName}`, {
514
- config: { broadcast: { self: false } }
515
- });
516
-
517
- channel
518
- .on('broadcast', { event: '*' }, (msg) => callback(msg))
519
- .subscribe();
520
-
521
- this._channels.set(`bytex-room-${roomName}`, channel);
522
-
523
- return {
524
- /** Send a message to all members of this room. */
525
- send: (event, payload) => channel.send({ type: 'broadcast', event, payload }),
526
- /** Leave the room and clean up. */
527
- leave: () => this.off(`bytex-room-${roomName}`)
528
- };
529
- }
530
-
531
- /**
532
- * Polling fallback — polls a URL and calls callback when response changes.
533
- * Used when no Supabase is configured.
534
- * @private
535
- */
536
- _pollTable(table, callback, options) {
537
- let lastHash = null;
538
- const pollerId = `poll-${table}-${Date.now()}`;
539
-
540
- const poll = async () => {
541
- try {
542
- const url = `${this._pollUrl}?action=list&table=${table}`;
543
- const res = await fetch(url);
544
- const text = await res.text();
545
- const hash = btoa(text.substring(0, 200));
546
- if (lastHash !== null && hash !== lastHash) {
547
- callback({ event: '*', source: 'poll', data: text });
548
- }
549
- lastHash = hash;
550
- } catch (e) {
551
- console.warn(`[BytexRealtime] Poll error: ${e.message}`);
552
- }
553
- };
554
-
555
- poll();
556
- const timer = setInterval(poll, this._pollInterval);
557
- this._pollers.set(pollerId, timer);
558
- return pollerId;
559
- }
560
-
561
- /**
562
- * Check current realtime mode.
563
- * @returns {'supabase'|'polling'|'idle'}
564
- */
565
- get mode() { return this._mode; }
566
-
567
- /**
568
- * Get current active connection count (Supabase mode only).
569
- */
570
- get connectionCount() { return this._channels.size; }
571
-
572
- /** Unsubscribe from a specific channel or poller. */
573
- off(channelId) {
574
- const ch = this._channels.get(channelId);
575
- if (ch) { this.client?.removeChannel(ch); this._channels.delete(channelId); return; }
576
-
577
- const timer = this._pollers.get(channelId);
578
- if (timer) { clearInterval(timer); this._pollers.delete(channelId); }
579
- }
580
-
581
- /** Disconnect all subscriptions and clean up. */
582
- destroy() {
583
- this._channels.forEach((ch) => this.client?.removeChannel(ch));
584
- this._channels.clear();
585
- this._pollers.forEach((t) => clearInterval(t));
586
- this._pollers.clear();
587
- }
588
- }
589
-
590
-
591
- // ════════════════════════════════════════════════════════════════
592
- // ByteX CRON — Scheduled Jobs via Cloudflare Workers Cron Triggers
593
- // Strategy: BYOC — user provides their Cloudflare API token
594
- // Free tier: 3 Cron Triggers per Cloudflare account (FREE)
595
- // ════════════════════════════════════════════════════════════════
596
- /**
597
- * BytexCron — Create and manage Cloudflare Workers Cron Triggers.
598
- *
599
- * Requires BYOC (user's Cloudflare account):
600
- * const cron = new BytexCron({ cfToken: '...', cfAccountId: '...', workerName: 'my-worker' });
601
- */
602
- export class BytexCron {
603
- constructor({ cfToken, cfAccountId, workerName } = {}) {
604
- if (!cfToken || !cfAccountId || !workerName)
605
- throw new Error('[BytexCron] Required: { cfToken, cfAccountId, workerName } — Use BYOC config from bytex dashboard.');
606
- this.token = cfToken;
607
- this.accountId = cfAccountId;
608
- this.workerName = workerName;
609
- this.base = `https://api.cloudflare.com/client/v4/accounts/${cfAccountId}`;
610
- }
611
-
612
- /** List all existing cron triggers for the worker. */
613
- async list() {
614
- const res = await fetch(`${this.base}/workers/scripts/${this.workerName}/schedules`, {
615
- headers: { 'Authorization': `Bearer ${this.token}` }
616
- });
617
- const data = await res.json();
618
- if (!data.success) throw new Error(`[BytexCron] ${JSON.stringify(data.errors)}`);
619
- return data.result?.schedules || [];
620
- }
621
-
622
- /**
623
- * Add a new cron trigger (max 3 in free tier).
624
- * @param {string} cron - Cron expression (e.g. '0 0 * * *' = daily at midnight)
625
- */
626
- async add(cron) {
627
- const existing = await this.list();
628
- const schedules = [...existing.map(s => ({ cron: s.cron })), { cron }];
629
- const res = await fetch(`${this.base}/workers/scripts/${this.workerName}/schedules`, {
630
- method: 'PUT',
631
- headers: { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/json' },
632
- body: JSON.stringify(schedules)
633
- });
634
- const data = await res.json();
635
- if (!data.success) throw new Error(`[BytexCron] ${JSON.stringify(data.errors)}`);
636
- return data.result;
637
- }
638
-
639
- /**
640
- * Remove a cron trigger.
641
- * @param {string} cron - The exact cron string to remove
642
- */
643
- async remove(cron) {
644
- const existing = await this.list();
645
- const schedules = existing.filter(s => s.cron !== cron).map(s => ({ cron: s.cron }));
646
- const res = await fetch(`${this.base}/workers/scripts/${this.workerName}/schedules`, {
647
- method: 'PUT',
648
- headers: { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/json' },
649
- body: JSON.stringify(schedules)
650
- });
651
- const data = await res.json();
652
- if (!data.success) throw new Error(`[BytexCron] ${JSON.stringify(data.errors)}`);
653
- return data.result;
654
- }
655
- }
656
-
657
- // ════════════════════════════════════════════════════════════════
658
- // ByteX QUEUE — Message Queue via Cloudflare Queues
659
- // Strategy: BYOC — user provides their Cloudflare API token
660
- // Free tier: 1,000,000 messages/month per account (FREE)
661
- // ════════════════════════════════════════════════════════════════
662
- /**
663
- * BytexQueue — Create and publish to Cloudflare Queues.
664
- *
665
- * Requires BYOC (user's Cloudflare account):
666
- * const queue = new BytexQueue({ cfToken: '...', cfAccountId: '...' });
667
- */
668
- export class BytexQueue {
669
- constructor({ cfToken, cfAccountId } = {}) {
670
- if (!cfToken || !cfAccountId)
671
- throw new Error('[BytexQueue] Required: { cfToken, cfAccountId } — Use BYOC config from bytex dashboard.');
672
- this.token = cfToken;
673
- this.accountId = cfAccountId;
674
- this.base = `https://api.cloudflare.com/client/v4/accounts/${cfAccountId}/queues`;
675
- }
676
-
677
- /** List all existing queues. */
678
- async list() {
679
- const res = await fetch(this.base, { headers: { 'Authorization': `Bearer ${this.token}` } });
680
- const data = await res.json();
681
- if (!data.success) throw new Error(`[BytexQueue] ${JSON.stringify(data.errors)}`);
682
- return data.result || [];
683
- }
684
-
685
- /**
686
- * Create a new queue.
687
- * @param {string} name - Queue name (lowercase, hyphens only)
688
- */
689
- async create(name) {
690
- const res = await fetch(this.base, {
691
- method: 'POST',
692
- headers: { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/json' },
693
- body: JSON.stringify({ queue_name: name })
694
- });
695
- const data = await res.json();
696
- if (!data.success) throw new Error(`[BytexQueue] ${JSON.stringify(data.errors)}`);
697
- return data.result;
698
- }
699
-
700
- /**
701
- * Delete a queue.
702
- * @param {string} name - Queue name
703
- */
704
- async delete(name) {
705
- const res = await fetch(`${this.base}/${name}`, {
706
- method: 'DELETE',
707
- headers: { 'Authorization': `Bearer ${this.token}` }
708
- });
709
- const data = await res.json();
710
- if (!data.success) throw new Error(`[BytexQueue] ${JSON.stringify(data.errors)}`);
711
- return true;
712
- }
713
-
714
- /**
715
- * Publish a message to a queue.
716
- * @param {string} queueName - Target queue
717
- * @param {object|string} body - Message content
718
- * @param {object} options - { delaySeconds? }
719
- */
720
- async publish(queueName, body, options = {}) {
721
- const message = { body: typeof body === 'string' ? body : JSON.stringify(body) };
722
- if (options.delaySeconds) message.delay_seconds = options.delaySeconds;
723
- const res = await fetch(`${this.base}/${queueName}/messages`, {
724
- method: 'POST',
725
- headers: { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/json' },
726
- body: JSON.stringify({ messages: [message] })
727
- });
728
- const data = await res.json();
729
- if (!data.success) throw new Error(`[BytexQueue] ${JSON.stringify(data.errors)}`);
730
- return data.result;
731
- }
732
-
733
- /**
734
- * Publish multiple messages in a single batch (max 100).
735
- * @param {string} queueName - Target queue
736
- * @param {Array<object|string>} items - Array of message bodies
737
- */
738
- async publishBatch(queueName, items) {
739
- const messages = items.map(body => ({ body: typeof body === 'string' ? body : JSON.stringify(body) }));
740
- const res = await fetch(`${this.base}/${queueName}/messages`, {
741
- method: 'POST',
742
- headers: { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/json' },
743
- body: JSON.stringify({ messages })
744
- });
745
- const data = await res.json();
746
- if (!data.success) throw new Error(`[BytexQueue] ${JSON.stringify(data.errors)}`);
747
- return data.result;
748
- }
749
- }
750
-
751
- // ════════════════════════════════════════════════════════════════
752
- // ByteX PROXY — Reverse Proxy via Cloudflare Workers
753
- // Strategy: Uses ByteX's Cloudflare (no BYOC needed for basic use)
754
- // Free tier: 100,000 requests/day (FREE)
755
- // ════════════════════════════════════════════════════════════════
756
- /**
757
- * BytexProxy — Deploy and manage Cloudflare Worker reverse proxies.
758
- *
759
- * Usage:
760
- * // Use ByteX's proxy endpoint (no config needed):
761
- * const url = BytexProxy.buildUrl('https://api.target.com/endpoint', { headers: {...} });
762
- *
763
- * // Or deploy your own proxy Worker (BYOC):
764
- * const proxy = new BytexProxy({ cfToken: '...', cfAccountId: '...' });
765
- * await proxy.deploy('my-proxy', 'https://api.target.com');
766
- */
767
- export class BytexProxy {
768
- constructor({ cfToken, cfAccountId } = {}) {
769
- this.token = cfToken;
770
- this.accountId = cfAccountId;
771
- }
772
-
773
- /**
774
- * Build a proxied URL via ByteX's own proxy layer.
775
- * Useful for CORS bypass and header injection.
776
- * @param {string} targetUrl - The destination URL to proxy
777
- * @param {{ headers?: object }} options
778
- */
779
- static buildUrl(targetUrl, options = {}) {
780
- const encoded = encodeURIComponent(targetUrl);
781
- const base = 'https://api.bytex.work/?action=proxy&target=';
782
- return `${base}${encoded}`;
783
- }
784
-
785
- /**
786
- * Deploy a Cloudflare Worker that proxies to a target origin (BYOC).
787
- * @param {string} workerName - Unique name for this proxy worker
788
- * @param {string} targetOrigin - Base URL of the backend (e.g. 'https://my-api.com')
789
- * @param {{ injectHeaders?: object, stripHeaders?: string[] }} options
790
- */
791
- async deploy(workerName, targetOrigin, options = {}) {
792
- if (!this.token || !this.accountId)
793
- throw new Error('[BytexProxy] BYOC required for deploy. Pass { cfToken, cfAccountId }.');
794
-
795
- const injectHeaders = options.injectHeaders
796
- ? Object.entries(options.injectHeaders).map(([k, v]) => `req.headers.set('${k}', '${v}');`).join('\n ')
797
- : '';
798
- const stripHeaders = (options.stripHeaders || [])
799
- .map(h => `req.headers.delete('${h}');`).join('\n ');
800
-
801
- const workerScript = `
802
- export default {
803
- async fetch(request) {
804
- const url = new URL(request.url);
805
- const target = new URL('${targetOrigin}' + url.pathname + url.search);
806
- const req = new Request(target, request);
807
- ${injectHeaders}
808
- ${stripHeaders}
809
- const response = await fetch(req);
810
- const res = new Response(response.body, response);
811
- res.headers.set('Access-Control-Allow-Origin', '*');
812
- return res;
813
- }
814
- }`;
815
-
816
- const fd = new FormData();
817
- fd.append('metadata', JSON.stringify({ main_module: 'worker.js', compatibility_date: '2024-01-01' }));
818
- fd.append('worker.js', new Blob([workerScript], { type: 'application/javascript+module' }), 'worker.js');
819
-
820
- const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${this.accountId}/workers/scripts/${workerName}`, {
821
- method: 'PUT',
822
- headers: { 'Authorization': `Bearer ${this.token}` },
823
- body: fd
824
- });
825
- const data = await res.json();
826
- if (!data.success) throw new Error(`[BytexProxy] ${JSON.stringify(data.errors)}`);
827
- return { workerName, url: `https://${workerName}.workers.dev`, target: targetOrigin };
828
- }
829
- }
830
-
831
- // ════════════════════════════════════════════════════════════════
832
- // ByteX MQTT — IoT Messaging via user's MQTT Broker
833
- // Strategy: BYOC — user provides their broker (HiveMQ/EMQX/any)
834
- // Free tier: HiveMQ Cloud free (10 devices), EMQX Serverless (1M msg/mo)
835
- // ════════════════════════════════════════════════════════════════
836
- /**
837
- * BytexMQTT — Lightweight MQTT client wrapper (BYOC).
838
- *
839
- * Requires the 'mqtt' package: npm install mqtt
840
- * Requires user's own MQTT broker (HiveMQ, EMQX, Mosquitto, etc.)
841
- *
842
- * Usage:
843
- * const mq = new BytexMQTT({
844
- * brokerUrl: 'mqtts://your-cluster.hivemq.cloud:8883',
845
- * username: 'user', password: 'pass'
846
- * });
847
- * await mq.connect();
848
- * mq.subscribe('bytex/files/#', (topic, msg) => console.log(topic, msg));
849
- * mq.publish('bytex/files/new', { name: 'photo.jpg' });
850
- */
851
- export class BytexMQTT {
852
- constructor({ brokerUrl, username, password, clientId } = {}) {
853
- if (!brokerUrl)
854
- throw new Error('[BytexMQTT] Required: { brokerUrl } — Get free broker at hivemq.com or emqx.com (BYOC).');
855
- this.brokerUrl = brokerUrl;
856
- this.options = {
857
- username, password,
858
- clientId: clientId || `bytex-${Math.random().toString(36).substring(2, 9)}`,
859
- clean: true,
860
- reconnectPeriod: 3000,
861
- connectTimeout: 10000,
862
- };
863
- this.client = null;
864
- this._handlers = new Map();
865
- }
866
-
867
- /**
868
- * Connect to the MQTT broker.
869
- * @returns {Promise<void>}
870
- */
871
- async connect() {
872
- let mqtt;
873
- try { mqtt = (await import('mqtt')).default; }
874
- catch { throw new Error('[BytexMQTT] Install the mqtt package first: npm install mqtt'); }
875
-
876
- return new Promise((resolve, reject) => {
877
- this.client = mqtt.connect(this.brokerUrl, this.options);
878
- this.client.on('connect', () => resolve());
879
- this.client.on('error', (err) => reject(new Error(`[BytexMQTT] Connection failed: ${err.message}`)));
880
- this.client.on('message', (topic, buf) => {
881
- const msg = buf.toString();
882
- let parsed; try { parsed = JSON.parse(msg); } catch { parsed = msg; }
883
- this._handlers.forEach((fn, pattern) => {
884
- if (this._topicMatch(pattern, topic)) fn(topic, parsed);
885
- });
886
- });
887
- });
888
- }
889
-
890
- /**
891
- * Publish a message to a topic.
892
- * @param {string} topic
893
- * @param {object|string} payload
894
- * @param {{ qos?: 0|1|2, retain?: boolean }} options
895
- */
896
- publish(topic, payload, options = {}) {
897
- if (!this.client) throw new Error('[BytexMQTT] Not connected. Call connect() first.');
898
- const msg = typeof payload === 'string' ? payload : JSON.stringify(payload);
899
- this.client.publish(topic, msg, { qos: options.qos ?? 1, retain: options.retain ?? false });
900
- }
901
-
902
- /**
903
- * Subscribe to a topic or wildcard pattern.
904
- * @param {string} topic - Supports MQTT wildcards: '#' (multi-level), '+' (single-level)
905
- * @param {function} callback - (topic, parsedPayload) => void
906
- * @param {{ qos?: 0|1|2 }} options
907
- */
908
- subscribe(topic, callback, options = {}) {
909
- if (!this.client) throw new Error('[BytexMQTT] Not connected. Call connect() first.');
910
- this.client.subscribe(topic, { qos: options.qos ?? 1 });
911
- this._handlers.set(topic, callback);
912
- }
913
-
914
- /** Unsubscribe from a topic. */
915
- unsubscribe(topic) {
916
- if (this.client) this.client.unsubscribe(topic);
917
- this._handlers.delete(topic);
918
- }
919
-
920
- /** Gracefully disconnect from the broker. */
921
- disconnect() {
922
- if (this.client) { this.client.end(); this.client = null; }
923
- }
924
-
925
- _topicMatch(pattern, topic) {
926
- const p = pattern.replace(/\+/g, '[^/]+').replace(/#$/, '.*');
927
- return new RegExp(`^${p}$`).test(topic);
928
- }
929
- }
930
-
package/postinstall.js DELETED
@@ -1,26 +0,0 @@
1
- import chalk from 'chalk';
2
-
3
- console.log('');
4
- console.log(chalk.blue.bold('========================================='));
5
- console.log(chalk.cyan.bold(' 🚀 Successfully installed ByteX SDK!'));
6
- console.log(chalk.blue.bold('========================================='));
7
- console.log('');
8
- console.log(chalk.white('Get started by importing the SDK into your project:'));
9
- console.log('');
10
- console.log(chalk.gray(' // 1. Initialize ByteX'));
11
- console.log(chalk.green(" import { BytexCloud } from 'bytex-sdk';"));
12
- console.log(chalk.green(" const bytex = new BytexCloud();"));
13
- console.log('');
14
- console.log(chalk.gray(' // 2. Login & Generate/Select API Key directly in code'));
15
- console.log(chalk.green(" await bytex.login('your@email.com', 'password');"));
16
- console.log(chalk.green(" const myKey = await bytex.createKey('My Web App');"));
17
- console.log(chalk.gray(' // (The active API Key is now set automatically!)'));
18
- console.log('');
19
- console.log(chalk.gray(' // 3. Upload a file'));
20
- console.log(chalk.green(" await bytex.upload('document.pdf', fileData);"));
21
- console.log('');
22
- console.log(chalk.white('Want to do this via terminal instead? Try the CLI:'));
23
- console.log(chalk.cyan(' npx bytex-cli init'));
24
- console.log('');
25
- console.log(chalk.gray('For full SDK documentation, visit: https://bytex.work/docs'));
26
- console.log('');