get-db9 0.5.0 → 0.6.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/dist/client.cjs CHANGED
@@ -278,6 +278,239 @@ function defaultCredentialStore() {
278
278
  return new FileCredentialStore();
279
279
  }
280
280
 
281
+ // src/ws.ts
282
+ var FsError = class extends Error {
283
+ code;
284
+ constructor(code, message) {
285
+ super(message);
286
+ this.name = "FsError";
287
+ this.code = code;
288
+ }
289
+ };
290
+ var nextId = 1;
291
+ function nextRequestId() {
292
+ return String(nextId++);
293
+ }
294
+ function toBase64(data) {
295
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
296
+ if (typeof Buffer !== "undefined") {
297
+ return Buffer.from(bytes).toString("base64");
298
+ }
299
+ let binary = "";
300
+ for (let i = 0; i < bytes.length; i++) {
301
+ binary += String.fromCharCode(bytes[i]);
302
+ }
303
+ return btoa(binary);
304
+ }
305
+ function fromBase64(b64) {
306
+ if (typeof Buffer !== "undefined") {
307
+ return new Uint8Array(Buffer.from(b64, "base64"));
308
+ }
309
+ const binary = atob(b64);
310
+ const bytes = new Uint8Array(binary.length);
311
+ for (let i = 0; i < binary.length; i++) {
312
+ bytes[i] = binary.charCodeAt(i);
313
+ }
314
+ return bytes;
315
+ }
316
+ var FsClient = class _FsClient {
317
+ ws;
318
+ pending = /* @__PURE__ */ new Map();
319
+ closed = false;
320
+ constructor(ws) {
321
+ this.ws = ws;
322
+ ws.onmessage = (ev) => {
323
+ const text = typeof ev.data === "string" ? ev.data : String(ev.data);
324
+ let resp;
325
+ try {
326
+ resp = JSON.parse(text);
327
+ } catch {
328
+ return;
329
+ }
330
+ const p = this.pending.get(resp.id);
331
+ if (p) {
332
+ this.pending.delete(resp.id);
333
+ p.resolve(resp);
334
+ }
335
+ };
336
+ ws.onclose = () => {
337
+ this.closed = true;
338
+ for (const [, p] of this.pending) {
339
+ p.reject(new FsError("CONNECTION_CLOSED", "WebSocket connection closed"));
340
+ }
341
+ this.pending.clear();
342
+ };
343
+ ws.onerror = () => {
344
+ };
345
+ }
346
+ /**
347
+ * Connect to an fs9 WebSocket server.
348
+ *
349
+ * @param url WebSocket URL, e.g. `wss://host:5480`
350
+ * @param WS WebSocket constructor (native or from `ws` package)
351
+ */
352
+ static connect(url, WS) {
353
+ return new Promise((resolve, reject) => {
354
+ const ws = new WS(url);
355
+ ws.onopen = () => {
356
+ ws.onopen = null;
357
+ ws.onerror = null;
358
+ resolve(new _FsClient(ws));
359
+ };
360
+ ws.onerror = (ev) => {
361
+ ws.onopen = null;
362
+ ws.onerror = null;
363
+ const msg = ev && typeof ev === "object" && "message" in ev ? String(ev.message) : "WebSocket connection failed";
364
+ reject(new FsError("CONNECTION_ERROR", msg));
365
+ };
366
+ });
367
+ }
368
+ /** Authenticate with the server. Must be called first after connect. */
369
+ async authenticate(username, password) {
370
+ const resp = await this.sendAndRecv({
371
+ id: nextRequestId(),
372
+ op: "auth",
373
+ username,
374
+ password
375
+ });
376
+ if (!resp.ok) {
377
+ throw new FsError("AUTH_FAILED", this.errorMessage(resp));
378
+ }
379
+ const data = resp.data;
380
+ return {
381
+ user: String(data?.user ?? ""),
382
+ tenant: String(data?.tenant ?? ""),
383
+ keyspace: String(data?.keyspace ?? "")
384
+ };
385
+ }
386
+ /** Get file or directory metadata. */
387
+ async stat(path) {
388
+ const resp = await this.sendAndRecv({
389
+ id: nextRequestId(),
390
+ op: "stat",
391
+ path
392
+ });
393
+ this.expectOk(resp);
394
+ return resp.data;
395
+ }
396
+ /** List directory contents. */
397
+ async readdir(path) {
398
+ const resp = await this.sendAndRecv({
399
+ id: nextRequestId(),
400
+ op: "readdir",
401
+ path
402
+ });
403
+ this.expectOk(resp);
404
+ const data = resp.data;
405
+ return data?.entries ?? [];
406
+ }
407
+ /** Create a directory. Always recursive (mkdir -p). */
408
+ async mkdir(path, recursive = true) {
409
+ const resp = await this.sendAndRecv({
410
+ id: nextRequestId(),
411
+ op: "mkdir",
412
+ path,
413
+ recursive
414
+ });
415
+ this.expectOk(resp);
416
+ }
417
+ /** Read an entire file, returning raw bytes. */
418
+ async readFile(path) {
419
+ const resp = await this.sendAndRecv({
420
+ id: nextRequestId(),
421
+ op: "read",
422
+ path
423
+ });
424
+ this.expectOk(resp);
425
+ const data = resp.data;
426
+ const content = data?.content;
427
+ if (typeof content !== "string") {
428
+ throw new FsError("PROTOCOL", "missing content field in read response");
429
+ }
430
+ return fromBase64(content);
431
+ }
432
+ /** Write (overwrite) a file. Returns bytes written. */
433
+ async writeFile(path, data) {
434
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
435
+ const resp = await this.sendAndRecv({
436
+ id: nextRequestId(),
437
+ op: "write",
438
+ path,
439
+ content: toBase64(bytes),
440
+ encoding: "base64"
441
+ });
442
+ this.expectOk(resp);
443
+ const result = resp.data;
444
+ return result?.written ?? bytes.byteLength;
445
+ }
446
+ /** Append to a file. Returns bytes written. */
447
+ async appendFile(path, data) {
448
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
449
+ const resp = await this.sendAndRecv({
450
+ id: nextRequestId(),
451
+ op: "append",
452
+ path,
453
+ content: toBase64(bytes),
454
+ encoding: "base64"
455
+ });
456
+ this.expectOk(resp);
457
+ const result = resp.data;
458
+ return result?.written ?? bytes.byteLength;
459
+ }
460
+ /** Remove a file (non-recursive) or directory (recursive). */
461
+ async rm(path, recursive = false) {
462
+ const resp = await this.sendAndRecv(
463
+ recursive ? { id: nextRequestId(), op: "rm", path, recursive: true } : { id: nextRequestId(), op: "unlink", path }
464
+ );
465
+ this.expectOk(resp);
466
+ }
467
+ /** Rename (move) a file or directory. */
468
+ async rename(oldPath, newPath) {
469
+ const resp = await this.sendAndRecv({
470
+ id: nextRequestId(),
471
+ op: "rename",
472
+ old_path: oldPath,
473
+ new_path: newPath
474
+ });
475
+ this.expectOk(resp);
476
+ }
477
+ /** Gracefully close the WebSocket connection. */
478
+ async close() {
479
+ if (!this.closed) {
480
+ this.ws.close();
481
+ }
482
+ }
483
+ // ── internals ──────────────────────────────────────────────────
484
+ sendAndRecv(request) {
485
+ if (this.closed) {
486
+ return Promise.reject(new FsError("CONNECTION_CLOSED", "WebSocket is closed"));
487
+ }
488
+ return new Promise((resolve, reject) => {
489
+ const id = request.id;
490
+ this.pending.set(id, { resolve, reject });
491
+ try {
492
+ this.ws.send(JSON.stringify(request));
493
+ } catch (err) {
494
+ this.pending.delete(id);
495
+ reject(new FsError("CONNECTION_ERROR", String(err)));
496
+ }
497
+ });
498
+ }
499
+ expectOk(resp) {
500
+ if (!resp.ok) {
501
+ const detail = resp.error;
502
+ throw new FsError(
503
+ detail?.code ?? "UNKNOWN",
504
+ detail?.message ?? "unknown error"
505
+ );
506
+ }
507
+ }
508
+ errorMessage(resp) {
509
+ const detail = resp.error;
510
+ return detail ? `${detail.code}: ${detail.message}` : "unknown error";
511
+ }
512
+ };
513
+
281
514
  // src/client.ts
