@temps-sdk/blob 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.
Files changed (2) hide show
  1. package/README.md +379 -0
  2. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,379 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/AnomalyCo/temps/main/temps-demo.gif" alt="Temps Platform" width="700" />
3
+ </p>
4
+
5
+ <h1 align="center">@temps-sdk/blob</h1>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/@temps-sdk/blob"><img src="https://img.shields.io/npm/v/@temps-sdk/blob.svg" alt="npm version" /></a>
9
+ <a href="https://www.npmjs.com/package/@temps-sdk/blob"><img src="https://img.shields.io/npm/dm/@temps-sdk/blob.svg" alt="npm downloads" /></a>
10
+ <a href="https://github.com/AnomalyCo/temps/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@temps-sdk/blob.svg" alt="license" /></a>
11
+ </p>
12
+
13
+ <p align="center">
14
+ File storage for Temps projects. Upload, download, list, copy, and delete files with a simple API -- backed by S3-compatible storage, no configuration required.
15
+ </p>
16
+
17
+ ---
18
+
19
+ ```bash
20
+ # npm
21
+ npm install @temps-sdk/blob
22
+
23
+ # bun
24
+ bun add @temps-sdk/blob
25
+
26
+ # pnpm
27
+ pnpm add @temps-sdk/blob
28
+
29
+ # yarn
30
+ yarn add @temps-sdk/blob
31
+ ```
32
+
33
+ ## Quick Start
34
+
35
+ ```typescript
36
+ import { blob } from '@temps-sdk/blob';
37
+
38
+ // Upload a file
39
+ const { url } = await blob.put('avatars/user-123.png', fileBuffer);
40
+
41
+ // Download it back
42
+ const response = await blob.download(url);
43
+ const data = await response.arrayBuffer();
44
+
45
+ // List files
46
+ const { blobs } = await blob.list({ prefix: 'avatars/' });
47
+
48
+ // Delete it
49
+ await blob.del(url);
50
+ ```
51
+
52
+ That's it. The `blob` singleton reads `TEMPS_API_URL` and `TEMPS_TOKEN` from your environment automatically.
53
+
54
+ ## Configuration
55
+
56
+ ### Environment Variables
57
+
58
+ ```bash
59
+ TEMPS_API_URL=https://your-instance.temps.dev # Your Temps API URL
60
+ TEMPS_TOKEN=your-token # API key or deployment token
61
+ TEMPS_PROJECT_ID=42 # Required for API keys, optional for deployment tokens
62
+ ```
63
+
64
+ ### Explicit Configuration
65
+
66
+ ```typescript
67
+ import { createClient } from '@temps-sdk/blob';
68
+
69
+ const storage = createClient({
70
+ apiUrl: 'https://your-instance.temps.dev',
71
+ token: 'your-token',
72
+ projectId: 42,
73
+ });
74
+ ```
75
+
76
+ > **Deployment tokens** embed the project ID, so `projectId` is optional. **API keys** require `projectId` to be set explicitly.
77
+
78
+ ## API Reference
79
+
80
+ ### `put(pathname, body, options?): Promise<BlobInfo>`
81
+
82
+ Upload a file. Content type is auto-detected from the file extension or can be set explicitly.
83
+
84
+ ```typescript
85
+ // Upload a string
86
+ await blob.put('notes/readme.txt', 'Hello, world!');
87
+
88
+ // Upload a Buffer (Node.js)
89
+ import { readFileSync } from 'fs';
90
+ const file = readFileSync('./photo.jpg');
91
+ await blob.put('photos/vacation.jpg', file);
92
+
93
+ // Upload a Uint8Array
94
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
95
+ await blob.put('data/header.bin', bytes);
96
+
97
+ // Upload a Blob (browser)
98
+ const formBlob = new Blob(['content'], { type: 'text/plain' });
99
+ await blob.put('uploads/file.txt', formBlob);
100
+
101
+ // Upload a ReadableStream
102
+ const stream = file.stream();
103
+ await blob.put('videos/clip.mp4', stream);
104
+ ```
105
+
106
+ **Accepted body types:** `string | ArrayBuffer | Uint8Array | Blob | ReadableStream<Uint8Array> | Buffer`
107
+
108
+ **Options:**
109
+
110
+ | Option | Type | Default | Description |
111
+ |--------|------|---------|-------------|
112
+ | `contentType` | `string` | Auto-detected | MIME type of the file |
113
+ | `addRandomSuffix` | `boolean` | `true` | Append a random suffix to prevent name collisions |
114
+ | `cacheControl` | `string` | - | Cache-Control header value |
115
+ | `contentEncoding` | `string` | - | Content encoding (e.g., `'gzip'`) |
116
+ | `contentDisposition` | `string` | - | Content disposition (e.g., `'attachment; filename="file.txt"'`) |
117
+
118
+ **Returns `BlobInfo`:**
119
+
120
+ ```typescript
121
+ {
122
+ url: string; // Full URL to access the file
123
+ pathname: string; // Path/name of the file
124
+ contentType: string; // MIME type
125
+ size: number; // Size in bytes
126
+ uploadedAt: string; // ISO 8601 timestamp
127
+ }
128
+ ```
129
+
130
+ ### `del(urls): Promise<void>`
131
+
132
+ Delete one or more files by URL or pathname.
133
+
134
+ ```typescript
135
+ // Delete a single file
136
+ await blob.del(fileUrl);
137
+
138
+ // Delete multiple files
139
+ await blob.del([urlA, urlB, urlC]);
140
+ ```
141
+
142
+ ### `head(url): Promise<BlobInfo>`
143
+
144
+ Get metadata about a file without downloading it.
145
+
146
+ ```typescript
147
+ const info = await blob.head(fileUrl);
148
+
149
+ console.log(info.size); // 1048576
150
+ console.log(info.contentType); // 'image/png'
151
+ console.log(info.uploadedAt); // '2025-01-15T10:30:00.000Z'
152
+ ```
153
+
154
+ ### `list(options?): Promise<ListResult>`
155
+
156
+ List files with optional prefix filtering and cursor-based pagination.
157
+
158
+ ```typescript
159
+ // List all files
160
+ const { blobs, hasMore, cursor } = await blob.list();
161
+
162
+ // List files under a prefix
163
+ const images = await blob.list({ prefix: 'images/', limit: 50 });
164
+
165
+ // Paginate through results
166
+ let page = await blob.list({ limit: 100 });
167
+ while (page.hasMore) {
168
+ for (const file of page.blobs) {
169
+ console.log(file.pathname, file.size);
170
+ }
171
+ page = await blob.list({ limit: 100, cursor: page.cursor });
172
+ }
173
+ ```
174
+
175
+ **Options:**
176
+
177
+ | Option | Type | Default | Description |
178
+ |--------|------|---------|-------------|
179
+ | `limit` | `number` | `1000` | Maximum number of results |
180
+ | `prefix` | `string` | - | Filter by path prefix (e.g., `'images/'`) |
181
+ | `cursor` | `string` | - | Pagination cursor from a previous response |
182
+
183
+ ### `download(url): Promise<Response>`
184
+
185
+ Download a file. Returns a standard `Response` object.
186
+
187
+ ```typescript
188
+ const response = await blob.download(fileUrl);
189
+
190
+ // Read as text
191
+ const text = await response.text();
192
+
193
+ // Read as binary
194
+ const buffer = await response.arrayBuffer();
195
+
196
+ // Stream to file (Node.js)
197
+ import { writeFile } from 'fs/promises';
198
+ const data = Buffer.from(await response.arrayBuffer());
199
+ await writeFile('./downloaded.png', data);
200
+ ```
201
+
202
+ ### `copy(fromUrl, toPathname): Promise<BlobInfo>`
203
+
204
+ Copy a file to a new location server-side (no re-upload needed).
205
+
206
+ ```typescript
207
+ const copy = await blob.copy(originalUrl, 'backups/photo-backup.jpg');
208
+ console.log(copy.url); // URL of the new copy
209
+ ```
210
+
211
+ ## Usage Patterns
212
+
213
+ ### User Avatar Upload (Next.js API Route)
214
+
215
+ ```typescript
216
+ import { blob } from '@temps-sdk/blob';
217
+
218
+ export async function POST(request: Request) {
219
+ const form = await request.formData();
220
+ const file = form.get('avatar') as File;
221
+
222
+ const { url } = await blob.put(
223
+ `avatars/${userId}/${file.name}`,
224
+ await file.arrayBuffer(),
225
+ {
226
+ contentType: file.type,
227
+ addRandomSuffix: false,
228
+ cacheControl: 'public, max-age=31536000, immutable',
229
+ }
230
+ );
231
+
232
+ return Response.json({ url });
233
+ }
234
+ ```
235
+
236
+ ### Backup and Restore
237
+
238
+ ```typescript
239
+ // Backup
240
+ const data = JSON.stringify(await db.export());
241
+ await blob.put(`backups/${new Date().toISOString()}.json`, data, {
242
+ contentType: 'application/json',
243
+ });
244
+
245
+ // List recent backups
246
+ const { blobs } = await blob.list({ prefix: 'backups/', limit: 10 });
247
+
248
+ // Restore latest
249
+ const latest = blobs[blobs.length - 1];
250
+ const response = await blob.download(latest.url);
251
+ const backup = await response.json();
252
+ ```
253
+
254
+ ### Static Asset Pipeline
255
+
256
+ ```typescript
257
+ import { readFileSync } from 'fs';
258
+ import { createHash } from 'crypto';
259
+
260
+ async function uploadAsset(filePath: string) {
261
+ const content = readFileSync(filePath);
262
+ const hash = createHash('md5').update(content).digest('hex').slice(0, 8);
263
+ const ext = filePath.split('.').pop();
264
+
265
+ const { url } = await blob.put(`assets/${hash}.${ext}`, content, {
266
+ addRandomSuffix: false,
267
+ cacheControl: 'public, max-age=31536000, immutable',
268
+ });
269
+
270
+ return url;
271
+ }
272
+ ```
273
+
274
+ ### Cleanup Old Files
275
+
276
+ ```typescript
277
+ async function cleanupOlderThan(prefix: string, maxAgeMs: number) {
278
+ const { blobs } = await blob.list({ prefix });
279
+ const cutoff = Date.now() - maxAgeMs;
280
+
281
+ const stale = blobs.filter(b => new Date(b.uploadedAt).getTime() < cutoff);
282
+
283
+ if (stale.length > 0) {
284
+ await blob.del(stale.map(b => b.url));
285
+ console.log(`Deleted ${stale.length} stale files`);
286
+ }
287
+ }
288
+
289
+ await cleanupOlderThan('temp/', 7 * 24 * 60 * 60 * 1000); // 7 days
290
+ ```
291
+
292
+ ## Multiple Clients
293
+
294
+ Create separate instances for different use cases:
295
+
296
+ ```typescript
297
+ import { BlobClient } from '@temps-sdk/blob';
298
+
299
+ const publicAssets = new BlobClient({ apiUrl: '...', token: '...' });
300
+ const privateData = new BlobClient({ apiUrl: '...', token: '...' });
301
+ ```
302
+
303
+ ## Error Handling
304
+
305
+ All errors are instances of `BlobError` with structured details:
306
+
307
+ ```typescript
308
+ import { blob, BlobError } from '@temps-sdk/blob';
309
+
310
+ try {
311
+ await blob.head('nonexistent.txt');
312
+ } catch (error) {
313
+ if (error instanceof BlobError) {
314
+ console.error(error.message); // 'Blob not found: nonexistent.txt'
315
+ console.error(error.code); // 'NOT_FOUND'
316
+ console.error(error.status); // 404
317
+ console.error(error.title); // RFC 7807 problem title
318
+ console.error(error.detail); // RFC 7807 problem detail
319
+ }
320
+ }
321
+ ```
322
+
323
+ **Error codes:**
324
+
325
+ | Code | Description |
326
+ |------|-------------|
327
+ | `MISSING_CONFIG` | Required environment variable or config option not set |
328
+ | `NETWORK_ERROR` | Failed to reach the Temps API |
329
+ | `NOT_FOUND` | File does not exist |
330
+ | `INVALID_INPUT` | Invalid argument (e.g., empty pathname) |
331
+
332
+ ## Auto-Detected Content Types
333
+
334
+ The SDK detects MIME types from file extensions automatically:
335
+
336
+ | Extensions | Content Type |
337
+ |---|---|
338
+ | `.jpg`, `.jpeg` | `image/jpeg` |
339
+ | `.png` | `image/png` |
340
+ | `.gif` | `image/gif` |
341
+ | `.webp` | `image/webp` |
342
+ | `.svg` | `image/svg+xml` |
343
+ | `.pdf` | `application/pdf` |
344
+ | `.json` | `application/json` |
345
+ | `.html` | `text/html` |
346
+ | `.css` | `text/css` |
347
+ | `.js` | `application/javascript` |
348
+ | `.mp4` | `video/mp4` |
349
+ | `.mp3` | `audio/mpeg` |
350
+ | `.zip` | `application/zip` |
351
+ | Others | `application/octet-stream` |
352
+
353
+ Override with the `contentType` option when auto-detection isn't sufficient.
354
+
355
+ ## TypeScript
356
+
357
+ Fully typed. All methods return typed responses:
358
+
359
+ ```typescript
360
+ import type { BlobInfo, ListResult, PutOptions } from '@temps-sdk/blob';
361
+
362
+ const info: BlobInfo = await blob.put('file.txt', 'content');
363
+ const result: ListResult = await blob.list();
364
+ ```
365
+
366
+ ## Requirements
367
+
368
+ - Node.js 18+ or Bun
369
+ - A running Temps instance
370
+
371
+ ## Related
372
+
373
+ - [`@temps-sdk/kv`](https://www.npmjs.com/package/@temps-sdk/kv) -- Key-value store
374
+ - [`@temps-sdk/react-analytics`](https://www.npmjs.com/package/@temps-sdk/react-analytics) -- React analytics, session replay, error tracking
375
+ - [`@temps-sdk/node-sdk`](https://www.npmjs.com/package/@temps-sdk/node-sdk) -- Full platform API client and server-side error tracking
376
+
377
+ ## License
378
+
379
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@temps-sdk/blob",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "Blob storage SDK for the Temps platform",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",