@baclet/sdk 0.2.2 → 0.2.4
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 +46 -1
- package/dist/index.d.ts +67 -1
- package/dist/index.js +100 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -27,6 +27,7 @@ Open the dashboard, choose a workspace, then go to **Projects → your project
|
|
|
27
27
|
- **API URL** → use as `apiUrl`
|
|
28
28
|
- **Publishable key** → use as `publishableKey`; safe for client code
|
|
29
29
|
- **Secret key** → server-only; shown in full only when created or rotated
|
|
30
|
+
- **Storage bucket** → copy from **Storage** when the project has an active storage connection; use as `storageBucket`
|
|
30
31
|
|
|
31
32
|
---
|
|
32
33
|
|
|
@@ -45,7 +46,7 @@ export const baclet = initializeBaclet({
|
|
|
45
46
|
export const auth = getAuth(baclet);
|
|
46
47
|
```
|
|
47
48
|
|
|
48
|
-
`initializeBaclet()` is idempotent. Calling it again with the same name and
|
|
49
|
+
`initializeBaclet()` is idempotent. Calling it again with the same name, credentials, and storage bucket returns the existing client. Calling it with different settings throws a `BacletError` with status `409`.
|
|
49
50
|
|
|
50
51
|
The client derives your project ID from the publishable key (`pb_<uuid>_...`), so there is no separate project ID to configure.
|
|
51
52
|
|
|
@@ -108,6 +109,7 @@ const baclet = createBacletClient({
|
|
|
108
109
|
| --- | --- | --- | --- |
|
|
109
110
|
| `apiUrl` | `string` | required | Base BACLET API URL. `https://` is added when omitted; a trailing `/v1` is removed automatically. |
|
|
110
111
|
| `publishableKey` | `string` | required | Your project publishable key. Safe to use in browser bundles. |
|
|
112
|
+
| `storageBucket` | `string` | `undefined` | Default bucket for storage methods. Required unless a `bucket` is passed per call. |
|
|
111
113
|
| `secretKey` | `string` | `undefined` | Optional server-side key. Validated when provided; omit it from browser code. |
|
|
112
114
|
| `storage` | `StorageLike \| null` | `localStorage`, or memory | Custom key/value store. Pass `null` to force in-memory storage. |
|
|
113
115
|
| `autoRefresh` | `boolean` | `true` | Refresh the session automatically when `getSession()` sees an expired access token. |
|
|
@@ -186,6 +188,44 @@ Pass `redirect: false` to `signInWithGoogle()` to receive the URL without naviga
|
|
|
186
188
|
|
|
187
189
|
---
|
|
188
190
|
|
|
191
|
+
## Storage
|
|
192
|
+
|
|
193
|
+
Firebase shows uploaded objects under **Storage → Files**. BACLET uses the same model: the bucket is the container created during provisioning, and object keys are paths inside that bucket. The bucket is not part of the key.
|
|
194
|
+
|
|
195
|
+
Initialize the client with the bucket shown in the BACLET dashboard:
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
import { initializeBaclet } from "@baclet/sdk";
|
|
199
|
+
|
|
200
|
+
const client = initializeBaclet({
|
|
201
|
+
apiUrl: import.meta.env.VITE_BACLET_API_URL,
|
|
202
|
+
publishableKey: import.meta.env.VITE_BACLET_PUBLISHABLE_KEY,
|
|
203
|
+
storageBucket: import.meta.env.VITE_BACLET_STORAGE_BUCKET,
|
|
204
|
+
});
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Then pass only object keys and prefixes to storage methods:
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
const object = await client.storage.upload({
|
|
211
|
+
key: `users/${user.id}/avatar.png`,
|
|
212
|
+
file: avatarFile,
|
|
213
|
+
contentType: "image/png",
|
|
214
|
+
visibility: "private",
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
const { url } = await client.storage.download({ key: object.key, expiresIn: 900 });
|
|
218
|
+
|
|
219
|
+
const objects = await client.storage.list({ prefix: `users/${user.id}/` });
|
|
220
|
+
await client.storage.remove({ key: object.key });
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
`upload()` requests a short-lived provider URL from BACLET, sends the file bytes directly to the provider, then records the object metadata. File bytes never pass through the BACLET API. You can pass `bucket` to an individual storage call to override the configured bucket.
|
|
224
|
+
|
|
225
|
+
Available methods: `upload()`, `download()`, `signedURL()`, `info()`, `list()`, `remove()`, `copy()`, and `move()`.
|
|
226
|
+
|
|
227
|
+
---
|
|
228
|
+
|
|
189
229
|
## Sessions and state
|
|
190
230
|
|
|
191
231
|
### Session methods
|
|
@@ -286,10 +326,15 @@ import type {
|
|
|
286
326
|
BacletSession,
|
|
287
327
|
BacletTokens,
|
|
288
328
|
BacletUser,
|
|
329
|
+
BacletStorage,
|
|
289
330
|
GoogleSignInOptions,
|
|
290
331
|
SignInInput,
|
|
291
332
|
SignUpInput,
|
|
333
|
+
StorageDownload,
|
|
292
334
|
StorageLike,
|
|
335
|
+
StorageObject,
|
|
336
|
+
StorageObjectInput,
|
|
337
|
+
StorageUploadInput,
|
|
293
338
|
} from "@baclet/sdk";
|
|
294
339
|
```
|
|
295
340
|
|
package/dist/index.d.ts
CHANGED
|
@@ -43,6 +43,7 @@ export interface StorageLike {
|
|
|
43
43
|
export interface BacletConfig {
|
|
44
44
|
apiUrl: string;
|
|
45
45
|
publishableKey: string;
|
|
46
|
+
storageBucket?: string;
|
|
46
47
|
secretKey?: string;
|
|
47
48
|
}
|
|
48
49
|
export interface BacletClientOptions extends BacletConfig {
|
|
@@ -67,6 +68,66 @@ export type AuthStateListener = (session: BacletSession | null) => void;
|
|
|
67
68
|
type MessageResponse = {
|
|
68
69
|
message: string;
|
|
69
70
|
};
|
|
71
|
+
export interface StorageObject {
|
|
72
|
+
key: string;
|
|
73
|
+
size_bytes: number;
|
|
74
|
+
content_type?: string;
|
|
75
|
+
etag?: string;
|
|
76
|
+
visibility: "public" | "private";
|
|
77
|
+
owner_user_id?: string;
|
|
78
|
+
}
|
|
79
|
+
export interface StorageUploadResult extends StorageObject {
|
|
80
|
+
upload_url: string;
|
|
81
|
+
method: string;
|
|
82
|
+
headers?: Record<string, string>;
|
|
83
|
+
fields?: Record<string, string>;
|
|
84
|
+
token: string;
|
|
85
|
+
expires_at: string;
|
|
86
|
+
bucket: string;
|
|
87
|
+
}
|
|
88
|
+
export interface StorageDownload {
|
|
89
|
+
url: string;
|
|
90
|
+
method: string;
|
|
91
|
+
headers?: Record<string, string>;
|
|
92
|
+
expires_at: string;
|
|
93
|
+
}
|
|
94
|
+
export interface StorageUploadInput {
|
|
95
|
+
bucket?: string;
|
|
96
|
+
key: string;
|
|
97
|
+
file: Blob;
|
|
98
|
+
fileName?: string;
|
|
99
|
+
contentType?: string;
|
|
100
|
+
visibility?: "public" | "private";
|
|
101
|
+
sizeBytes?: number;
|
|
102
|
+
}
|
|
103
|
+
export interface StorageObjectInput {
|
|
104
|
+
bucket?: string;
|
|
105
|
+
key: string;
|
|
106
|
+
}
|
|
107
|
+
export interface StorageListInput {
|
|
108
|
+
bucket?: string;
|
|
109
|
+
prefix?: string;
|
|
110
|
+
limit?: number;
|
|
111
|
+
}
|
|
112
|
+
export interface StorageMutationInput {
|
|
113
|
+
bucket?: string;
|
|
114
|
+
from: string;
|
|
115
|
+
to: string;
|
|
116
|
+
}
|
|
117
|
+
export interface BacletStorage {
|
|
118
|
+
upload(input: StorageUploadInput): Promise<StorageObject>;
|
|
119
|
+
download(input: StorageObjectInput & {
|
|
120
|
+
expiresIn?: number;
|
|
121
|
+
}): Promise<StorageDownload>;
|
|
122
|
+
signedURL(input: StorageObjectInput & {
|
|
123
|
+
expiresIn?: number;
|
|
124
|
+
}): Promise<string>;
|
|
125
|
+
info(input: StorageObjectInput): Promise<StorageObject>;
|
|
126
|
+
list(input: StorageListInput): Promise<StorageObject[]>;
|
|
127
|
+
remove(input: StorageObjectInput): Promise<void>;
|
|
128
|
+
copy(input: StorageMutationInput): Promise<StorageObject>;
|
|
129
|
+
move(input: StorageMutationInput): Promise<StorageObject>;
|
|
130
|
+
}
|
|
70
131
|
export interface BacletAuth {
|
|
71
132
|
capabilities(): Promise<AuthCapabilities>;
|
|
72
133
|
signUp(input: SignUpInput): Promise<BacletSession>;
|
|
@@ -105,18 +166,22 @@ export declare class BacletError extends Error {
|
|
|
105
166
|
export declare class BacletClient {
|
|
106
167
|
readonly apiUrl: string;
|
|
107
168
|
readonly publishableKey: string;
|
|
169
|
+
readonly storageBucket?: string;
|
|
108
170
|
readonly secretKey?: string;
|
|
109
171
|
readonly projectID: string;
|
|
110
|
-
private readonly
|
|
172
|
+
private readonly tokenStorage;
|
|
111
173
|
private readonly fetchImpl;
|
|
112
174
|
private readonly autoRefresh;
|
|
113
175
|
private readonly tokensKey;
|
|
114
176
|
private readonly userKey;
|
|
115
177
|
private readonly listeners;
|
|
116
178
|
private readonly authService;
|
|
179
|
+
private readonly storageService;
|
|
117
180
|
constructor(options: BacletClientOptions);
|
|
118
181
|
get auth(): BacletAuth;
|
|
182
|
+
get storage(): BacletStorage;
|
|
119
183
|
private createAuthService;
|
|
184
|
+
private createStorageService;
|
|
120
185
|
capabilities(): Promise<AuthCapabilities>;
|
|
121
186
|
signUp(input: SignUpInput): Promise<BacletSession>;
|
|
122
187
|
signIn(input: SignInInput): Promise<BacletSession>;
|
|
@@ -137,6 +202,7 @@ export declare class BacletClient {
|
|
|
137
202
|
onAuthStateChanged(listener: AuthStateListener): () => void;
|
|
138
203
|
private authPath;
|
|
139
204
|
private currentUser;
|
|
205
|
+
private storageRequest;
|
|
140
206
|
private request;
|
|
141
207
|
private throwResponseError;
|
|
142
208
|
private readTokens;
|
package/dist/index.js
CHANGED
|
@@ -100,15 +100,17 @@ export class BacletError extends Error {
|
|
|
100
100
|
export class BacletClient {
|
|
101
101
|
apiUrl;
|
|
102
102
|
publishableKey;
|
|
103
|
+
storageBucket;
|
|
103
104
|
secretKey;
|
|
104
105
|
projectID;
|
|
105
|
-
|
|
106
|
+
tokenStorage;
|
|
106
107
|
fetchImpl;
|
|
107
108
|
autoRefresh;
|
|
108
109
|
tokensKey;
|
|
109
110
|
userKey;
|
|
110
111
|
listeners = new Set();
|
|
111
112
|
authService;
|
|
113
|
+
storageService;
|
|
112
114
|
constructor(options) {
|
|
113
115
|
if (!options.publishableKey) {
|
|
114
116
|
throw new BacletError("A BACLET publishable key is required.", 400);
|
|
@@ -116,9 +118,10 @@ export class BacletClient {
|
|
|
116
118
|
validateSecretKey(options.secretKey);
|
|
117
119
|
this.apiUrl = normalizeAPIURL(options.apiUrl);
|
|
118
120
|
this.publishableKey = options.publishableKey;
|
|
121
|
+
this.storageBucket = options.storageBucket?.trim() || undefined;
|
|
119
122
|
this.secretKey = options.secretKey;
|
|
120
123
|
this.projectID = projectIDFromKey(options.publishableKey);
|
|
121
|
-
this.
|
|
124
|
+
this.tokenStorage = resolveStorage(options.storage);
|
|
122
125
|
this.fetchImpl = (options.fetch ?? globalThis.fetch).bind(globalThis);
|
|
123
126
|
if (typeof this.fetchImpl !== "function") {
|
|
124
127
|
throw new BacletError("This runtime does not provide fetch; pass options.fetch.", 500);
|
|
@@ -127,10 +130,14 @@ export class BacletClient {
|
|
|
127
130
|
this.tokensKey = `baclet:${this.projectID}:tokens`;
|
|
128
131
|
this.userKey = `baclet:${this.projectID}:user`;
|
|
129
132
|
this.authService = this.createAuthService();
|
|
133
|
+
this.storageService = this.createStorageService();
|
|
130
134
|
}
|
|
131
135
|
get auth() {
|
|
132
136
|
return this.authService;
|
|
133
137
|
}
|
|
138
|
+
get storage() {
|
|
139
|
+
return this.storageService;
|
|
140
|
+
}
|
|
134
141
|
createAuthService() {
|
|
135
142
|
return {
|
|
136
143
|
capabilities: () => this.capabilities(),
|
|
@@ -153,6 +160,85 @@ export class BacletClient {
|
|
|
153
160
|
onAuthStateChanged: (listener) => this.onAuthStateChanged(listener),
|
|
154
161
|
};
|
|
155
162
|
}
|
|
163
|
+
createStorageService() {
|
|
164
|
+
const path = (suffix) => `/v1/projects/${this.projectID}/storage${suffix}`;
|
|
165
|
+
const bucketFor = (bucket) => {
|
|
166
|
+
const resolved = bucket?.trim() || this.storageBucket;
|
|
167
|
+
if (!resolved) {
|
|
168
|
+
throw new BacletError("A storage bucket is required. Set storageBucket when initializing BACLET or pass bucket to the storage call.", 400);
|
|
169
|
+
}
|
|
170
|
+
return resolved;
|
|
171
|
+
};
|
|
172
|
+
const objectQuery = (input) => {
|
|
173
|
+
const query = new URLSearchParams({ bucket: bucketFor(input.bucket), key: input.key });
|
|
174
|
+
if (input.expiresIn)
|
|
175
|
+
query.set("expires_in", String(input.expiresIn));
|
|
176
|
+
return `?${query.toString()}`;
|
|
177
|
+
};
|
|
178
|
+
return {
|
|
179
|
+
upload: async (input) => {
|
|
180
|
+
const upload = await this.storageRequest(path("/uploads"), {
|
|
181
|
+
method: "POST",
|
|
182
|
+
body: {
|
|
183
|
+
bucket: bucketFor(input.bucket),
|
|
184
|
+
key: input.key,
|
|
185
|
+
size_bytes: input.sizeBytes ?? input.file.size,
|
|
186
|
+
content_type: input.contentType ?? input.file.type,
|
|
187
|
+
visibility: input.visibility ?? "private",
|
|
188
|
+
},
|
|
189
|
+
});
|
|
190
|
+
let response;
|
|
191
|
+
if (upload.fields) {
|
|
192
|
+
const form = new FormData();
|
|
193
|
+
for (const [key, value] of Object.entries(upload.fields))
|
|
194
|
+
form.append(key, value);
|
|
195
|
+
form.append("file", input.file, input.fileName ?? "upload.bin");
|
|
196
|
+
response = await this.fetchImpl(upload.upload_url, { method: upload.method, body: form });
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
const headers = { ...(upload.headers ?? {}) };
|
|
200
|
+
response = await this.fetchImpl(upload.upload_url, {
|
|
201
|
+
method: upload.method,
|
|
202
|
+
headers,
|
|
203
|
+
body: input.file,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
if (!response.ok)
|
|
207
|
+
await this.throwResponseError(response);
|
|
208
|
+
const object = await this.storageRequest(path("/uploads/complete"), {
|
|
209
|
+
method: "POST",
|
|
210
|
+
body: { token: upload.token },
|
|
211
|
+
});
|
|
212
|
+
return object;
|
|
213
|
+
},
|
|
214
|
+
download: (input) => this.storageRequest(path(`/objects${objectQuery(input)}`)),
|
|
215
|
+
signedURL: async (input) => {
|
|
216
|
+
const result = await this.storageRequest(path(`/objects${objectQuery(input)}`));
|
|
217
|
+
return result.url;
|
|
218
|
+
},
|
|
219
|
+
info: (input) => this.storageRequest(path(`/objects/info${objectQuery(input)}`)),
|
|
220
|
+
list: async (input) => {
|
|
221
|
+
const query = new URLSearchParams({ bucket: bucketFor(input.bucket) });
|
|
222
|
+
if (input.prefix)
|
|
223
|
+
query.set("prefix", input.prefix);
|
|
224
|
+
if (input.limit)
|
|
225
|
+
query.set("limit", String(input.limit));
|
|
226
|
+
const result = await this.storageRequest(path(`/objects/list?${query.toString()}`));
|
|
227
|
+
return result.objects;
|
|
228
|
+
},
|
|
229
|
+
remove: async (input) => {
|
|
230
|
+
await this.storageRequest(path(`/objects${objectQuery(input)}`), { method: "DELETE" });
|
|
231
|
+
},
|
|
232
|
+
copy: (input) => this.storageRequest(path("/objects/copy"), {
|
|
233
|
+
method: "POST",
|
|
234
|
+
body: { bucket: bucketFor(input.bucket), from: input.from, to: input.to },
|
|
235
|
+
}),
|
|
236
|
+
move: (input) => this.storageRequest(path("/objects/move"), {
|
|
237
|
+
method: "POST",
|
|
238
|
+
body: { bucket: bucketFor(input.bucket), from: input.from, to: input.to },
|
|
239
|
+
}),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
156
242
|
capabilities() {
|
|
157
243
|
return this.request(`/v1/projects/${this.projectID}/auth/capabilities`);
|
|
158
244
|
}
|
|
@@ -219,7 +305,7 @@ export class BacletClient {
|
|
|
219
305
|
this.clearSession();
|
|
220
306
|
throw new BacletError("OAuth response did not include tokens.", 400);
|
|
221
307
|
}
|
|
222
|
-
this.
|
|
308
|
+
this.tokenStorage.setItem(this.tokensKey, JSON.stringify(tokens));
|
|
223
309
|
const session = await this.getSession();
|
|
224
310
|
if (!session) {
|
|
225
311
|
throw new BacletError("OAuth sign-in could not load the user.", 401);
|
|
@@ -333,6 +419,10 @@ export class BacletClient {
|
|
|
333
419
|
accessToken,
|
|
334
420
|
}).then((result) => result.user);
|
|
335
421
|
}
|
|
422
|
+
storageRequest(path, options = {}) {
|
|
423
|
+
const accessToken = options.accessToken ?? this.readTokens()?.access_token;
|
|
424
|
+
return this.request(path, { ...options, accessToken });
|
|
425
|
+
}
|
|
336
426
|
async request(path, options = {}) {
|
|
337
427
|
const headers = {
|
|
338
428
|
Accept: "application/json",
|
|
@@ -367,22 +457,22 @@ export class BacletClient {
|
|
|
367
457
|
throw new BacletError(message, response.status, payload);
|
|
368
458
|
}
|
|
369
459
|
readTokens() {
|
|
370
|
-
const tokens = parseTokens(this.
|
|
460
|
+
const tokens = parseTokens(this.tokenStorage.getItem(this.tokensKey));
|
|
371
461
|
if (!tokens)
|
|
372
|
-
this.
|
|
462
|
+
this.tokenStorage.removeItem(this.tokensKey);
|
|
373
463
|
return tokens;
|
|
374
464
|
}
|
|
375
465
|
writeSession(session) {
|
|
376
|
-
this.
|
|
377
|
-
this.
|
|
466
|
+
this.tokenStorage.setItem(this.tokensKey, JSON.stringify(session.tokens));
|
|
467
|
+
this.tokenStorage.setItem(this.userKey, JSON.stringify(session.user));
|
|
378
468
|
this.emit(session);
|
|
379
469
|
}
|
|
380
470
|
applySession(session) {
|
|
381
471
|
this.writeSession(session);
|
|
382
472
|
}
|
|
383
473
|
clearSession() {
|
|
384
|
-
this.
|
|
385
|
-
this.
|
|
474
|
+
this.tokenStorage.removeItem(this.tokensKey);
|
|
475
|
+
this.tokenStorage.removeItem(this.userKey);
|
|
386
476
|
this.emit(null);
|
|
387
477
|
}
|
|
388
478
|
emit(session) {
|
|
@@ -415,6 +505,7 @@ export function initializeBaclet(config, name = "DEFAULT") {
|
|
|
415
505
|
if (existing) {
|
|
416
506
|
if (existing.apiUrl !== normalizeAPIURL(config.apiUrl) ||
|
|
417
507
|
existing.publishableKey !== config.publishableKey ||
|
|
508
|
+
existing.storageBucket !== config.storageBucket?.trim() ||
|
|
418
509
|
existing.secretKey !== config.secretKey) {
|
|
419
510
|
throw new BacletError(`BACLET app "${name}" already exists with different credentials.`, 409);
|
|
420
511
|
}
|