@bigbucket-ai/sdk 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BigBucket
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,203 @@
1
- # Temporary Holding Version
1
+ # @bigbucket-ai/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official TypeScript and JavaScript SDK for [BigBucket](https://github.com/bigbucket/bigbucket) — the high-performance, developer-friendly image storage and management platform powered by Cloudflare R2 and FastAPI.
4
+
5
+ ---
6
+
7
+ ## What is BigBucket?
8
+
9
+ BigBucket provides image infrastructure as a service. Instead of configuring S3 buckets, CORS policies, presigned URL signing algorithms, image optimization workers, and metadata databases in your application, you can integrate BigBucket in minutes.
10
+
11
+ ---
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ # npm
17
+ npm install @bigbucket-ai/sdk
18
+
19
+ # pnpm
20
+ pnpm add @bigbucket-ai/sdk
21
+
22
+ # yarn
23
+ yarn add @bigbucket-ai/sdk
24
+ ```
25
+
26
+ ---
27
+
28
+ ## Getting Started
29
+
30
+ ### 1. Account & Project Setup
31
+ 1. Register your developer account on the BigBucket platform.
32
+ 2. Create a project representing your application (e.g. "My E-Commerce Website").
33
+ 3. Generate a secret API key for your project (`bb_live_...`).
34
+
35
+ ### 2. Environment Variables
36
+ Store your API key in your server environment:
37
+ ```bash
38
+ BIGBUCKET_API_KEY=bb_live_your_secret_api_key_here
39
+ BIGBUCKET_API_URL=https://api.bigbucket.example.com/api/v1 # or http://localhost:8000/api/v1 for local dev
40
+ ```
41
+
42
+ ### 3. Client Initialization
43
+ ```typescript
44
+ import { BigBucket } from "@bigbucket-ai/sdk";
45
+
46
+ const bigbucket = new BigBucket({
47
+ apiKey: process.env.BIGBUCKET_API_KEY!,
48
+ baseUrl: process.env.BIGBUCKET_API_URL, // optional, defaults to http://localhost:8000/api/v1
49
+ timeout: 30000, // optional, request timeout in ms
50
+ });
51
+ ```
52
+
53
+ ---
54
+
55
+ ## Core Features & Examples
56
+
57
+ ### 1. Uploading an Image
58
+ Upload file buffers, `Uint8Array`, `ArrayBuffer`, or browser `Blob`/`File` instances. BigBucket automatically negotiates presigned S3/R2 direct upload URLs, performs content verification and Pillow image decode checks on the server, and returns a verified asset with its stable delivery URL.
59
+
60
+ ```typescript
61
+ import fs from "node:fs/promises";
62
+
63
+ const fileBuffer = await fs.readFile("./product.webp");
64
+
65
+ const image = await bigbucket.upload(fileBuffer, {
66
+ filename: "product.webp",
67
+ contentType: "image/webp",
68
+ });
69
+
70
+ console.log("Image ID:", image.id);
71
+ console.log("Delivery URL:", image.url);
72
+ console.log("Dimensions:", `${image.width}x${image.height}`);
73
+ console.log("Format:", image.format);
74
+ ```
75
+
76
+ ### 2. Retrieving Image Metadata
77
+ ```typescript
78
+ const image = await bigbucket.images.get("image-uuid-123");
79
+ console.log(image.status); // "ready"
80
+ console.log(image.url); // "https://images.example.com/..."
81
+ ```
82
+
83
+ ### 3. Listing & Paginating Images
84
+ ```typescript
85
+ const response = await bigbucket.images.list({
86
+ page: 1,
87
+ pageSize: 20,
88
+ status: "ready",
89
+ format: "webp",
90
+ });
91
+
92
+ for (const img of response.data) {
93
+ console.log(img.id, img.url);
94
+ }
95
+
96
+ console.log("Total images:", response.pagination.total);
97
+ console.log("Has next page:", response.pagination.hasNext);
98
+ ```
99
+
100
+ ### 4. Deleting an Image
101
+ Deletes the object from storage (Cloudflare R2) and frees project usage accounting atomically:
102
+
103
+ ```typescript
104
+ await bigbucket.images.delete("image-uuid-123");
105
+ console.log("Image deleted successfully");
106
+ ```
107
+
108
+ ### 5. Inspecting Usage Statistics
109
+ ```typescript
110
+ const usage = await bigbucket.usage.get("project-id");
111
+
112
+ console.log(`Stored Bytes: ${usage.totalStoredBytes}`);
113
+ console.log(`Ready Images: ${usage.totalReadyImages}`);
114
+ console.log(`Total Uploads: ${usage.successfulUploads}`);
115
+ console.log(`Total Deletes: ${usage.deletedImages}`);
116
+ ```
117
+
118
+ ---
119
+
120
+ ## Next.js Integration (App Router)
121
+
122
+ The SDK must be executed on the server to keep your project API key secure.
123
+
124
+ ```typescript
125
+ // app/api/upload/route.ts
126
+ import { NextResponse } from "next/server";
127
+ import { BigBucket, BigBucketError } from "@bigbucket-ai/sdk";
128
+
129
+ const bigbucket = new BigBucket({
130
+ apiKey: process.env.BIGBUCKET_API_KEY!,
131
+ });
132
+
133
+ export async function POST(request: Request) {
134
+ try {
135
+ const formData = await request.formData();
136
+ const file = formData.get("file") as File | null;
137
+
138
+ if (!file) {
139
+ return NextResponse.json({ error: "Missing file" }, { status: 400 });
140
+ }
141
+
142
+ const arrayBuffer = await file.arrayBuffer();
143
+ const image = await bigbucket.upload(new Uint8Array(arrayBuffer), {
144
+ filename: file.name,
145
+ contentType: file.type || "image/png",
146
+ fileSize: file.size,
147
+ });
148
+
149
+ return NextResponse.json({ data: image });
150
+ } catch (error) {
151
+ if (error instanceof BigBucketError) {
152
+ return NextResponse.json(
153
+ { error: { code: error.code, message: error.message } },
154
+ { status: error.statusCode }
155
+ );
156
+ }
157
+ return NextResponse.json({ error: "Upload failed" }, { status: 500 });
158
+ }
159
+ }
160
+ ```
161
+
162
+ ---
163
+
164
+ ## Error Handling
165
+
166
+ All API errors throw typed subclasses of `BigBucketError`:
167
+
168
+ ```typescript
169
+ import {
170
+ BigBucket,
171
+ AuthenticationError,
172
+ NotFoundError,
173
+ PayloadTooLargeError,
174
+ UnsupportedFormatError,
175
+ RateLimitError,
176
+ } from "@bigbucket-ai/sdk";
177
+
178
+ try {
179
+ await bigbucket.images.get("invalid-id");
180
+ } catch (error) {
181
+ if (error instanceof AuthenticationError) {
182
+ console.error("Invalid or revoked API key");
183
+ } else if (error instanceof NotFoundError) {
184
+ console.error("Image was not found");
185
+ } else if (error instanceof PayloadTooLargeError) {
186
+ console.error("Image file exceeded maximum allowed size");
187
+ } else if (error instanceof UnsupportedFormatError) {
188
+ console.error("Format not supported (allowed: JPEG, PNG, WebP, GIF)");
189
+ } else if (error instanceof RateLimitError) {
190
+ console.error("Rate limit exceeded, retry later");
191
+ } else {
192
+ console.error("Unexpected BigBucket error:", error);
193
+ }
194
+ }
195
+ ```
196
+
197
+ ---
198
+
199
+ ## Security Guidelines
200
+
201
+ 1. **Keep Keys Server-Side**: Never import or bundle `@bigbucket-ai/sdk` with a permanent `bb_live_...` key in client-side React, Vue, or browser scripts.
202
+ 2. **Key Rotation**: Rotate your keys regularly using `bigbucket.projects.apiKeys.rotate()` or the BigBucket console.
203
+ 3. **Restricted Tokens**: For direct client uploads from browsers, have your backend call `bigbucket.uploads.create()` and return only the temporary presigned upload URL to the browser.
@@ -0,0 +1,260 @@
1
+ interface TransportConfig {
2
+ apiKey: string;
3
+ baseUrl?: string | undefined;
4
+ timeout?: number | undefined;
5
+ fetch?: typeof fetch | undefined;
6
+ }
7
+ declare class HttpTransport {
8
+ private readonly apiKey;
9
+ private readonly baseUrl;
10
+ private readonly timeout;
11
+ private readonly customFetch;
12
+ constructor(config: TransportConfig);
13
+ /**
14
+ * Execute an authenticated request against the BigBucket API.
15
+ */
16
+ request<T>(path: string, options?: RequestInit): Promise<T>;
17
+ /**
18
+ * Upload binary data directly to the storage provider (Cloudflare R2 or Local Storage).
19
+ * Note: Permanent BigBucket credentials MUST NOT be forwarded to the storage provider.
20
+ */
21
+ uploadToPresignedUrl(uploadUrl: string, method: string, signedHeaders: Record<string, string>, body: BodyInit): Promise<void>;
22
+ }
23
+
24
+ /**
25
+ * TypeScript types for @bigbucket-ai/sdk matching the BigBucket API.
26
+ */
27
+ type ImageFormat = "jpeg" | "png" | "webp" | "gif";
28
+ type ImageStatus = "pending" | "processing" | "ready" | "failed" | "deleted";
29
+ interface BigBucketOptions {
30
+ /**
31
+ * Secret project API key (e.g. bb_live_...).
32
+ * Must only be used in trusted server-side environments.
33
+ */
34
+ apiKey: string;
35
+ /**
36
+ * Base URL of the BigBucket API. Defaults to http://localhost:8000/api/v1 in local dev.
37
+ */
38
+ baseUrl?: string | undefined;
39
+ /**
40
+ * Request timeout in milliseconds. Defaults to 30,000 (30 seconds).
41
+ */
42
+ timeout?: number | undefined;
43
+ /**
44
+ * Optional custom fetch implementation (useful in testing or specialized runtimes).
45
+ */
46
+ fetch?: typeof fetch | undefined;
47
+ }
48
+ type FileInput = Uint8Array | ArrayBuffer | Blob | {
49
+ buffer: ArrayBuffer;
50
+ } | string;
51
+ interface UploadOptions {
52
+ /**
53
+ * Original file name (e.g. product.webp).
54
+ */
55
+ filename: string;
56
+ /**
57
+ * MIME content type (e.g. image/webp, image/jpeg, image/png, image/gif).
58
+ */
59
+ contentType: string;
60
+ /**
61
+ * File size in bytes (optional, computed automatically when possible).
62
+ */
63
+ fileSize?: number | undefined;
64
+ }
65
+ interface ImageVariant {
66
+ variantName: string;
67
+ url: string;
68
+ mimeType: string;
69
+ fileSize: number;
70
+ width: number;
71
+ height: number;
72
+ format: string;
73
+ }
74
+ interface ImageAsset {
75
+ id: string;
76
+ projectId: string;
77
+ url: string;
78
+ originalFilename: string;
79
+ mimeType: string;
80
+ fileSize: number;
81
+ width: number;
82
+ height: number;
83
+ format: ImageFormat;
84
+ status: ImageStatus;
85
+ createdAt: string;
86
+ updatedAt: string;
87
+ variants: ImageVariant[];
88
+ }
89
+ interface ImageListOptions {
90
+ page?: number | undefined;
91
+ pageSize?: number | undefined;
92
+ status?: ImageStatus | undefined;
93
+ format?: string | undefined;
94
+ }
95
+ interface Pagination {
96
+ total: number;
97
+ page: number;
98
+ pageSize: number;
99
+ hasNext: boolean;
100
+ }
101
+ interface PaginatedImages {
102
+ data: ImageAsset[];
103
+ pagination: Pagination;
104
+ }
105
+ interface PresignedDetails {
106
+ url: string;
107
+ method: string;
108
+ headers: Record<string, string>;
109
+ }
110
+ interface UploadSession {
111
+ uploadId: string;
112
+ objectKey: string;
113
+ presigned: PresignedDetails;
114
+ expiresAt: string;
115
+ }
116
+ interface UploadStatus {
117
+ id: string;
118
+ projectId: string;
119
+ objectKey: string;
120
+ expectedFileSize: number;
121
+ expectedMimeType: string;
122
+ status: string;
123
+ expiresAt: string;
124
+ createdAt: string;
125
+ completedAt: string | null;
126
+ assetId: string | null;
127
+ }
128
+ interface UsageSummary {
129
+ totalStoredBytes: number;
130
+ totalReadyImages: number;
131
+ successfulUploads: number;
132
+ deletedImages: number;
133
+ }
134
+
135
+ /**
136
+ * Images resource for listing, inspecting, and deleting media assets.
137
+ */
138
+
139
+ declare class ImagesResource {
140
+ private readonly transport;
141
+ constructor(transport: HttpTransport);
142
+ private mapAsset;
143
+ /**
144
+ * Retrieve metadata and stable delivery URL for an image.
145
+ */
146
+ get(imageId: string): Promise<ImageAsset>;
147
+ /**
148
+ * List and paginate media assets belonging to the authenticated project.
149
+ */
150
+ list(options?: ImageListOptions): Promise<PaginatedImages>;
151
+ /**
152
+ * Delete an image from storage and mark it deleted in BigBucket.
153
+ */
154
+ delete(imageId: string): Promise<{
155
+ success: boolean;
156
+ id: string;
157
+ }>;
158
+ }
159
+
160
+ /**
161
+ * Uploads resource for managing upload sessions and finalization.
162
+ */
163
+
164
+ declare class UploadsResource {
165
+ private readonly transport;
166
+ constructor(transport: HttpTransport);
167
+ /**
168
+ * Request permission and generate a presigned upload URL.
169
+ */
170
+ create(options: {
171
+ filename: string;
172
+ contentType: string;
173
+ fileSize: number;
174
+ }): Promise<UploadSession>;
175
+ /**
176
+ * Finalize an upload session once the client has uploaded bytes to the presigned URL.
177
+ */
178
+ complete(uploadId: string): Promise<ImageAsset>;
179
+ /**
180
+ * Check the status of an ongoing or completed upload session.
181
+ */
182
+ get(uploadId: string): Promise<UploadStatus>;
183
+ }
184
+
185
+ /**
186
+ * Usage resource for inspecting stored bytes, ready images, and upload metrics.
187
+ */
188
+
189
+ declare class UsageResource {
190
+ private readonly transport;
191
+ constructor(transport: HttpTransport);
192
+ /**
193
+ * Retrieve usage metrics for a project or the account.
194
+ */
195
+ get(projectId?: string): Promise<UsageSummary>;
196
+ }
197
+
198
+ declare class BigBucket {
199
+ private readonly transport;
200
+ readonly images: ImagesResource;
201
+ readonly uploads: UploadsResource;
202
+ readonly usage: UsageResource;
203
+ constructor(options: BigBucketOptions);
204
+ /**
205
+ * Helper method to normalize arbitrary input types (Buffer, Uint8Array, Blob, etc.)
206
+ * and resolve byte length.
207
+ */
208
+ private resolveFileData;
209
+ /**
210
+ * Complete end-to-end image upload workflow:
211
+ * 1. Requests an upload session and receives presigned storage URL.
212
+ * 2. Uploads binary data directly to the storage provider (Cloudflare R2).
213
+ * 3. Finalizes the upload with server verification and content inspection.
214
+ * 4. Returns verified ImageAsset with delivery URL.
215
+ */
216
+ upload(file: FileInput, options: UploadOptions): Promise<ImageAsset>;
217
+ }
218
+
219
+ /**
220
+ * Typed Error hierarchy for BigBucket SDK.
221
+ */
222
+ interface BigBucketErrorOptions {
223
+ message: string;
224
+ statusCode?: number | undefined;
225
+ code?: string | undefined;
226
+ requestId?: string | undefined;
227
+ details?: unknown;
228
+ cause?: unknown;
229
+ }
230
+ declare class BigBucketError extends Error {
231
+ readonly statusCode: number;
232
+ readonly code: string;
233
+ readonly requestId: string | undefined;
234
+ readonly details: unknown;
235
+ readonly isRetryable: boolean;
236
+ constructor(options: BigBucketErrorOptions);
237
+ }
238
+ declare class AuthenticationError extends BigBucketError {
239
+ constructor(options: BigBucketErrorOptions);
240
+ }
241
+ declare class NotFoundError extends BigBucketError {
242
+ constructor(options: BigBucketErrorOptions);
243
+ }
244
+ declare class PayloadTooLargeError extends BigBucketError {
245
+ constructor(options: BigBucketErrorOptions);
246
+ }
247
+ declare class UnsupportedFormatError extends BigBucketError {
248
+ constructor(options: BigBucketErrorOptions);
249
+ }
250
+ declare class RateLimitError extends BigBucketError {
251
+ constructor(options: BigBucketErrorOptions);
252
+ }
253
+ declare class StorageUploadError extends BigBucketError {
254
+ constructor(message: string, cause?: unknown);
255
+ }
256
+ declare class TimeoutError extends BigBucketError {
257
+ constructor(message?: string);
258
+ }
259
+
260
+ export { AuthenticationError, BigBucket, BigBucketError, type BigBucketErrorOptions, type BigBucketOptions, type FileInput, HttpTransport, type ImageAsset, type ImageFormat, type ImageListOptions, type ImageStatus, type ImageVariant, ImagesResource, NotFoundError, type PaginatedImages, type Pagination, PayloadTooLargeError, type PresignedDetails, RateLimitError, StorageUploadError, TimeoutError, type TransportConfig, UnsupportedFormatError, type UploadOptions, type UploadSession, type UploadStatus, UploadsResource, UsageResource, type UsageSummary };