@baclet/sdk 0.2.4 → 0.2.6

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/dist/index.d.ts CHANGED
@@ -107,8 +107,13 @@ export interface StorageObjectInput {
107
107
  export interface StorageListInput {
108
108
  bucket?: string;
109
109
  prefix?: string;
110
+ cursor?: string;
110
111
  limit?: number;
111
112
  }
113
+ export interface StorageListPage {
114
+ objects: StorageObject[];
115
+ nextCursor?: string;
116
+ }
112
117
  export interface StorageMutationInput {
113
118
  bucket?: string;
114
119
  from: string;
@@ -124,6 +129,7 @@ export interface BacletStorage {
124
129
  }): Promise<string>;
125
130
  info(input: StorageObjectInput): Promise<StorageObject>;
126
131
  list(input: StorageListInput): Promise<StorageObject[]>;
132
+ listPage(input: StorageListInput): Promise<StorageListPage>;
127
133
  remove(input: StorageObjectInput): Promise<void>;
128
134
  copy(input: StorageMutationInput): Promise<StorageObject>;
129
135
  move(input: StorageMutationInput): Promise<StorageObject>;
@@ -174,6 +180,8 @@ export declare class BacletClient {
174
180
  private readonly autoRefresh;
175
181
  private readonly tokensKey;
176
182
  private readonly userKey;
183
+ private readonly expiresKey;
184
+ private readonly storageCache;
177
185
  private readonly listeners;
178
186
  private readonly authService;
179
187
  private readonly storageService;
@@ -206,9 +214,11 @@ export declare class BacletClient {
206
214
  private request;
207
215
  private throwResponseError;
208
216
  private readTokens;
217
+ private readTokenExpiry;
209
218
  private writeSession;
210
219
  private applySession;
211
220
  private clearSession;
221
+ private clearStorageCache;
212
222
  private emit;
213
223
  private tokensFromParams;
214
224
  private clearLocationFragment;
package/dist/index.js CHANGED
@@ -1,4 +1,8 @@
1
1
  const bacletApps = new Map();
2
+ const SESSION_REFRESH_SKEW_MS = 60_000;
3
+ const STORAGE_CACHE_TTL_MS = 30_000;
4
+ const STORAGE_DOWNLOAD_CACHE_TTL_MS = 5 * 60_000;
5
+ const STORAGE_CACHE_SEPARATOR = "\u0000";
2
6
  const memoryValues = new Map();
3
7
  const memoryStorage = {
4
8
  getItem: (key) => memoryValues.get(key) ?? null,
@@ -82,6 +86,19 @@ function parseTokens(value) {
82
86
  return null;
83
87
  }
84
88
  }
89
+ function parseUser(value) {
90
+ if (!value)
91
+ return null;
92
+ try {
93
+ const parsed = JSON.parse(value);
94
+ if (!parsed || typeof parsed.id !== "string" || typeof parsed.display_name !== "string")
95
+ return null;
96
+ return parsed;
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ }
85
102
  function parseResponse(response) {
86
103
  if (response.status === 204)
87
104
  return Promise.resolve(undefined);
@@ -108,6 +125,8 @@ export class BacletClient {
108
125
  autoRefresh;
109
126
  tokensKey;
110
127
  userKey;
128
+ expiresKey;
129
+ storageCache = new Map();
111
130
  listeners = new Set();
112
131
  authService;
113
132
  storageService;
@@ -129,6 +148,7 @@ export class BacletClient {
129
148
  this.autoRefresh = options.autoRefresh ?? true;
130
149
  this.tokensKey = `baclet:${this.projectID}:tokens`;
131
150
  this.userKey = `baclet:${this.projectID}:user`;
151
+ this.expiresKey = `baclet:${this.projectID}:expires_at`;
132
152
  this.authService = this.createAuthService();
133
153
  this.storageService = this.createStorageService();
134
154
  }
@@ -175,12 +195,73 @@ export class BacletClient {
175
195
  query.set("expires_in", String(input.expiresIn));
176
196
  return `?${query.toString()}`;
177
197
  };
198
+ const cacheKey = (...parts) => parts.join(STORAGE_CACHE_SEPARATOR);
199
+ const readCache = (key) => {
200
+ const entry = this.storageCache.get(key);
201
+ if (!entry)
202
+ return undefined;
203
+ if (Date.now() >= entry.expiresAt) {
204
+ this.storageCache.delete(key);
205
+ return undefined;
206
+ }
207
+ return entry.value;
208
+ };
209
+ const writeCache = (key, value, ttl) => {
210
+ if (ttl > 0)
211
+ this.storageCache.set(key, { expiresAt: Date.now() + ttl, value });
212
+ };
213
+ const listPage = async (input) => {
214
+ const bucket = bucketFor(input.bucket);
215
+ const query = new URLSearchParams({ bucket });
216
+ if (input.prefix)
217
+ query.set("prefix", input.prefix);
218
+ if (input.cursor)
219
+ query.set("cursor", input.cursor);
220
+ if (input.limit)
221
+ query.set("limit", String(input.limit));
222
+ const key = cacheKey("list", bucket, input.prefix ?? "", input.cursor ?? "", input.limit ? String(input.limit) : "");
223
+ const cached = readCache(key);
224
+ if (cached)
225
+ return cached;
226
+ const result = await this.storageRequest(path(`/objects/list?${query.toString()}`));
227
+ const page = {
228
+ objects: result.objects,
229
+ nextCursor: result.next_cursor || undefined,
230
+ };
231
+ writeCache(key, page, STORAGE_CACHE_TTL_MS);
232
+ return page;
233
+ };
234
+ const info = async (input) => {
235
+ const bucket = bucketFor(input.bucket);
236
+ const key = cacheKey("info", bucket, input.key);
237
+ const cached = readCache(key);
238
+ if (cached)
239
+ return cached;
240
+ const object = await this.storageRequest(path(`/objects/info${objectQuery(input)}`));
241
+ writeCache(key, object, STORAGE_CACHE_TTL_MS);
242
+ return object;
243
+ };
244
+ const download = async (input) => {
245
+ const bucket = bucketFor(input.bucket);
246
+ const key = cacheKey("download", bucket, input.key, input.expiresIn ? String(input.expiresIn) : "");
247
+ const cached = readCache(key);
248
+ if (cached)
249
+ return cached;
250
+ const result = await this.storageRequest(path(`/objects${objectQuery(input)}`));
251
+ const expiresAt = Date.parse(result.expires_at);
252
+ if (Number.isFinite(expiresAt)) {
253
+ const ttl = Math.min(expiresAt - Date.now() - SESSION_REFRESH_SKEW_MS, STORAGE_DOWNLOAD_CACHE_TTL_MS);
254
+ writeCache(key, result, ttl);
255
+ }
256
+ return result;
257
+ };
178
258
  return {
179
259
  upload: async (input) => {
260
+ const bucket = bucketFor(input.bucket);
180
261
  const upload = await this.storageRequest(path("/uploads"), {
181
262
  method: "POST",
182
263
  body: {
183
- bucket: bucketFor(input.bucket),
264
+ bucket,
184
265
  key: input.key,
185
266
  size_bytes: input.sizeBytes ?? input.file.size,
186
267
  content_type: input.contentType ?? input.file.type,
@@ -209,34 +290,37 @@ export class BacletClient {
209
290
  method: "POST",
210
291
  body: { token: upload.token },
211
292
  });
293
+ this.clearStorageCache(bucket);
212
294
  return object;
213
295
  },
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
- },
296
+ download,
297
+ signedURL: async (input) => (await download(input)).url,
298
+ info,
299
+ list: async (input) => (await listPage(input)).objects,
300
+ listPage,
229
301
  remove: async (input) => {
302
+ const bucket = bucketFor(input.bucket);
230
303
  await this.storageRequest(path(`/objects${objectQuery(input)}`), { method: "DELETE" });
304
+ this.clearStorageCache(bucket);
305
+ },
306
+ copy: async (input) => {
307
+ const bucket = bucketFor(input.bucket);
308
+ const object = await this.storageRequest(path("/objects/copy"), {
309
+ method: "POST",
310
+ body: { bucket, from: input.from, to: input.to },
311
+ });
312
+ this.clearStorageCache(bucket);
313
+ return object;
314
+ },
315
+ move: async (input) => {
316
+ const bucket = bucketFor(input.bucket);
317
+ const object = await this.storageRequest(path("/objects/move"), {
318
+ method: "POST",
319
+ body: { bucket, from: input.from, to: input.to },
320
+ });
321
+ this.clearStorageCache(bucket);
322
+ return object;
231
323
  },
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
324
  };
241
325
  }
242
326
  capabilities() {
@@ -306,6 +390,9 @@ export class BacletClient {
306
390
  throw new BacletError("OAuth response did not include tokens.", 400);
307
391
  }
308
392
  this.tokenStorage.setItem(this.tokensKey, JSON.stringify(tokens));
393
+ this.tokenStorage.removeItem(this.userKey);
394
+ this.tokenStorage.removeItem(this.expiresKey);
395
+ this.clearStorageCache();
309
396
  const session = await this.getSession();
310
397
  if (!session) {
311
398
  throw new BacletError("OAuth sign-in could not load the user.", 401);
@@ -340,6 +427,23 @@ export class BacletClient {
340
427
  const tokens = this.readTokens();
341
428
  if (!tokens)
342
429
  return null;
430
+ const cachedUser = parseUser(this.tokenStorage.getItem(this.userKey));
431
+ const expiresAt = this.readTokenExpiry();
432
+ if (cachedUser && expiresAt !== null && Date.now() < expiresAt - SESSION_REFRESH_SKEW_MS) {
433
+ return { user: cachedUser, tokens };
434
+ }
435
+ if (this.autoRefresh && tokens.refresh_token && expiresAt !== null && Date.now() >= expiresAt - SESSION_REFRESH_SKEW_MS) {
436
+ try {
437
+ return await this.refreshSession(tokens.refresh_token);
438
+ }
439
+ catch (error) {
440
+ if (!hasStatus(error, 401) && cachedUser && Date.now() < expiresAt) {
441
+ return { user: cachedUser, tokens };
442
+ }
443
+ this.clearSession();
444
+ return null;
445
+ }
446
+ }
343
447
  try {
344
448
  const user = await this.currentUser(tokens.access_token);
345
449
  const session = { user, tokens };
@@ -419,9 +523,19 @@ export class BacletClient {
419
523
  accessToken,
420
524
  }).then((result) => result.user);
421
525
  }
422
- storageRequest(path, options = {}) {
423
- const accessToken = options.accessToken ?? this.readTokens()?.access_token;
424
- return this.request(path, { ...options, accessToken });
526
+ async storageRequest(path, options = {}) {
527
+ const tokens = this.readTokens();
528
+ const accessToken = options.accessToken ?? tokens?.access_token;
529
+ try {
530
+ return await this.request(path, { ...options, accessToken });
531
+ }
532
+ catch (error) {
533
+ if (!hasStatus(error, 401) || options.accessToken || !this.autoRefresh || !tokens?.refresh_token) {
534
+ throw error;
535
+ }
536
+ const session = await this.refreshSession(tokens.refresh_token);
537
+ return this.request(path, { ...options, accessToken: session.tokens.access_token });
538
+ }
425
539
  }
426
540
  async request(path, options = {}) {
427
541
  const headers = {
@@ -462,19 +576,41 @@ export class BacletClient {
462
576
  this.tokenStorage.removeItem(this.tokensKey);
463
577
  return tokens;
464
578
  }
579
+ readTokenExpiry() {
580
+ const value = Number(this.tokenStorage.getItem(this.expiresKey));
581
+ return Number.isFinite(value) && value > 0 ? value : null;
582
+ }
465
583
  writeSession(session) {
584
+ const expiresAt = Date.now() + Math.max(0, session.tokens.expires_in) * 1000;
466
585
  this.tokenStorage.setItem(this.tokensKey, JSON.stringify(session.tokens));
467
586
  this.tokenStorage.setItem(this.userKey, JSON.stringify(session.user));
587
+ this.tokenStorage.setItem(this.expiresKey, String(expiresAt));
468
588
  this.emit(session);
469
589
  }
470
590
  applySession(session) {
591
+ this.clearStorageCache();
471
592
  this.writeSession(session);
472
593
  }
473
594
  clearSession() {
474
595
  this.tokenStorage.removeItem(this.tokensKey);
475
596
  this.tokenStorage.removeItem(this.userKey);
597
+ this.tokenStorage.removeItem(this.expiresKey);
598
+ this.clearStorageCache();
476
599
  this.emit(null);
477
600
  }
601
+ clearStorageCache(bucket) {
602
+ if (!bucket) {
603
+ this.storageCache.clear();
604
+ return;
605
+ }
606
+ for (const key of this.storageCache.keys()) {
607
+ if (key.startsWith(`list${STORAGE_CACHE_SEPARATOR}${bucket}${STORAGE_CACHE_SEPARATOR}`) ||
608
+ key.startsWith(`info${STORAGE_CACHE_SEPARATOR}${bucket}${STORAGE_CACHE_SEPARATOR}`) ||
609
+ key.startsWith(`download${STORAGE_CACHE_SEPARATOR}${bucket}${STORAGE_CACHE_SEPARATOR}`)) {
610
+ this.storageCache.delete(key);
611
+ }
612
+ }
613
+ }
478
614
  emit(session) {
479
615
  for (const listener of this.listeners)
480
616
  listener(session);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baclet/sdk",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "BACLET users database SDK for browsers and servers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",