bytex-sdk 1.7.6 → 1.8.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/index.js +65 -721
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -3,17 +3,7 @@ import { createClient } from '@supabase/supabase-js';
|
|
|
3
3
|
const SUPABASE_URL = 'https://vkiddclfbwmslaiyyftl.supabase.co';
|
|
4
4
|
const SUPABASE_ANON_KEY = 'sb_publishable_hXMlH9OmJG1_n1s-3lbXKg_6V-88Lj9';
|
|
5
5
|
const WORKER_URL = 'https://api.bytex.work/';
|
|
6
|
-
const DEFAULT_ENC_KEY = 'btx-default-secret-key-32-chars!!';
|
|
7
|
-
const DEFAULT_IV = 'btx-fixed-iv-16b';
|
|
8
6
|
|
|
9
|
-
/**
|
|
10
|
-
* ByteX Cloud SDK — Full-featured client for the ByteX Storage Platform.
|
|
11
|
-
* Supports upload, download, streaming, encryption, bulk ops, and more.
|
|
12
|
-
*
|
|
13
|
-
* @example
|
|
14
|
-
* const bytex = new BytexCloud({ apiKey: 'BTX-USER-XXXXXXXX' });
|
|
15
|
-
* await bytex.upload('photo.jpg', fileData);
|
|
16
|
-
*/
|
|
17
7
|
export class BytexCloud {
|
|
18
8
|
constructor(config = {}) {
|
|
19
9
|
this.apiKey = config.apiKey || null;
|
|
@@ -24,7 +14,6 @@ export class BytexCloud {
|
|
|
24
14
|
const url = config.supabaseUrl || SUPABASE_URL;
|
|
25
15
|
const key = config.supabaseKey || SUPABASE_ANON_KEY;
|
|
26
16
|
|
|
27
|
-
// Add custom storage support for React Native
|
|
28
17
|
const supabaseConfig = {
|
|
29
18
|
auth: {
|
|
30
19
|
persistSession: true,
|
|
@@ -37,775 +26,130 @@ export class BytexCloud {
|
|
|
37
26
|
}
|
|
38
27
|
|
|
39
28
|
this.supabase = createClient(url, key, supabaseConfig);
|
|
40
|
-
} else if (this.provider === 'firebase') {
|
|
41
|
-
this.fbProjectId = config.fbProjectId;
|
|
42
|
-
this.fbApiKey = config.fbApiKey;
|
|
43
29
|
}
|
|
44
|
-
|
|
45
30
|
this.user = null;
|
|
46
31
|
this._listeners = {};
|
|
47
|
-
this._middlewares = [];
|
|
48
|
-
this._projectScope = 'production';
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Dynamically update infrastructure settings (BYOC).
|
|
53
|
-
* @param {object} config - { supabaseUrl, supabaseKey, workerUrl, dbProvider }
|
|
54
|
-
*/
|
|
55
|
-
configure(config = {}) {
|
|
56
|
-
if (config.workerUrl) this.workerUrl = config.workerUrl;
|
|
57
|
-
if (config.dbProvider) this.provider = config.dbProvider;
|
|
58
|
-
|
|
59
|
-
if (this.provider === 'supabase' && (config.supabaseUrl || config.supabaseKey)) {
|
|
60
|
-
const url = config.supabaseUrl || this.supabase.supabaseUrl;
|
|
61
|
-
const key = config.supabaseKey || this.supabase.supabaseKey;
|
|
62
|
-
this.supabase = createClient(url, key);
|
|
63
|
-
}
|
|
64
|
-
console.log('[ByteX SDK] Configuration updated.');
|
|
65
32
|
}
|
|
66
33
|
|
|
67
|
-
// ─────────────────────────────────────────────
|
|
68
|
-
// SECTION 1: AUTHENTICATION
|
|
69
|
-
// ─────────────────────────────────────────────
|
|
70
|
-
|
|
71
34
|
async login(email, password) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
});
|
|
78
|
-
const data = await res.json();
|
|
79
|
-
if (data.error) throw new Error(`Login Failed: ${data.error.message}`);
|
|
80
|
-
this.user = { id: data.localId, email: data.email };
|
|
81
|
-
this.session = data.idToken;
|
|
82
|
-
this._emit('login', this.user);
|
|
83
|
-
return this.user;
|
|
84
|
-
} else {
|
|
85
|
-
const { data, error } = await this.supabase.auth.signInWithPassword({ email, password });
|
|
86
|
-
if (error) throw new Error(`Login Failed: ${error.message}`);
|
|
87
|
-
this.user = data.user;
|
|
88
|
-
this._emit('login', this.user);
|
|
89
|
-
return this.user;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Sign out and clear the current session.
|
|
95
|
-
*/
|
|
96
|
-
async logout() {
|
|
97
|
-
await this.supabase.auth.signOut();
|
|
98
|
-
this.user = null;
|
|
99
|
-
this.apiKey = null;
|
|
100
|
-
this._emit('logout');
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Get the current user's profile from the database.
|
|
105
|
-
* @returns {object|null} Profile data
|
|
106
|
-
*/
|
|
107
|
-
async getProfile() {
|
|
108
|
-
if (!this.user) throw new Error('You must login() first.');
|
|
109
|
-
const { data, error } = await this.supabase.from('profiles').select('*').eq('id', this.user.id).single();
|
|
110
|
-
if (error) throw error;
|
|
111
|
-
return data;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// ─────────────────────────────────────────────
|
|
115
|
-
// SECTION 2: API KEY MANAGEMENT
|
|
116
|
-
// ─────────────────────────────────────────────
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Set the active API key for storage operations.
|
|
120
|
-
* @param {string} key - Your BTX-USER-XXXXXXXX key
|
|
121
|
-
*/
|
|
122
|
-
setApiKey(key) {
|
|
123
|
-
this.apiKey = key;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/**
|
|
127
|
-
* List all API keys for the logged-in user.
|
|
128
|
-
* @returns {Array<{label: string, key: string}>}
|
|
129
|
-
*/
|
|
130
|
-
async getKeys() {
|
|
131
|
-
if (!this.user) throw new Error('You must login() first.');
|
|
132
|
-
if (this.provider === 'firebase') {
|
|
133
|
-
const res = await fetch(`https://firestore.googleapis.com/v1/projects/${this.fbProjectId}/databases/(default)/documents/api_keys`);
|
|
134
|
-
const data = await res.json();
|
|
135
|
-
return (data.documents || []).map(d => ({
|
|
136
|
-
label: d.fields.key_label?.stringValue,
|
|
137
|
-
key: d.fields.api_key?.stringValue,
|
|
138
|
-
createdAt: d.createTime
|
|
139
|
-
}));
|
|
140
|
-
} else {
|
|
141
|
-
const { data, error } = await this.supabase.from('api_keys').select('*').eq('user_id', this.user.id);
|
|
142
|
-
if (error) throw error;
|
|
143
|
-
return data.map(k => ({ label: k.key_label, key: k.api_key, createdAt: k.created_at }));
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* Generate a new API key and auto-set it as active.
|
|
149
|
-
* @param {string} label - A friendly project name
|
|
150
|
-
* @returns {string} The new API key
|
|
151
|
-
*/
|
|
152
|
-
async createKey(label) {
|
|
153
|
-
if (!this.user) throw new Error('You must login() first.');
|
|
154
|
-
const newKey = `BTX-USER-${_randomId()}`;
|
|
155
|
-
if (this.provider === 'firebase') {
|
|
156
|
-
await fetch(`https://firestore.googleapis.com/v1/projects/${this.fbProjectId}/databases/(default)/documents/api_keys?documentId=${newKey}`, {
|
|
157
|
-
method: 'POST',
|
|
158
|
-
headers: { 'Content-Type': 'application/json' },
|
|
159
|
-
body: JSON.stringify({
|
|
160
|
-
fields: {
|
|
161
|
-
user_id: { stringValue: this.user.id },
|
|
162
|
-
key_label: { stringValue: label },
|
|
163
|
-
api_key: { stringValue: newKey }
|
|
164
|
-
}
|
|
165
|
-
})
|
|
166
|
-
});
|
|
167
|
-
} else {
|
|
168
|
-
const { error } = await this.supabase.from('api_keys').insert([{
|
|
169
|
-
user_id: this.user.id,
|
|
170
|
-
key_label: label,
|
|
171
|
-
api_key: newKey
|
|
172
|
-
}]);
|
|
173
|
-
if (error) throw error;
|
|
174
|
-
}
|
|
175
|
-
this.apiKey = newKey;
|
|
176
|
-
return newKey;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/**
|
|
180
|
-
* Delete a specific API key.
|
|
181
|
-
* @param {string} apiKey - The key to revoke
|
|
182
|
-
*/
|
|
183
|
-
async deleteKey(apiKey) {
|
|
184
|
-
if (!this.user) throw new Error('You must login() first.');
|
|
185
|
-
const { error } = await this.supabase.from('api_keys').delete().eq('user_id', this.user.id).eq('api_key', apiKey);
|
|
186
|
-
if (error) throw error;
|
|
187
|
-
if (this.apiKey === apiKey) this.apiKey = null;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/**
|
|
191
|
-
* Delete a project: removes the API key AND all files uploaded under it.
|
|
192
|
-
* @param {string} apiKey - The project key to destroy
|
|
193
|
-
*/
|
|
194
|
-
async deleteProject(apiKey) {
|
|
195
|
-
const files = await this.listFiles();
|
|
196
|
-
for (const file of files) {
|
|
197
|
-
try { await this._workerPost('delete', { fileName: file.file_name }); } catch (e) { /* skip */ }
|
|
198
|
-
}
|
|
199
|
-
await this.deleteKey(apiKey);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// ─────────────────────────────────────────────
|
|
203
|
-
// SECTION 3: FILE UPLOAD
|
|
204
|
-
// ─────────────────────────────────────────────
|
|
205
|
-
|
|
206
|
-
/**
|
|
207
|
-
* Set the project scope for isolation (e.g., 'development', 'staging', 'production')
|
|
208
|
-
* @param {string} scope
|
|
209
|
-
*/
|
|
210
|
-
setProjectScope(scope) {
|
|
211
|
-
this._projectScope = scope;
|
|
35
|
+
const { data, error } = await this.supabase.auth.signInWithPassword({ email, password });
|
|
36
|
+
if (error) throw new Error(`Login Failed: ${error.message}`);
|
|
37
|
+
this.user = data.user;
|
|
38
|
+
this._emit('login', this.user);
|
|
39
|
+
return data.user;
|
|
212
40
|
}
|
|
213
41
|
|
|
214
|
-
|
|
215
|
-
* Register a middleware to intercept uploads and downloads.
|
|
216
|
-
* @param {object} middleware - Object with beforeUpload / afterUpload methods.
|
|
217
|
-
*/
|
|
218
|
-
use(middleware) {
|
|
219
|
-
this._middlewares.push(middleware);
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* Purge the global CDN cache for a specific file.
|
|
224
|
-
* @param {string} fileName
|
|
225
|
-
*/
|
|
226
|
-
async purgeCache(fileName) {
|
|
227
|
-
this._requireKey();
|
|
228
|
-
const res = await fetch(`${this.workerUrl}?action=purge&key=${this.apiKey}`, {
|
|
229
|
-
method: 'POST',
|
|
230
|
-
headers: { 'Content-Type': 'application/json' },
|
|
231
|
-
body: JSON.stringify({ fileName })
|
|
232
|
-
});
|
|
233
|
-
if (!res.ok) throw new Error('Failed to purge CDN cache');
|
|
234
|
-
return await res.json();
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/**
|
|
238
|
-
* Upload a file with default encryption (AES-CTR).
|
|
239
|
-
* @param {string} name - Filename (e.g. 'video.mp4')
|
|
240
|
-
* @param {Blob|ArrayBuffer|File} data - File content
|
|
241
|
-
* @param {object} [options] - Optional: { thumbnail: Blob, title: string }
|
|
242
|
-
* @returns {object} { success: boolean }
|
|
243
|
-
*/
|
|
244
|
-
async upload(name, data, options = {}) {
|
|
245
|
-
this._requireKey();
|
|
246
|
-
|
|
247
|
-
// Execute beforeUpload Middlewares
|
|
248
|
-
let payload = { name, data, options, scope: this._projectScope };
|
|
249
|
-
for (const mw of this._middlewares) {
|
|
250
|
-
if (typeof mw.beforeUpload === 'function') {
|
|
251
|
-
payload = await mw.beforeUpload(payload) || payload;
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// Apply scope prefix if not production
|
|
256
|
-
const finalName = payload.scope !== 'production' ? `[${payload.scope}]_${payload.name}` : payload.name;
|
|
257
|
-
|
|
258
|
-
const fd = new FormData();
|
|
259
|
-
const blob = payload.data instanceof Blob ? payload.data : new Blob([payload.data]);
|
|
260
|
-
fd.append('file', blob, finalName);
|
|
261
|
-
if (options.thumbnail) {
|
|
262
|
-
const thumbBlob = options.thumbnail instanceof Blob ? options.thumbnail : new Blob([options.thumbnail]);
|
|
263
|
-
fd.append('thumbnail', thumbBlob, `thumb_${name}`);
|
|
264
|
-
}
|
|
265
|
-
if (options.title) fd.append('title', options.title);
|
|
266
|
-
if (options.password) fd.append('password', options.password);
|
|
267
|
-
|
|
268
|
-
const res = await fetch(`${this.workerUrl}?action=upload&key=${this.apiKey}`, {
|
|
269
|
-
method: 'POST',
|
|
270
|
-
body: fd
|
|
271
|
-
});
|
|
272
|
-
if (!res.ok) {
|
|
273
|
-
const errText = await res.text();
|
|
274
|
-
this._emit('error', { action: 'upload', message: errText });
|
|
275
|
-
throw new Error(`Upload failed: ${errText}`);
|
|
276
|
-
}
|
|
277
|
-
const result = await res.json();
|
|
278
|
-
this._emit('upload', { name, size: blob.size });
|
|
279
|
-
return result;
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* Pro Feature: Chunked Upload for very large files.
|
|
284
|
-
* Splits file into 5MB chunks for better reliability.
|
|
285
|
-
* @param {string} name
|
|
286
|
-
* @param {File|Blob} file
|
|
287
|
-
* @param {object} [options]
|
|
288
|
-
*/
|
|
289
|
-
async uploadLarge(name, file, options = {}) {
|
|
290
|
-
this._requireKey();
|
|
291
|
-
const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB
|
|
292
|
-
const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
|
|
293
|
-
|
|
294
|
-
console.log(`[ByteX] 🚀 Starting Chunked Upload for ${name} (${totalChunks} chunks)`);
|
|
295
|
-
|
|
296
|
-
// For now, we perform a simplified sequential upload or a single multi-part
|
|
297
|
-
// In a full TUS implementation, we would send chunks one by one.
|
|
298
|
-
// For ByteX, we will use the standard upload but with optimized buffer handling.
|
|
299
|
-
return this.upload(name, file, options);
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
/**
|
|
304
|
-
* Upload a file WITHOUT encryption (raw/plain).
|
|
305
|
-
* Note: This sends the file directly without AES-CTR processing.
|
|
306
|
-
* The file will still be committed to your storage node as-is.
|
|
307
|
-
* @param {string} name
|
|
308
|
-
* @param {Blob|ArrayBuffer|File} data
|
|
309
|
-
* @returns {object}
|
|
310
|
-
*/
|
|
311
|
-
async uploadRaw(name, data) {
|
|
42
|
+
async upload(name, data) {
|
|
312
43
|
this._requireKey();
|
|
313
44
|
const fd = new FormData();
|
|
314
45
|
const blob = data instanceof Blob ? data : new Blob([data]);
|
|
315
46
|
fd.append('file', blob, name);
|
|
316
|
-
fd.append('raw', 'true');
|
|
317
|
-
|
|
318
|
-
const res = await fetch(`${this.workerUrl}?action=upload&key=${this.apiKey}&raw=true`, {
|
|
319
|
-
method: 'POST',
|
|
320
|
-
body: fd
|
|
321
|
-
});
|
|
322
|
-
if (!res.ok) throw new Error(`Raw upload failed: ${await res.text()}`);
|
|
323
|
-
return await res.json();
|
|
324
|
-
}
|
|
325
47
|
|
|
326
|
-
|
|
327
|
-
* Upload a file with a CUSTOM encryption key (Bring Your Own Key).
|
|
328
|
-
* @param {string} name
|
|
329
|
-
* @param {Blob|ArrayBuffer|File} data
|
|
330
|
-
* @param {string} encryptionKey - Your custom 32-char encryption key
|
|
331
|
-
* @returns {object}
|
|
332
|
-
*/
|
|
333
|
-
async uploadEncrypted(name, data, encryptionKey) {
|
|
334
|
-
this._requireKey();
|
|
335
|
-
const rawData = data instanceof Blob ? await data.arrayBuffer() : (data instanceof ArrayBuffer ? data : new Blob([data]).arrayBuffer());
|
|
336
|
-
const actualData = rawData instanceof Promise ? await rawData : rawData;
|
|
337
|
-
const encrypted = await this.encrypt(actualData, encryptionKey);
|
|
338
|
-
const fd = new FormData();
|
|
339
|
-
fd.append('file', new Blob([encrypted]), name);
|
|
340
|
-
fd.append('custom_enc', 'true');
|
|
341
|
-
|
|
342
|
-
const res = await fetch(`${this.workerUrl}?action=upload&key=${this.apiKey}&custom_enc=true`, {
|
|
48
|
+
const res = await fetch(`${this.workerUrl}?action=upload&key=${this.apiKey}`, {
|
|
343
49
|
method: 'POST',
|
|
344
50
|
body: fd
|
|
345
51
|
});
|
|
346
|
-
if (!res.ok) throw new Error(`
|
|
52
|
+
if (!res.ok) throw new Error(`Upload failed: ${await res.text()}`);
|
|
347
53
|
return await res.json();
|
|
348
54
|
}
|
|
349
55
|
|
|
350
|
-
|
|
351
|
-
// SECTION 4: FILE RETRIEVAL & STREAMING
|
|
352
|
-
// ─────────────────────────────────────────────
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* Download a file (auto-decrypts if encrypted).
|
|
356
|
-
* @param {string} name - Filename (with or without .stream.btx)
|
|
357
|
-
* @param {string} [password] - Password if the file is protected
|
|
358
|
-
* @returns {Blob} Decrypted file data
|
|
359
|
-
*/
|
|
360
|
-
async download(name, password) {
|
|
56
|
+
async downloadData(name) {
|
|
361
57
|
this._requireKey();
|
|
362
|
-
// ByteX Worker always expects .stream.btx for action=view
|
|
363
58
|
const streamName = name.endsWith('.stream.btx') ? name : `${name}.stream.btx`;
|
|
364
|
-
|
|
365
|
-
if (password) url += `&password=${encodeURIComponent(password)}`;
|
|
59
|
+
const url = `${this.workerUrl}?action=view&key=${this.apiKey}&file=${encodeURIComponent(streamName)}&_cb=${Date.now()}`;
|
|
366
60
|
|
|
367
61
|
const { data: { session } } = await this.supabase.auth.getSession();
|
|
368
62
|
const res = await fetch(url, {
|
|
369
63
|
headers: {
|
|
370
|
-
'Authorization': `Bearer ${session?.access_token || ''}
|
|
64
|
+
'Authorization': `Bearer ${session?.access_token || ''}`,
|
|
65
|
+
'Cache-Control': 'no-cache'
|
|
371
66
|
}
|
|
372
67
|
});
|
|
373
68
|
if (!res.ok) throw new Error(`Download failed: ${res.status}`);
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
*/
|
|
382
|
-
async downloadData(name) {
|
|
383
|
-
const blob = await this.download(name);
|
|
384
|
-
const text = await blob.text();
|
|
385
|
-
return JSON.parse(text);
|
|
69
|
+
const text = await res.text();
|
|
70
|
+
try {
|
|
71
|
+
return JSON.parse(text);
|
|
72
|
+
} catch (e) {
|
|
73
|
+
// Handle NDJSON
|
|
74
|
+
return text.split('\n').filter(Boolean).map(line => JSON.parse(line));
|
|
75
|
+
}
|
|
386
76
|
}
|
|
387
77
|
|
|
388
|
-
|
|
389
|
-
* Get the streaming URL for a media file (video/audio).
|
|
390
|
-
* Supports precision seeking with range requests.
|
|
391
|
-
* @param {string} name - Original filename (e.g. 'movie.mp4')
|
|
392
|
-
* @param {string} [password] - Password if the file is protected
|
|
393
|
-
* @returns {string} Full streaming URL
|
|
394
|
-
*/
|
|
395
|
-
stream(name, password) {
|
|
78
|
+
async delete(name) {
|
|
396
79
|
this._requireKey();
|
|
397
80
|
const streamName = name.endsWith('.stream.btx') ? name : `${name}.stream.btx`;
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
81
|
+
const { data: { session } } = await this.supabase.auth.getSession();
|
|
82
|
+
const res = await fetch(`${this.workerUrl}?action=delete&key=${this.apiKey}&file=${encodeURIComponent(streamName)}`, {
|
|
83
|
+
method: 'DELETE',
|
|
84
|
+
headers: {
|
|
85
|
+
'Authorization': `Bearer ${session?.access_token || ''}`
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
if (!res.ok) throw new Error(`Delete failed: ${res.status}`);
|
|
89
|
+
return { success: true };
|
|
401
90
|
}
|
|
402
91
|
|
|
403
|
-
// ─────────────────────────────────────────────
|
|
404
|
-
// SECTION 5: FILE MANAGEMENT
|
|
405
|
-
// ─────────────────────────────────────────────
|
|
406
|
-
|
|
407
|
-
/**
|
|
408
|
-
* List all uploaded files with metadata.
|
|
409
|
-
* @returns {Array<{file_name, path, title, thumbnail, size, uploaded_at}>}
|
|
410
|
-
*/
|
|
411
92
|
async listFiles() {
|
|
412
93
|
this._requireKey();
|
|
413
94
|
const res = await fetch(`${this.workerUrl}?action=list&key=${this.apiKey}&cb=${Date.now()}`);
|
|
414
95
|
if (!res.ok) throw new Error(`List failed: ${res.status}`);
|
|
415
96
|
const text = await res.text();
|
|
416
|
-
|
|
417
|
-
return text.trim().split('\n').filter(l => l.trim() !== '' && l.trim() !== '{}').map(line => {
|
|
418
|
-
try { return JSON.parse(line); } catch (e) { return null; }
|
|
419
|
-
}).filter(Boolean);
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
/**
|
|
423
|
-
* Get detailed info/metadata for a specific file.
|
|
424
|
-
* @param {string} name - The filename to look up
|
|
425
|
-
* @returns {object|null} File metadata or null
|
|
426
|
-
*/
|
|
427
|
-
async getFileInfo(name) {
|
|
428
|
-
const files = await this.listFiles();
|
|
429
|
-
const baseName = name.replace(/\.stream\.btx$/i, '').replace(/\.btx$/i, '');
|
|
430
|
-
return files.find(f => {
|
|
431
|
-
const fBase = (f.file_name || f.path || '').replace(/\.stream\.btx$/i, '').replace(/\.btx$/i, '');
|
|
432
|
-
return fBase === baseName || fBase === name;
|
|
433
|
-
}) || null;
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
/**
|
|
437
|
-
* Search files by name or title.
|
|
438
|
-
* @param {string} query - Search query (case-insensitive)
|
|
439
|
-
* @returns {Array} Matching files
|
|
440
|
-
*/
|
|
441
|
-
async search(query) {
|
|
442
|
-
const files = await this.listFiles();
|
|
443
|
-
const q = query.toLowerCase();
|
|
444
|
-
return files.filter(f =>
|
|
445
|
-
(f.file_name || '').toLowerCase().includes(q) ||
|
|
446
|
-
(f.title || '').toLowerCase().includes(q)
|
|
447
|
-
);
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
/**
|
|
451
|
-
* Delete a single file permanently.
|
|
452
|
-
* @param {string} name - Filename to delete
|
|
453
|
-
* @returns {object} { success: boolean }
|
|
454
|
-
*/
|
|
455
|
-
async delete(name) {
|
|
456
|
-
this._requireKey();
|
|
457
|
-
const streamName = name.endsWith('.stream.btx') ? name : `${name}.stream.btx`;
|
|
458
|
-
const result = await this._workerPost('delete', { fileName: streamName });
|
|
459
|
-
this._emit('delete', { name });
|
|
460
|
-
return result;
|
|
97
|
+
return text.split('\n').filter(Boolean).map(line => JSON.parse(line));
|
|
461
98
|
}
|
|
462
99
|
|
|
463
100
|
/**
|
|
464
|
-
*
|
|
465
|
-
* @returns {{ deleted: number, errors: number }}
|
|
466
|
-
*/
|
|
467
|
-
async deleteAll() {
|
|
468
|
-
const files = await this.listFiles();
|
|
469
|
-
let deleted = 0, errors = 0;
|
|
470
|
-
for (const file of files) {
|
|
471
|
-
try {
|
|
472
|
-
await this._workerPost('delete', { fileName: file.file_name || file.path });
|
|
473
|
-
deleted++;
|
|
474
|
-
} catch (e) { errors++; }
|
|
475
|
-
}
|
|
476
|
-
return { deleted, errors };
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
/**
|
|
480
|
-
* Rename a file (delete old + re-upload metadata).
|
|
481
|
-
* @param {string} oldName
|
|
482
|
-
* @param {string} newName
|
|
483
|
-
*/
|
|
484
|
-
async rename(oldName, newName) {
|
|
485
|
-
this._requireKey();
|
|
486
|
-
const fileData = await this.download(oldName);
|
|
487
|
-
await this.delete(oldName);
|
|
488
|
-
await this.upload(newName, fileData);
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
// ─────────────────────────────────────────────
|
|
492
|
-
// SECTION 6: BULK & EXPORT OPERATIONS
|
|
493
|
-
// ─────────────────────────────────────────────
|
|
494
|
-
|
|
495
|
-
/**
|
|
496
|
-
* Download ALL files and return as a map of { filename: Blob }.
|
|
497
|
-
* For ZIP export in browser, use exportZip() instead.
|
|
498
|
-
* @returns {Object<string, Blob>}
|
|
499
|
-
*/
|
|
500
|
-
async downloadAll() {
|
|
501
|
-
const files = await this.listFiles();
|
|
502
|
-
const result = {};
|
|
503
|
-
for (const file of files) {
|
|
504
|
-
try {
|
|
505
|
-
const blob = await this.download(file.file_name || file.path);
|
|
506
|
-
const cleanName = (file.file_name || file.path || 'file').replace(/\.stream\.btx$/i, '');
|
|
507
|
-
result[cleanName] = blob;
|
|
508
|
-
} catch (e) { /* skip failed downloads */ }
|
|
509
|
-
}
|
|
510
|
-
return result;
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
/**
|
|
514
|
-
* Export ALL files as a single ZIP download (browser only).
|
|
515
|
-
* Requires JSZip to be available globally or passed in options.
|
|
516
|
-
* @param {object} [options] - { JSZip: JSZipConstructor, zipName: 'bytex-export.zip' }
|
|
517
|
-
* @returns {Blob} ZIP file blob
|
|
518
|
-
*/
|
|
519
|
-
/**
|
|
520
|
-
* Export files as a single ZIP download (browser only).
|
|
521
|
-
* @param {object} [options] - { projectLabel, JSZip, zipName }
|
|
522
|
-
* @returns {Blob} ZIP file blob
|
|
101
|
+
* ByteX X-RAY: Full system diagnostic.
|
|
523
102
|
*/
|
|
524
|
-
async
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
// Filter by project label if provided
|
|
532
|
-
const filteredFiles = options.projectLabel
|
|
533
|
-
? files.filter(f => f.key_label === options.projectLabel)
|
|
534
|
-
: files;
|
|
103
|
+
async xray() {
|
|
104
|
+
console.log('[ByteX X-RAY] 🔍 Starting diagnostic scan...');
|
|
105
|
+
const report = {
|
|
106
|
+
timestamp: new Date().toISOString(),
|
|
107
|
+
sdk_version: '1.8.1',
|
|
108
|
+
checks: {}
|
|
109
|
+
};
|
|
535
110
|
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
} catch (e) { console.warn(`Failed to include ${file.file_name} in ZIP`); }
|
|
111
|
+
try {
|
|
112
|
+
this._requireKey();
|
|
113
|
+
report.checks.api_key = { status: 'OK', key: `${this.apiKey.substring(0, 8)}...` };
|
|
114
|
+
} catch (e) {
|
|
115
|
+
report.checks.api_key = { status: 'ERROR', message: e.message };
|
|
542
116
|
}
|
|
543
|
-
|
|
544
|
-
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
|
545
|
-
|
|
546
|
-
if (typeof document !== 'undefined') {
|
|
547
|
-
const a = document.createElement('a');
|
|
548
|
-
a.href = URL.createObjectURL(zipBlob);
|
|
549
|
-
a.download = options.zipName || (options.projectLabel ? `bytex-${options.projectLabel}.zip` : 'bytex-export.zip');
|
|
550
|
-
a.click();
|
|
551
|
-
URL.revokeObjectURL(a.href);
|
|
552
|
-
}
|
|
553
|
-
return zipBlob;
|
|
554
|
-
}
|
|
555
117
|
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
/**
|
|
561
|
-
* Get current storage usage and limits.
|
|
562
|
-
* @returns {{ usedBytes, limitBytes, usedGB, limitGB, percentage }}
|
|
563
|
-
*/
|
|
564
|
-
async getQuota() {
|
|
565
|
-
this._requireKey();
|
|
566
|
-
const res = await fetch(`${this.workerUrl}?action=quota`, {
|
|
567
|
-
headers: { 'x-bytex-key': this.apiKey }
|
|
568
|
-
});
|
|
569
|
-
if (!res.ok) throw new Error(`Quota check failed: ${res.status}`);
|
|
570
|
-
const data = await res.json();
|
|
571
|
-
const usedGB = (data.usedBytes / (1024 ** 3)).toFixed(2);
|
|
572
|
-
const limitGB = data.limitBytes > 0 ? (data.limitBytes / (1024 ** 3)).toFixed(0) : 'Unlimited';
|
|
573
|
-
const percentage = data.limitBytes > 0 ? ((data.usedBytes / data.limitBytes) * 100).toFixed(1) : 0;
|
|
574
|
-
|
|
575
|
-
if (percentage > 90) this._emit('quota-warn', { percentage, usedGB, limitGB });
|
|
576
|
-
|
|
577
|
-
return { ...data, usedGB, limitGB, percentage };
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
/**
|
|
581
|
-
* Get detailed analytics for the current API Key.
|
|
582
|
-
* @returns {Promise<{download_count, bandwidth_used_gb}>}
|
|
583
|
-
*/
|
|
584
|
-
async getAnalytics() {
|
|
585
|
-
this._requireKey();
|
|
586
|
-
const { data, error } = await this.supabase
|
|
587
|
-
.from('api_keys')
|
|
588
|
-
.select('download_count, bandwidth_used')
|
|
589
|
-
.eq('api_key', this.apiKey)
|
|
590
|
-
.single();
|
|
591
|
-
|
|
592
|
-
if (error) throw error;
|
|
593
|
-
return {
|
|
594
|
-
downloadCount: data.download_count || 0,
|
|
595
|
-
bandwidthUsedGB: ((data.bandwidth_used || 0) / (1024 ** 3)).toFixed(4)
|
|
118
|
+
const { data: { session } } = await this.supabase.auth.getSession();
|
|
119
|
+
report.checks.auth = {
|
|
120
|
+
status: session ? 'LOGGED_IN' : 'GUEST',
|
|
121
|
+
user: session?.user?.email || 'none'
|
|
596
122
|
};
|
|
597
|
-
}
|
|
598
|
-
|
|
599
123
|
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
async encrypt(data, key) {
|
|
611
|
-
const encoder = new TextEncoder();
|
|
612
|
-
const kb = encoder.encode(key || DEFAULT_ENC_KEY).slice(0, 32);
|
|
613
|
-
const iv = encoder.encode(DEFAULT_IV).slice(0, 16);
|
|
614
|
-
const cryptoKey = await crypto.subtle.importKey('raw', kb, 'AES-CTR', false, ['encrypt']);
|
|
615
|
-
return await crypto.subtle.encrypt({ name: 'AES-CTR', counter: iv, length: 64 }, cryptoKey, data);
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
/**
|
|
619
|
-
* Decrypt AES-CTR encrypted data.
|
|
620
|
-
* @param {ArrayBuffer} data - Encrypted data
|
|
621
|
-
* @param {string} [key] - 32-char encryption key (defaults to ByteX standard)
|
|
622
|
-
* @returns {ArrayBuffer} Decrypted data
|
|
623
|
-
*/
|
|
624
|
-
async decrypt(data, key) {
|
|
625
|
-
const encoder = new TextEncoder();
|
|
626
|
-
const kb = encoder.encode(key || DEFAULT_ENC_KEY).slice(0, 32);
|
|
627
|
-
const iv = encoder.encode(DEFAULT_IV).slice(0, 16);
|
|
628
|
-
const cryptoKey = await crypto.subtle.importKey('raw', kb, 'AES-CTR', false, ['decrypt']);
|
|
629
|
-
return await crypto.subtle.decrypt({ name: 'AES-CTR', counter: iv, length: 64 }, cryptoKey, data);
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
// ─────────────────────────────────────────────
|
|
633
|
-
// SECTION 9: SHARING
|
|
634
|
-
// ─────────────────────────────────────────────
|
|
635
|
-
|
|
636
|
-
/**
|
|
637
|
-
* Generate a public shareable URL for a file.
|
|
638
|
-
* @param {string} name - Filename to share
|
|
639
|
-
* @param {string} [password] - Optional password protection
|
|
640
|
-
* @returns {string} Public URL
|
|
641
|
-
*/
|
|
642
|
-
share(name, password) {
|
|
643
|
-
return this.stream(name, password);
|
|
644
|
-
}
|
|
124
|
+
const start = Date.now();
|
|
125
|
+
try {
|
|
126
|
+
const res = await fetch(`${this.workerUrl}?action=list&key=${this.apiKey}`);
|
|
127
|
+
report.checks.worker = {
|
|
128
|
+
status: res.ok ? 'ONLINE' : 'ERROR',
|
|
129
|
+
latency_ms: Date.now() - start
|
|
130
|
+
};
|
|
131
|
+
} catch (e) {
|
|
132
|
+
report.checks.worker = { status: 'OFFLINE', message: e.message };
|
|
133
|
+
}
|
|
645
134
|
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
* @param {string} name - Filename to share
|
|
649
|
-
* @param {string} duration - Duration string (e.g. '1h', '2d')
|
|
650
|
-
* @param {string} [password] - Optional password
|
|
651
|
-
* @returns {Promise<string>} Signed URL
|
|
652
|
-
*/
|
|
653
|
-
async shareSigned(name, duration, password) {
|
|
654
|
-
this._requireKey();
|
|
655
|
-
const streamName = name.endsWith('.stream.btx') ? name : `${name}.stream.btx`;
|
|
135
|
+
const issues = Object.values(report.checks).filter(c => c.status === 'ERROR' || c.status === 'OFFLINE');
|
|
136
|
+
report.health_score = issues.length === 0 ? 'EXCELLENT' : 'CRITICAL';
|
|
656
137
|
|
|
657
|
-
|
|
658
|
-
let ms = 3600000; // default 1h
|
|
659
|
-
if (duration.endsWith('h')) ms = parseInt(duration) * 3600000;
|
|
660
|
-
else if (duration.endsWith('d')) ms = parseInt(duration) * 86400000;
|
|
661
|
-
else if (duration.endsWith('m')) ms = parseInt(duration) * 60000;
|
|
662
|
-
|
|
663
|
-
const expires = Date.now() + ms;
|
|
664
|
-
const secret = "btx-link-signing-secret"; // Must match worker secret
|
|
665
|
-
|
|
666
|
-
// Generate HMAC signature
|
|
667
|
-
const encoder = new TextEncoder();
|
|
668
|
-
const data = encoder.encode(`${streamName}:${expires}`);
|
|
669
|
-
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
670
|
-
const signatureBuffer = await crypto.subtle.sign("HMAC", key, data);
|
|
671
|
-
const signature = Array.from(new Uint8Array(signatureBuffer)).map(b => b.toString(16).padStart(2, "0")).join("");
|
|
672
|
-
|
|
673
|
-
let url = `${this.workerUrl}?action=view&key=${this.apiKey}&file=${encodeURIComponent(streamName)}&expires=${expires}&signature=${signature}`;
|
|
674
|
-
if (password) url += `&password=${encodeURIComponent(password)}`;
|
|
675
|
-
return url;
|
|
138
|
+
return report;
|
|
676
139
|
}
|
|
677
140
|
|
|
678
|
-
// ─────────────────────────────────────────────
|
|
679
|
-
// SECTION 10: EVENT SYSTEM
|
|
680
|
-
// ─────────────────────────────────────────────
|
|
681
|
-
|
|
682
|
-
/**
|
|
683
|
-
* Listen to SDK events.
|
|
684
|
-
* Supported events: 'login', 'logout', 'upload', 'delete', 'error', 'quota-warn'
|
|
685
|
-
* @param {string} event
|
|
686
|
-
* @param {Function} callback
|
|
687
|
-
*/
|
|
688
|
-
on(event, callback) {
|
|
689
|
-
if (!this._listeners[event]) this._listeners[event] = [];
|
|
690
|
-
this._listeners[event].push(callback);
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
/**
|
|
694
|
-
* Remove an event listener.
|
|
695
|
-
* @param {string} event
|
|
696
|
-
* @param {Function} callback
|
|
697
|
-
*/
|
|
698
|
-
off(event, callback) {
|
|
699
|
-
if (!this._listeners[event]) return;
|
|
700
|
-
this._listeners[event] = this._listeners[event].filter(cb => cb !== callback);
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
// ─────────────────────────────────────────────
|
|
704
|
-
// INTERNAL HELPERS
|
|
705
|
-
// ─────────────────────────────────────────────
|
|
706
|
-
|
|
707
141
|
_requireKey() {
|
|
708
|
-
if (!this.apiKey) throw new Error('API Key required!
|
|
142
|
+
if (!this.apiKey) throw new Error('API Key required!');
|
|
709
143
|
}
|
|
710
144
|
|
|
711
145
|
_emit(event, data) {
|
|
712
146
|
if (this._listeners[event]) {
|
|
713
|
-
this._listeners[event].forEach(cb =>
|
|
147
|
+
this._listeners[event].forEach(cb => cb(data));
|
|
714
148
|
}
|
|
715
149
|
}
|
|
716
150
|
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
headers: { 'Content-Type': 'application/json' },
|
|
721
|
-
body: JSON.stringify(body)
|
|
722
|
-
});
|
|
723
|
-
if (!res.ok) {
|
|
724
|
-
const errText = await res.text();
|
|
725
|
-
this._emit('error', { action, message: errText });
|
|
726
|
-
throw new Error(`${action} failed: ${errText}`);
|
|
727
|
-
}
|
|
728
|
-
return await res.json();
|
|
729
|
-
}
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
/**
|
|
733
|
-
* BytexWeb — Manage and deploy websites to Cloudflare Pages.
|
|
734
|
-
*/
|
|
735
|
-
export class BytexWeb {
|
|
736
|
-
constructor(config = {}) {
|
|
737
|
-
this.cfToken = config.cfToken || null;
|
|
738
|
-
this.cfAccountId = config.cfAccountId || null;
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
/**
|
|
742
|
-
* Deploy a static directory to Cloudflare Pages.
|
|
743
|
-
* @param {string} projectName
|
|
744
|
-
* @param {string} directory - Path to build files
|
|
745
|
-
* @returns {Promise<object>} Deployment info
|
|
746
|
-
*/
|
|
747
|
-
async deploy(projectName, directory) {
|
|
748
|
-
if (!this.cfToken || !this.cfAccountId) throw new Error('Cloudflare credentials required.');
|
|
749
|
-
|
|
750
|
-
// 1. Create project if not exists
|
|
751
|
-
await fetch(`https://api.cloudflare.com/client/v4/accounts/${this.cfAccountId}/pages/projects`, {
|
|
752
|
-
method: 'POST',
|
|
753
|
-
headers: { 'Authorization': `Bearer ${this.cfToken}`, 'Content-Type': 'application/json' },
|
|
754
|
-
body: JSON.stringify({ name: projectName, production_branch: 'main' })
|
|
755
|
-
}).catch(() => {}); // ignore error if already exists
|
|
756
|
-
|
|
757
|
-
// 2. Deployment via direct upload requires zipping or multipart
|
|
758
|
-
// For the SDK (browser/node), we'll provide the instructions or use a helper.
|
|
759
|
-
// In the CLI, we will use a more robust method.
|
|
760
|
-
return { success: true, url: `https://${projectName}.pages.dev` };
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
/**
|
|
764
|
-
* Bind a custom domain to a Pages project.
|
|
765
|
-
* @param {string} projectName
|
|
766
|
-
* @param {string} domain
|
|
767
|
-
*/
|
|
768
|
-
async addDomain(projectName, domain) {
|
|
769
|
-
const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${this.cfAccountId}/pages/projects/${projectName}/domains`, {
|
|
770
|
-
method: 'POST',
|
|
771
|
-
headers: { 'Authorization': `Bearer ${this.cfToken}`, 'Content-Type': 'application/json' },
|
|
772
|
-
body: JSON.stringify({ name: domain })
|
|
773
|
-
});
|
|
774
|
-
return await res.json();
|
|
151
|
+
on(event, callback) {
|
|
152
|
+
if (!this._listeners[event]) this._listeners[event] = [];
|
|
153
|
+
this._listeners[event].push(callback);
|
|
775
154
|
}
|
|
776
155
|
}
|
|
777
|
-
|
|
778
|
-
export const BytexMiddlewares = {
|
|
779
|
-
/**
|
|
780
|
-
* Middleware to automatically optimize images to WebP in the browser before upload.
|
|
781
|
-
* @param {number} quality - WebP quality (0.0 to 1.0)
|
|
782
|
-
*/
|
|
783
|
-
imageOptimizer: (quality = 0.8) => ({
|
|
784
|
-
beforeUpload: async (payload) => {
|
|
785
|
-
// Only run in browser environment and if the file is an image
|
|
786
|
-
if (typeof document === 'undefined' || !payload.name.match(/\.(jpg|jpeg|png)$/i)) return payload;
|
|
787
|
-
|
|
788
|
-
try {
|
|
789
|
-
const file = payload.data;
|
|
790
|
-
const bitmap = await createImageBitmap(file);
|
|
791
|
-
const canvas = document.createElement('canvas');
|
|
792
|
-
canvas.width = bitmap.width;
|
|
793
|
-
canvas.height = bitmap.height;
|
|
794
|
-
const ctx = canvas.getContext('2d');
|
|
795
|
-
ctx.drawImage(bitmap, 0, 0);
|
|
796
|
-
|
|
797
|
-
const optimizedBlob = await new Promise(resolve => canvas.toBlob(resolve, 'image/webp', quality));
|
|
798
|
-
payload.data = optimizedBlob;
|
|
799
|
-
payload.name = payload.name.replace(/\.(jpg|jpeg|png)$/i, '.webp');
|
|
800
|
-
console.log(`[ByteX SDK] Optimized image to WebP: ${payload.name}`);
|
|
801
|
-
} catch (e) {
|
|
802
|
-
console.warn('[ByteX SDK] Image optimization failed, skipping:', e);
|
|
803
|
-
}
|
|
804
|
-
return payload;
|
|
805
|
-
}
|
|
806
|
-
})
|
|
807
|
-
};
|
|
808
|
-
|
|
809
|
-
function _randomId() {
|
|
810
|
-
return Math.random().toString(36).substring(2, 10).toUpperCase();
|
|
811
|
-
}
|