tuturuuu 0.0.1 → 0.0.2

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.
@@ -1,604 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
- import {
3
- AuthenticationError,
4
- NetworkError,
5
- NotFoundError,
6
- ValidationError,
7
- } from './errors';
8
- import { StorageClient, TuturuuuClient } from './storage';
9
- import type {
10
- AnalyticsResponse,
11
- CreateFolderResponse,
12
- DeleteResponse,
13
- ListStorageResponse,
14
- ShareResponse,
15
- UploadResponse,
16
- } from './types';
17
-
18
- // Mock fetch globally
19
- const mockFetch = vi.fn();
20
-
21
- // Helper to create mock response with proper headers
22
- const createMockResponse = (data: unknown, status = 200) => ({
23
- ok: status >= 200 && status < 300,
24
- status,
25
- headers: new Headers({ 'content-type': 'application/json' }),
26
- json: async () => data,
27
- blob: async () => (data instanceof Blob ? data : new Blob()),
28
- });
29
-
30
- describe('TuturuuuClient', () => {
31
- beforeEach(() => {
32
- vi.stubGlobal('fetch', mockFetch);
33
- mockFetch.mockClear();
34
- });
35
-
36
- afterEach(() => {
37
- vi.unstubAllGlobals();
38
- });
39
-
40
- describe('constructor', () => {
41
- it('should initialize with string API key', () => {
42
- const client = new TuturuuuClient('ttr_test_key');
43
- expect(client.apiKey).toBe('ttr_test_key');
44
- expect(client.baseUrl).toBe('https://tuturuuu.com/api/v1');
45
- expect(client.timeout).toBe(30000);
46
- });
47
-
48
- it('should initialize with config object', () => {
49
- const client = new TuturuuuClient({
50
- apiKey: 'ttr_test_key',
51
- baseUrl: 'https://custom.api.com',
52
- timeout: 60000,
53
- });
54
- expect(client.apiKey).toBe('ttr_test_key');
55
- expect(client.baseUrl).toBe('https://custom.api.com');
56
- expect(client.timeout).toBe(60000);
57
- });
58
-
59
- it('should use default values for optional config', () => {
60
- const client = new TuturuuuClient({
61
- apiKey: 'ttr_test_key',
62
- });
63
- expect(client.baseUrl).toBe('https://tuturuuu.com/api/v1');
64
- expect(client.timeout).toBe(30000);
65
- });
66
-
67
- it('should throw ValidationError for invalid API key', () => {
68
- expect(() => new TuturuuuClient('invalid_key')).toThrow(ValidationError);
69
- expect(() => new TuturuuuClient('invalid_key')).toThrow(
70
- 'Invalid API key format'
71
- );
72
- });
73
-
74
- it('should throw ValidationError for empty API key', () => {
75
- expect(() => new TuturuuuClient('')).toThrow(ValidationError);
76
- });
77
-
78
- it('should initialize storage and documents clients', () => {
79
- const client = new TuturuuuClient('ttr_test_key');
80
- expect(client.storage).toBeInstanceOf(StorageClient);
81
- expect(client.documents).toBeDefined();
82
- });
83
-
84
- it('should accept custom fetch function', () => {
85
- const customFetch = vi.fn();
86
- const client = new TuturuuuClient({
87
- apiKey: 'ttr_test_key',
88
- fetch: customFetch,
89
- });
90
- expect(client.fetch).toBe(customFetch);
91
- });
92
- });
93
-
94
- describe('request', () => {
95
- it('should make successful GET request', async () => {
96
- const mockResponse = { data: 'test' };
97
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
98
-
99
- const client = new TuturuuuClient('ttr_test_key');
100
- const result = await client.request('/test');
101
-
102
- expect(result).toEqual(mockResponse);
103
- expect(mockFetch).toHaveBeenCalledWith(
104
- 'https://tuturuuu.com/api/v1/test',
105
- expect.any(Object)
106
- );
107
-
108
- // Inspect headers from the actual call
109
- const callOptions = mockFetch.mock.calls[0]?.[1];
110
- const headers = callOptions?.headers;
111
- const authHeader =
112
- headers instanceof Headers
113
- ? headers.get('Authorization')
114
- : headers?.Authorization;
115
- expect(authHeader).toBe('Bearer ttr_test_key');
116
- });
117
-
118
- it('should make successful POST request with JSON body', async () => {
119
- const mockResponse = { data: 'test' };
120
- const body = JSON.stringify({ key: 'value' });
121
-
122
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
123
-
124
- const client = new TuturuuuClient('ttr_test_key');
125
- await client.request('/test', { method: 'POST', body });
126
-
127
- expect(mockFetch).toHaveBeenCalledWith(
128
- 'https://tuturuuu.com/api/v1/test',
129
- expect.objectContaining({
130
- method: 'POST',
131
- body,
132
- })
133
- );
134
-
135
- // Inspect headers from the actual call
136
- const callOptions = mockFetch.mock.calls[0]?.[1];
137
- const headers = callOptions?.headers;
138
- const authHeader =
139
- headers instanceof Headers
140
- ? headers.get('Authorization')
141
- : headers?.Authorization;
142
- const contentType =
143
- headers instanceof Headers
144
- ? headers.get('Content-Type')
145
- : headers?.['Content-Type'];
146
- expect(authHeader).toBe('Bearer ttr_test_key');
147
- expect(contentType).toBe('application/json');
148
- });
149
-
150
- it('should skip Content-Type for FormData', async () => {
151
- const mockResponse = { data: 'test' };
152
- const formData = new FormData();
153
-
154
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
155
-
156
- const client = new TuturuuuClient('ttr_test_key');
157
- await client.request('/test', {
158
- method: 'POST',
159
- body: formData,
160
- skipJsonContentType: true,
161
- });
162
-
163
- expect(mockFetch).toHaveBeenCalledWith(
164
- 'https://tuturuuu.com/api/v1/test',
165
- expect.objectContaining({
166
- method: 'POST',
167
- body: formData,
168
- })
169
- );
170
-
171
- // Inspect headers from the actual call
172
- const callOptions = mockFetch.mock.calls[0]?.[1];
173
- const headers = callOptions?.headers;
174
- const authHeader =
175
- headers instanceof Headers
176
- ? headers.get('Authorization')
177
- : headers?.Authorization;
178
- const contentType =
179
- headers instanceof Headers
180
- ? headers.get('Content-Type')
181
- : headers?.['Content-Type'];
182
- expect(authHeader).toBe('Bearer ttr_test_key');
183
- // Content-Type should not be set for FormData (browser sets it with boundary)
184
- // Accept both null (Headers.get) and undefined (plain object)
185
- expect(contentType == null).toBe(true);
186
- });
187
-
188
- it('should throw error for API error response', async () => {
189
- mockFetch.mockResolvedValueOnce(
190
- createMockResponse(
191
- {
192
- error: 'Unauthorized',
193
- message: 'Invalid API key',
194
- },
195
- 401
196
- )
197
- );
198
-
199
- const client = new TuturuuuClient('ttr_test_key');
200
- await expect(client.request('/test')).rejects.toThrow(
201
- AuthenticationError
202
- );
203
- });
204
-
205
- it('should throw NetworkError for non-API error response', async () => {
206
- mockFetch.mockResolvedValueOnce({
207
- ok: false,
208
- status: 500,
209
- statusText: 'Internal Server Error',
210
- headers: new Headers({ 'content-type': 'application/json' }),
211
- json: async () => ({}),
212
- });
213
-
214
- const client = new TuturuuuClient('ttr_test_key');
215
- await expect(client.request('/test')).rejects.toThrow(NetworkError);
216
- });
217
-
218
- it('should handle abort signal', async () => {
219
- const client = new TuturuuuClient({
220
- apiKey: 'ttr_test_key',
221
- timeout: 100,
222
- });
223
-
224
- // Simulate an abort error
225
- const abortError = new Error('The operation was aborted');
226
- abortError.name = 'AbortError';
227
- mockFetch.mockRejectedValueOnce(abortError);
228
-
229
- try {
230
- await client.request('/test');
231
- expect.fail('Should have thrown an error');
232
- } catch (error) {
233
- expect(error).toBeInstanceOf(NetworkError);
234
- expect((error as NetworkError).message).toMatch(/timeout/i);
235
- }
236
- });
237
-
238
- it('should propagate network errors', async () => {
239
- mockFetch.mockRejectedValueOnce(new Error('Network failure'));
240
-
241
- const client = new TuturuuuClient('ttr_test_key');
242
- await expect(client.request('/test')).rejects.toThrow('Network failure');
243
- });
244
- });
245
- });
246
-
247
- describe('StorageClient', () => {
248
- let client: TuturuuuClient;
249
-
250
- beforeEach(() => {
251
- vi.stubGlobal('fetch', mockFetch);
252
- mockFetch.mockClear();
253
- client = new TuturuuuClient('ttr_test_key');
254
- });
255
-
256
- afterEach(() => {
257
- vi.unstubAllGlobals();
258
- });
259
-
260
- describe('list', () => {
261
- it('should list files with default options', async () => {
262
- const mockApiResponse = {
263
- data: [
264
- {
265
- name: 'file.txt',
266
- id: '1',
267
- created_at: '2024-01-01',
268
- },
269
- ],
270
- pagination: { limit: 50, offset: 0, total: 1 },
271
- };
272
-
273
- const expectedResponse: ListStorageResponse = {
274
- data: [
275
- {
276
- name: 'file.txt',
277
- id: '1',
278
- createdAt: '2024-01-01',
279
- },
280
- ],
281
- pagination: { limit: 50, offset: 0, total: 1 },
282
- };
283
-
284
- mockFetch.mockResolvedValueOnce(createMockResponse(mockApiResponse));
285
-
286
- const result = await client.storage.list();
287
-
288
- expect(result).toEqual(expectedResponse);
289
- expect(mockFetch).toHaveBeenCalledWith(
290
- expect.stringContaining('/storage/list?'),
291
- expect.any(Object)
292
- );
293
- });
294
-
295
- it('should list files with all options', async () => {
296
- const mockResponse: ListStorageResponse = {
297
- data: [],
298
- pagination: { limit: 10, offset: 5, total: 0 },
299
- };
300
-
301
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
302
-
303
- await client.storage.list({
304
- path: 'documents',
305
- search: 'report',
306
- limit: 10,
307
- offset: 5,
308
- sortBy: 'created_at',
309
- sortOrder: 'desc',
310
- });
311
-
312
- expect(mockFetch).toHaveBeenCalledWith(
313
- expect.stringContaining('path=documents'),
314
- expect.any(Object)
315
- );
316
- expect(mockFetch).toHaveBeenCalledWith(
317
- expect.stringContaining('search=report'),
318
- expect.any(Object)
319
- );
320
- expect(mockFetch).toHaveBeenCalledWith(
321
- expect.stringContaining('limit=10'),
322
- expect.any(Object)
323
- );
324
- expect(mockFetch).toHaveBeenCalledWith(
325
- expect.stringContaining('offset=5'),
326
- expect.any(Object)
327
- );
328
- expect(mockFetch).toHaveBeenCalledWith(
329
- expect.stringContaining('sortBy=created_at'),
330
- expect.any(Object)
331
- );
332
- expect(mockFetch).toHaveBeenCalledWith(
333
- expect.stringContaining('sortOrder=desc'),
334
- expect.any(Object)
335
- );
336
- });
337
-
338
- it('should reject invalid options', async () => {
339
- await expect(client.storage.list({ limit: 0 })).rejects.toThrow();
340
-
341
- await expect(client.storage.list({ limit: 1001 })).rejects.toThrow();
342
-
343
- await expect(client.storage.list({ offset: -1 })).rejects.toThrow();
344
- });
345
- });
346
-
347
- describe('upload', () => {
348
- it('should upload File object', async () => {
349
- const mockResponse: UploadResponse = {
350
- message: 'Uploaded',
351
- data: { path: 'test.txt', fullPath: 'workspace/test.txt' },
352
- };
353
-
354
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
355
-
356
- const file = new File(['content'], 'test.txt');
357
- const result = await client.storage.upload(file, { path: 'documents' });
358
-
359
- expect(result).toEqual(mockResponse);
360
- expect(mockFetch).toHaveBeenCalledWith(
361
- expect.stringContaining('/storage/upload'),
362
- expect.objectContaining({
363
- method: 'POST',
364
- })
365
- );
366
- });
367
-
368
- it('should upload Blob object', async () => {
369
- const mockResponse: UploadResponse = {
370
- message: 'Uploaded',
371
- data: { path: 'file', fullPath: 'workspace/file' },
372
- };
373
-
374
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
375
-
376
- const blob = new Blob(['content']);
377
- const result = await client.storage.upload(blob);
378
-
379
- expect(result).toEqual(mockResponse);
380
- });
381
-
382
- it('should accept upsert option', async () => {
383
- const mockResponse: UploadResponse = {
384
- message: 'Uploaded',
385
- data: { path: 'test.txt', fullPath: 'workspace/test.txt' },
386
- };
387
-
388
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
389
-
390
- const file = new File(['content'], 'test.txt');
391
- await client.storage.upload(file, { upsert: true });
392
-
393
- expect(mockFetch).toHaveBeenCalled();
394
- });
395
- });
396
-
397
- describe('download', () => {
398
- it('should download file', async () => {
399
- const mockBlob = new Blob(['content']);
400
- mockFetch.mockResolvedValueOnce({
401
- ok: true,
402
- blob: async () => mockBlob,
403
- });
404
-
405
- const result = await client.storage.download('documents/file.txt');
406
-
407
- expect(result).toBe(mockBlob);
408
- expect(mockFetch).toHaveBeenCalledWith(
409
- expect.stringContaining('/storage/download/documents/file.txt'),
410
- expect.any(Object)
411
- );
412
- });
413
-
414
- it('should throw ValidationError for empty path', async () => {
415
- await expect(client.storage.download('')).rejects.toThrow(
416
- ValidationError
417
- );
418
- });
419
-
420
- it('should throw error for API error response', async () => {
421
- mockFetch.mockResolvedValueOnce(
422
- createMockResponse(
423
- {
424
- error: 'Not Found',
425
- message: 'File not found',
426
- },
427
- 404
428
- )
429
- );
430
-
431
- await expect(client.storage.download('missing.txt')).rejects.toThrow(
432
- NotFoundError
433
- );
434
- });
435
- });
436
-
437
- describe('delete', () => {
438
- it('should delete files', async () => {
439
- const mockResponse: DeleteResponse = {
440
- message: 'Deleted',
441
- data: { deleted: 2, paths: ['file1.txt', 'file2.txt'] },
442
- };
443
-
444
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
445
-
446
- const result = await client.storage.delete(['file1.txt', 'file2.txt']);
447
-
448
- expect(result).toEqual(mockResponse);
449
- expect(mockFetch).toHaveBeenCalledWith(
450
- expect.stringContaining('/storage/delete'),
451
- expect.objectContaining({
452
- method: 'DELETE',
453
- })
454
- );
455
- });
456
-
457
- it('should throw ValidationError for empty array', async () => {
458
- await expect(client.storage.delete([])).rejects.toThrow(ValidationError);
459
- });
460
-
461
- it('should throw ValidationError for non-array', async () => {
462
- await expect(
463
- client.storage.delete('string' as unknown as string[])
464
- ).rejects.toThrow(ValidationError);
465
- });
466
-
467
- it('should throw ValidationError for too many paths', async () => {
468
- const paths = Array(101).fill('file.txt');
469
- await expect(client.storage.delete(paths)).rejects.toThrow(
470
- ValidationError
471
- );
472
- });
473
- });
474
-
475
- describe('createFolder', () => {
476
- it('should create folder', async () => {
477
- const mockResponse: CreateFolderResponse = {
478
- message: 'Created',
479
- data: { path: 'reports', fullPath: 'documents/reports' },
480
- };
481
-
482
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
483
-
484
- const result = await client.storage.createFolder('documents', 'reports');
485
-
486
- expect(result).toEqual(mockResponse);
487
- expect(mockFetch).toHaveBeenCalledWith(
488
- expect.stringContaining('/storage/folders'),
489
- expect.objectContaining({
490
- method: 'POST',
491
- })
492
- );
493
- });
494
-
495
- it('should throw ValidationError for empty name', async () => {
496
- await expect(client.storage.createFolder('path', '')).rejects.toThrow(
497
- ValidationError
498
- );
499
- });
500
- });
501
-
502
- describe('share', () => {
503
- it('should generate signed URL with default expiry', async () => {
504
- const mockResponse: ShareResponse = {
505
- message: 'Shared',
506
- data: {
507
- signedUrl: 'https://example.com/signed',
508
- expiresAt: '2024-01-01',
509
- expiresIn: 3600,
510
- },
511
- };
512
-
513
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
514
-
515
- const result = await client.storage.share('file.txt');
516
-
517
- expect(result).toEqual(mockResponse);
518
- });
519
-
520
- it('should generate signed URL with custom expiry', async () => {
521
- const mockResponse: ShareResponse = {
522
- message: 'Shared',
523
- data: {
524
- signedUrl: 'https://example.com/signed',
525
- expiresAt: '2024-01-01',
526
- expiresIn: 7200,
527
- },
528
- };
529
-
530
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
531
-
532
- await client.storage.share('file.txt', { expiresIn: 7200 });
533
-
534
- expect(mockFetch).toHaveBeenCalled();
535
- });
536
-
537
- it('should throw ValidationError for empty path', async () => {
538
- await expect(client.storage.share('')).rejects.toThrow(ValidationError);
539
- });
540
-
541
- it('should reject invalid expiresIn', async () => {
542
- await expect(
543
- client.storage.share('file.txt', { expiresIn: 30 })
544
- ).rejects.toThrow();
545
-
546
- await expect(
547
- client.storage.share('file.txt', { expiresIn: 700000 })
548
- ).rejects.toThrow();
549
- });
550
- });
551
-
552
- describe('getAnalytics', () => {
553
- it('should get storage analytics', async () => {
554
- const mockResponse: AnalyticsResponse = {
555
- data: {
556
- totalSize: 1024000,
557
- fileCount: 42,
558
- storageLimit: 5000000,
559
- usagePercentage: 20.48,
560
- largestFile: {
561
- name: 'large.pdf',
562
- size: 500000,
563
- createdAt: '2024-01-01',
564
- },
565
- smallestFile: {
566
- name: 'small.txt',
567
- size: 100,
568
- createdAt: '2024-01-02',
569
- },
570
- },
571
- };
572
-
573
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
574
-
575
- const result = await client.storage.getAnalytics();
576
-
577
- expect(result).toEqual(mockResponse);
578
- expect(mockFetch).toHaveBeenCalledWith(
579
- expect.stringContaining('/storage/analytics'),
580
- expect.any(Object)
581
- );
582
- });
583
-
584
- it('should handle analytics with null files', async () => {
585
- const mockResponse: AnalyticsResponse = {
586
- data: {
587
- totalSize: 0,
588
- fileCount: 0,
589
- storageLimit: 5000000,
590
- usagePercentage: 0,
591
- largestFile: null,
592
- smallestFile: null,
593
- },
594
- };
595
-
596
- mockFetch.mockResolvedValueOnce(createMockResponse(mockResponse));
597
-
598
- const result = await client.storage.getAnalytics();
599
-
600
- expect(result.data.largestFile).toBeNull();
601
- expect(result.data.smallestFile).toBeNull();
602
- });
603
- });
604
- });