282
515
  function createDb9Client(options = {}) {
283
516
  const baseUrl = options.baseUrl ?? "https://db9.shared.aws.tidbcloud.com/api";
@@ -357,44 +590,42 @@ function createDb9Client(options = {}) {
357
590
  return operation(newClient);
358
591
  }
359
592
  }
360
- function deriveFs9Url(dbId) {
361
- const origin = baseUrl.replace(/\/api\/?$/, "");
362
- return `${origin}/fs9/${dbId}`;
363
- }
364
- function getFsClient(dbId) {
365
- const fs9Base = deriveFs9Url(dbId) + "/api/v1";
366
- return createHttpClient({
367
- baseUrl: fs9Base,
368
- fetch: options.fetch,
369
- headers: token ? { Authorization: `Bearer ${token}` } : {},
370
- timeout: options.timeout,
371
- maxRetries: options.maxRetries,
372
- retryDelay: options.retryDelay
373
- });
593
+ const fsWsPort = options.wsPort ?? 5480;
594
+ async function resolveFsConn(dbId) {
595
+ const creds = await withAuthRetry(
596
+ (client) => client.get(
597
+ `/customer/databases/${dbId}/credentials`
598
+ )
599
+ );
600
+ const connStr = creds.connection_string;
601
+ const hostMatch = connStr.match(/@([^:/?]+)/);
602
+ const host = hostMatch?.[1];
603
+ if (!host) {
604
+ throw new Error(`Cannot parse host from connection string for database '${dbId}'`);
605
+ }
606
+ const userMatch = connStr.match(/:\/\/([^:@]+)/);
607
+ const username = userMatch?.[1] ?? creds.admin_user;
608
+ const protocol = host === "localhost" || host === "127.0.0.1" ? "ws" : "wss";
609
+ return {
610
+ wsUrl: `${protocol}://${host}:${fsWsPort}`,
611
+ username,
612
+ password: creds.admin_password
613
+ };
374
614
  }
375
- async function withFsAuthRetry(dbId, operation) {
376
- if (!token && !tokenLoaded) {
377
- await getAuthClient();
615
+ async function withFsClient(dbId, operation) {
616
+ const WS = options.WebSocket ?? (typeof globalThis !== "undefined" ? globalThis.WebSocket : void 0);
617
+ if (!WS) {
618
+ throw new Error(
619
+ "WebSocket constructor not available. Pass `WebSocket` in Db9ClientOptions, or use Node 21+ / a browser environment with native WebSocket support, or install the `ws` package for Node 18\u201320."
620
+ );
378
621
  }
379
- const client = getFsClient(dbId);
622
+ const conn = await resolveFsConn(dbId);
623
+ const client = await FsClient.connect(conn.wsUrl, WS);
380
624
  try {
625
+ await client.authenticate(conn.username, conn.password);
381
626
  return await operation(client);
382
- } catch (err) {
383
- if (!(err instanceof Db9Error) || err.statusCode !== 401) {
384
- throw err;
385
- }
386
- try {
387
- if (!refreshPromise) {
388
- refreshPromise = refreshAnonymousToken();
389
- }
390
- await refreshPromise;
391
- } catch {
392
- throw err;
393
- } finally {
394
- refreshPromise = null;
395
- }
396
- const newClient = getFsClient(dbId);
397
- return operation(newClient);
627
+ } finally {
628
+ await client.close();
398
629
  }
399
630
  }
400
631
  function parseSqlError(raw) {
@@ -415,12 +646,6 @@ function createDb9Client(options = {}) {
415
646
  }
416
647
  return { message: raw };
417
648
  }
418
- async function fsStat(dbId, path) {
419
- return withFsAuthRetry(
420
- dbId,
421
- (client) => client.get("/stat", { path })
422
- );
423
- }
424
649
  async function fetchAnonymousSecret() {
425
650
  return withAuthRetry(
426
651
  (client) => client.post("/customer/anonymous-secret", {})
@@ -494,6 +719,11 @@ function createDb9Client(options = {}) {
494
719
  `/customer/databases/${databaseId}/reset-password`
495
720
  )
496
721
  ),
722
+ credentials: async (databaseId) => withAuthRetry(
723
+ (client) => client.get(
724
+ `/customer/databases/${databaseId}/credentials`
725
+ )
726
+ ),
497
727
  observability: async (databaseId) => withAuthRetry(
498
728
  (client) => client.get(
499
729
  `/customer/databases/${databaseId}/observability`
@@ -576,70 +806,84 @@ function createDb9Client(options = {}) {
576
806
  }
577
807
  },
578
808
  fs: {
579
- list: async (dbId, path, options2) => {
580
- const params = { path };
581
- if (options2?.recursive) params.recursive = "true";
582
- return withFsAuthRetry(
583
- dbId,
584
- (client) => client.get("/readdir", params)
585
- );
586
- },
587
- read: async (dbId, path) => {
588
- return withFsAuthRetry(dbId, async (client) => {
589
- const resp = await client.getRaw("/download", { path });
590
- return resp.text();
591
- });
592
- },
593
- readBinary: async (dbId, path) => {
594
- return withFsAuthRetry(dbId, async (client) => {
595
- const resp = await client.getRaw("/download", { path });
596
- return resp.arrayBuffer();
597
- });
809
+ /**
810
+ * Open a persistent WebSocket connection for multiple fs operations.
811
+ * Caller is responsible for calling `client.close()` when done.
812
+ */
813
+ connect: async (dbId) => {
814
+ const WS = options.WebSocket ?? (typeof globalThis !== "undefined" ? globalThis.WebSocket : void 0);
815
+ if (!WS) {
816
+ throw new Error(
817
+ "WebSocket constructor not available. Pass `WebSocket` in Db9ClientOptions, or use Node 21+ / a browser environment with native WebSocket support, or install the `ws` package for Node 18\u201320."
818
+ );
819
+ }
820
+ const conn = await resolveFsConn(dbId);
821
+ const client = await FsClient.connect(conn.wsUrl, WS);
822
+ await client.authenticate(conn.username, conn.password);
823
+ return client;
598
824
  },
825
+ /** List directory contents. */
826
+ list: async (dbId, path) => withFsClient(dbId, (client) => client.readdir(path)),
827
+ /** Read a file as text (UTF-8). */
828
+ read: async (dbId, path) => withFsClient(dbId, async (client) => {
829
+ const bytes = await client.readFile(path);
830
+ return new TextDecoder().decode(bytes);
831
+ }),
832
+ /** Read a file as raw bytes. */
833
+ readBinary: async (dbId, path) => withFsClient(dbId, (client) => client.readFile(path)),
834
+ /** Write (overwrite) a file. Accepts string, ArrayBuffer, or Uint8Array. */
599
835
  write: async (dbId, path, content) => {
600
- const contentType = typeof content === "string" ? "text/plain" : "application/octet-stream";
601
- await withFsAuthRetry(
602
- dbId,
603
- (client) => client.putRaw(`/upload?${new URLSearchParams({ path })}`, content, { "Content-Type": contentType })
604
- );
605
- },
606
- stat: (dbId, path) => {
607
- return fsStat(dbId, path);
836
+ await withFsClient(dbId, (client) => client.writeFile(path, content));
608
837
  },
838
+ /** Append to a file. Returns bytes written. */
839
+ append: async (dbId, path, content) => withFsClient(dbId, (client) => client.appendFile(path, content)),
840
+ /** Get file or directory metadata. */
841
+ stat: async (dbId, path) => withFsClient(dbId, (client) => client.stat(path)),
842
+ /** Check if a file or directory exists. */
609
843
  exists: async (dbId, path) => {
610
844
  try {
611
- await fsStat(dbId, path);
845
+ await withFsClient(dbId, (client) => client.stat(path));
612
846
  return true;
613
847
  } catch (err) {
614
- if (err instanceof Db9Error && err.statusCode === 404) {
848
+ if (err instanceof FsError && err.code === "ENOENT") {
615
849
  return false;
616
850
  }
617
851
  throw err;
618
852
  }
619
853
  },
854
+ /** Create a directory (recursive by default). */
620
855
  mkdir: async (dbId, path) => {
621
- await withFsAuthRetry(
622
- dbId,
623
- (client) => client.postRaw(`/mkdir?${new URLSearchParams({ path, recursive: "true" })}`)
624
- );
856
+ await withFsClient(dbId, (client) => client.mkdir(path, true));
625
857
  },
626
- remove: async (dbId, path) => {
627
- await withFsAuthRetry(
628
- dbId,
629
- (client) => client.delRaw("/remove", { path })
630
- );
858
+ /** Remove a file or directory. */
859
+ remove: async (dbId, path, opts) => {
860
+ await withFsClient(dbId, (client) => client.rm(path, opts?.recursive ?? false));
631
861
  },
632
- events: async (dbId, options2) => {
633
- const params = {};
634
- if (options2?.limit !== void 0) params.limit = String(options2.limit);
635
- if (options2?.offset !== void 0) params.offset = String(options2.offset);
636
- if (options2?.path) params.path = options2.path;
637
- if (options2?.type) params.type = options2.type;
638
- return withFsAuthRetry(
639
- dbId,
640
- (client) => client.get("/events", params)
641
- );
862
+ /** Rename (move) a file or directory. */
863
+ rename: async (dbId, oldPath, newPath) => {
864
+ await withFsClient(dbId, (client) => client.rename(oldPath, newPath));
642
865
  }
866
+ },
867
+ // ── Device Auth Flow ─────────────────────────────────────────
868
+ deviceAuth: {
869
+ /** Start device code flow. Returns codes for user to authorize. */
870
+ createDeviceCode: () => publicClient.post("/customer/device-code"),
871
+ /** Poll for device token after user authorizes. Returns token or error status. */
872
+ pollDeviceToken: async (req) => {
873
+ try {
874
+ return await publicClient.post("/customer/device-token", req);
875
+ } catch (err) {
876
+ if (err instanceof Db9Error && err.statusCode === 400) {
877
+ const errorType = err.message;
878
+ if (errorType === "authorization_pending" || errorType === "expired_token" || errorType === "access_denied") {
879
+ return { error: errorType };
880
+ }
881
+ }
882
+ throw err;
883
+ }
884
+ },
885
+ /** Submit device verification with user credentials. */
886
+ verifyDevice: (req) => publicClient.post("/customer/device-verify", req)
643
887
  }
644
888
  };
645
889
  }