dserver-client 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.
@@ -0,0 +1,833 @@
1
+ import SparkMD5 from "spark-md5";
2
+ // src/types.ts
3
+ /**
4
+ * Error thrown by the dserver client
5
+ */
6
+ var DServerError = class extends Error {
7
+ constructor(message, status, statusText, body) {
8
+ super(message);
9
+ this.status = status;
10
+ this.statusText = statusText;
11
+ this.body = body;
12
+ this.name = "DServerError";
13
+ }
14
+ };
15
+ /**
16
+ * Error thrown when authentication fails
17
+ */
18
+ var AuthenticationError = class extends DServerError {
19
+ constructor(message = "Authentication failed", body) {
20
+ super(message, 401, "Unauthorized", body);
21
+ this.name = "AuthenticationError";
22
+ }
23
+ };
24
+ /**
25
+ * Error thrown when authorization fails
26
+ */
27
+ var AuthorizationError = class extends DServerError {
28
+ constructor(message = "Access denied", body) {
29
+ super(message, 403, "Forbidden", body);
30
+ this.name = "AuthorizationError";
31
+ }
32
+ };
33
+ /**
34
+ * Error thrown when a resource is not found
35
+ */
36
+ var NotFoundError = class extends DServerError {
37
+ constructor(message = "Resource not found", body) {
38
+ super(message, 404, "Not Found", body);
39
+ this.name = "NotFoundError";
40
+ }
41
+ };
42
+ // src/utils.ts
43
+ /**
44
+ * Parse an X-Pagination response header into a PaginationInfo.
45
+ *
46
+ * dservercore (flask-smorest) emits
47
+ * {"total", "total_pages", "first_page", "last_page", "page", "next_page"}
48
+ * — note: no "pages" or "per_page" fields. Other servers may emit
49
+ * {"total", "page", "per_page", "pages"} directly. Both shapes are
50
+ * normalized here; missing fields are derived from the requested page
51
+ * size and the number of returned items.
52
+ */
53
+ function parsePaginationHeader(headerValue, requestedPageSize, dataLength) {
54
+ let raw = {};
55
+ if (headerValue) try {
56
+ raw = JSON.parse(headerValue);
57
+ } catch {}
58
+ const total = typeof raw.total === "number" ? raw.total : dataLength;
59
+ const page = typeof raw.page === "number" ? raw.page : 1;
60
+ const per_page = typeof raw.per_page === "number" ? raw.per_page : requestedPageSize ?? dataLength;
61
+ let pages;
62
+ if (typeof raw.pages === "number") pages = raw.pages;
63
+ else if (typeof raw.total_pages === "number") pages = raw.total_pages;
64
+ else pages = per_page > 0 ? Math.ceil(total / per_page) : 1;
65
+ return {
66
+ total,
67
+ page,
68
+ per_page,
69
+ pages
70
+ };
71
+ }
72
+ /**
73
+ * Generate a SHA-1 hash of a string (item identifier from relpath)
74
+ * Uses the Web Crypto API which is available in browsers and Node.js 18+
75
+ */
76
+ async function generateIdentifier(relpath) {
77
+ const data = new TextEncoder().encode(relpath);
78
+ const hashBuffer = await crypto.subtle.digest("SHA-1", data);
79
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
80
+ }
81
+ /**
82
+ * Generate a UUID v4
83
+ */
84
+ function generateUUID() {
85
+ if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
86
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
87
+ const r = Math.random() * 16 | 0;
88
+ return (c === "x" ? r : r & 3 | 8).toString(16);
89
+ });
90
+ }
91
+ /**
92
+ * URL-encode a URI for use in API paths
93
+ */
94
+ function encodeUri(uri) {
95
+ return encodeURIComponent(uri);
96
+ }
97
+ /**
98
+ * Extract the subject (username) from a JWT without verifying it.
99
+ * Returns undefined for malformed tokens.
100
+ */
101
+ function getJwtSubject(token) {
102
+ const parts = token.split(".");
103
+ if (parts.length !== 3) return;
104
+ try {
105
+ const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
106
+ const payload = JSON.parse(atob(base64));
107
+ return typeof payload.sub === "string" ? payload.sub : void 0;
108
+ } catch {
109
+ return;
110
+ }
111
+ }
112
+ /**
113
+ * Get current Unix timestamp
114
+ */
115
+ function getCurrentTimestamp() {
116
+ return Math.floor(Date.now() / 1e3);
117
+ }
118
+ /**
119
+ * Parse ISO timestamp to Unix timestamp
120
+ */
121
+ function parseISOTimestamp(isoString) {
122
+ return Math.floor(new Date(isoString).getTime() / 1e3);
123
+ }
124
+ /**
125
+ * Check if a signed URL has expired
126
+ */
127
+ function isExpired(expiryTimestamp) {
128
+ const expiry = parseISOTimestamp(expiryTimestamp);
129
+ return getCurrentTimestamp() >= expiry;
130
+ }
131
+ /**
132
+ * Calculate remaining time until expiry in seconds
133
+ */
134
+ function timeUntilExpiry(expiryTimestamp) {
135
+ const expiry = parseISOTimestamp(expiryTimestamp);
136
+ const now = getCurrentTimestamp();
137
+ return Math.max(0, expiry - now);
138
+ }
139
+ /**
140
+ * Format bytes to human-readable string
141
+ */
142
+ function formatBytes(bytes, decimals = 2) {
143
+ if (bytes === 0) return "0 Bytes";
144
+ const k = 1024;
145
+ const dm = decimals < 0 ? 0 : decimals;
146
+ const sizes = [
147
+ "Bytes",
148
+ "KB",
149
+ "MB",
150
+ "GB",
151
+ "TB",
152
+ "PB"
153
+ ];
154
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
155
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
156
+ }
157
+ /**
158
+ * Create a delay promise (useful for rate limiting)
159
+ */
160
+ function delay(ms) {
161
+ return new Promise((resolve) => setTimeout(resolve, ms));
162
+ }
163
+ /**
164
+ * Retry a function with exponential backoff
165
+ */
166
+ async function withRetry(fn, options = {}) {
167
+ const { maxRetries = 3, initialDelay = 1e3, maxDelay = 3e4, backoffFactor = 2 } = options;
168
+ let lastError;
169
+ let currentDelay = initialDelay;
170
+ for (let attempt = 0; attempt <= maxRetries; attempt++) try {
171
+ return await fn();
172
+ } catch (error) {
173
+ lastError = error;
174
+ const status = error.status;
175
+ if (lastError.name === "AbortError" || typeof status === "number" && status >= 400 && status < 500) throw lastError;
176
+ if (attempt < maxRetries) {
177
+ await delay(currentDelay);
178
+ currentDelay = Math.min(currentDelay * backoffFactor, maxDelay);
179
+ }
180
+ }
181
+ throw lastError;
182
+ }
183
+ /**
184
+ * Chunk an array into smaller arrays
185
+ */
186
+ function chunk(array, size) {
187
+ const chunks = [];
188
+ for (let i = 0; i < array.length; i += size) chunks.push(array.slice(i, i + size));
189
+ return chunks;
190
+ }
191
+ /**
192
+ * Run promises with concurrency limit
193
+ */
194
+ async function parallelLimit(items, limit, fn) {
195
+ const results = [];
196
+ const executing = /* @__PURE__ */ new Set();
197
+ for (const item of items) {
198
+ const p = Promise.resolve().then(() => fn(item));
199
+ results.push(p);
200
+ const e = p.then(() => void 0, () => void 0).then(() => {
201
+ executing.delete(e);
202
+ });
203
+ executing.add(e);
204
+ if (executing.size >= limit) await Promise.race(executing);
205
+ }
206
+ const settled = await Promise.allSettled(results);
207
+ const firstRejected = settled.find((s) => s.status === "rejected");
208
+ if (firstRejected) throw firstRejected.reason;
209
+ return settled.map((s) => s.value);
210
+ }
211
+ // src/client.ts
212
+ /**
213
+ * DServer Client - TypeScript client for dserver signed URL API
214
+ */
215
+ /** Page size for fetching dependency graphs (the server's maximum). */
216
+ const GRAPH_PAGE_SIZE = 100;
217
+ /**
218
+ * Pull a human-readable message out of a dserver error body, if present.
219
+ */
220
+ function extractErrorMessage(errorBody) {
221
+ if (typeof errorBody === "string" && errorBody.trim()) return errorBody;
222
+ if (errorBody && typeof errorBody === "object") {
223
+ const body = errorBody;
224
+ for (const key of [
225
+ "message",
226
+ "error",
227
+ "description",
228
+ "msg"
229
+ ]) if (typeof body[key] === "string" && body[key].trim()) return body[key];
230
+ }
231
+ }
232
+ /**
233
+ * Client for interacting with dserver's signed URL API
234
+ *
235
+ * @example
236
+ * ```typescript
237
+ * const client = new DServerClient({
238
+ * baseUrl: "http://localhost:5000",
239
+ * token: "your-jwt-token"
240
+ * });
241
+ *
242
+ * // Get signed URLs for a dataset
243
+ * const urls = await client.getDatasetSignedUrls("s3://bucket/uuid");
244
+ *
245
+ * // Download an item
246
+ * const content = await client.downloadItem(urls, "item-identifier");
247
+ * ```
248
+ */
249
+ var DServerClient = class {
250
+ constructor(config) {
251
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
252
+ this.token = config.token;
253
+ this.fetchImpl = config.fetch ?? fetch.bind(globalThis);
254
+ }
255
+ /**
256
+ * Set or update the authentication token
257
+ */
258
+ setToken(token) {
259
+ this.token = token;
260
+ }
261
+ /**
262
+ * Get authorization headers
263
+ */
264
+ getHeaders() {
265
+ const headers = { "Content-Type": "application/json" };
266
+ if (this.token) headers["Authorization"] = `Bearer ${this.token}`;
267
+ return headers;
268
+ }
269
+ /**
270
+ * Make an authenticated request to dserver
271
+ */
272
+ async request(method, path, body, signal) {
273
+ const url = `${this.baseUrl}${path}`;
274
+ const options = {
275
+ method,
276
+ headers: this.getHeaders(),
277
+ signal
278
+ };
279
+ if (body !== void 0) options.body = JSON.stringify(body);
280
+ const response = await this.fetchImpl(url, options);
281
+ if (!response.ok) return this.handleErrorResponse(response);
282
+ const text = await response.text();
283
+ return text ? JSON.parse(text) : void 0;
284
+ }
285
+ /**
286
+ * Get signed URLs for reading an entire dataset
287
+ *
288
+ * @param uri - Dataset URI (e.g., "s3://bucket/uuid")
289
+ * @returns Signed URLs for all dataset components
290
+ */
291
+ async getDatasetSignedUrls(uri) {
292
+ const encodedUri = encodeUri(uri);
293
+ return this.request("GET", `/signed-urls/dataset/${encodedUri}`);
294
+ }
295
+ /**
296
+ * Get a signed URL for a single dataset item
297
+ *
298
+ * @param uri - Dataset URI
299
+ * @param identifier - Item identifier (SHA-1 hash of relpath)
300
+ * @returns Signed URL for the item
301
+ */
302
+ async getItemSignedUrl(uri, identifier) {
303
+ const encodedUri = encodeUri(uri);
304
+ return this.request("GET", `/signed-urls/item/${encodedUri}/${identifier}`);
305
+ }
306
+ /**
307
+ * Get signed URLs for uploading a new dataset
308
+ *
309
+ * @param baseUri - Base URI (e.g., "s3://bucket")
310
+ * @param request - Upload request with UUID, name, and items
311
+ * @returns Signed URLs for uploading dataset components
312
+ */
313
+ async getUploadUrls(baseUri, request) {
314
+ const encodedBaseUri = encodeUri(baseUri);
315
+ return this.request("POST", `/signed-urls/upload/${encodedBaseUri}`, request);
316
+ }
317
+ /**
318
+ * Signal that a dataset upload is complete
319
+ *
320
+ * @param uri - Dataset URI
321
+ * @returns Registration result
322
+ */
323
+ async signalUploadComplete(uri) {
324
+ const request = { uri };
325
+ return this.request("POST", `/signed-urls/upload-complete`, request);
326
+ }
327
+ /**
328
+ * Download a dataset item using its signed URL
329
+ *
330
+ * @param urls - Signed URLs response from getDatasetSignedUrls
331
+ * @param identifier - Item identifier
332
+ * @param options - Download options
333
+ * @returns Item content as ArrayBuffer
334
+ */
335
+ async downloadItem(urls, identifier, options = {}) {
336
+ const itemUrl = urls.item_urls[identifier];
337
+ if (!itemUrl) throw new NotFoundError(`Item ${identifier} not found in dataset`);
338
+ const response = await this.fetchImpl(itemUrl, { signal: options.signal });
339
+ if (!response.ok) throw new DServerError(`Failed to download item: ${response.statusText}`, response.status);
340
+ if (options.onProgress && response.body) {
341
+ const reader = response.body.getReader();
342
+ const contentLength = Number(response.headers.get("Content-Length")) || 0;
343
+ const chunks = [];
344
+ let receivedLength = 0;
345
+ while (true) {
346
+ const { done, value } = await reader.read();
347
+ if (done) break;
348
+ chunks.push(value);
349
+ receivedLength += value.length;
350
+ options.onProgress(receivedLength, contentLength, identifier);
351
+ }
352
+ const result = new Uint8Array(receivedLength);
353
+ let position = 0;
354
+ for (const chunk of chunks) {
355
+ result.set(chunk, position);
356
+ position += chunk.length;
357
+ }
358
+ return result.buffer;
359
+ }
360
+ return response.arrayBuffer();
361
+ }
362
+ /**
363
+ * Download and parse the dataset manifest
364
+ *
365
+ * @param urls - Signed URLs response
366
+ * @returns Parsed manifest
367
+ */
368
+ async downloadManifest(urls) {
369
+ const response = await this.fetchImpl(urls.manifest_url);
370
+ if (!response.ok) throw new DServerError("Failed to download manifest", response.status);
371
+ return response.json();
372
+ }
373
+ /**
374
+ * Download and parse the dataset admin metadata
375
+ *
376
+ * @param urls - Signed URLs response
377
+ * @returns Parsed admin metadata
378
+ */
379
+ async downloadAdminMetadata(urls) {
380
+ const response = await this.fetchImpl(urls.admin_metadata_url);
381
+ if (!response.ok) throw new DServerError("Failed to download admin metadata", response.status);
382
+ return response.json();
383
+ }
384
+ /**
385
+ * Download the dataset README
386
+ *
387
+ * @param urls - Signed URLs response
388
+ * @returns README content as string
389
+ */
390
+ async downloadReadme(urls) {
391
+ const response = await this.fetchImpl(urls.readme_url);
392
+ if (!response.ok) throw new DServerError("Failed to download README", response.status);
393
+ return response.text();
394
+ }
395
+ /**
396
+ * Download an overlay
397
+ *
398
+ * @param urls - Signed URLs response
399
+ * @param overlayName - Name of the overlay
400
+ * @returns Overlay data
401
+ */
402
+ async downloadOverlay(urls, overlayName) {
403
+ const overlayUrl = urls.overlay_urls[overlayName];
404
+ if (!overlayUrl) throw new NotFoundError(`Overlay ${overlayName} not found`);
405
+ const response = await this.fetchImpl(overlayUrl);
406
+ if (!response.ok) throw new DServerError("Failed to download overlay", response.status);
407
+ return response.json();
408
+ }
409
+ /**
410
+ * Download an annotation
411
+ *
412
+ * @param urls - Signed URLs response
413
+ * @param annotationName - Name of the annotation
414
+ * @returns Annotation value
415
+ */
416
+ async downloadAnnotation(urls, annotationName) {
417
+ const annotationUrl = urls.annotation_urls[annotationName];
418
+ if (!annotationUrl) throw new NotFoundError(`Annotation ${annotationName} not found`);
419
+ const response = await this.fetchImpl(annotationUrl);
420
+ if (!response.ok) throw new DServerError("Failed to download annotation", response.status);
421
+ return response.json();
422
+ }
423
+ /**
424
+ * Create and upload a new dataset
425
+ *
426
+ * The server handles admin_metadata, manifest, structure, tags, and annotations
427
+ * directly based on metadata sent in the upload request. We only need to upload
428
+ * README and item files.
429
+ *
430
+ * @param baseUri - Base URI (e.g., "s3://bucket")
431
+ * @param name - Dataset name
432
+ * @param files - Files to upload
433
+ * @param options - Upload options (readme, tags, annotations)
434
+ * @returns Upload completion response
435
+ */
436
+ async createDataset(baseUri, name, files, options = {}) {
437
+ const uuid = generateUUID();
438
+ const creatorUsername = this.token && getJwtSubject(this.token) || "webapp-user";
439
+ const frozenAt = getCurrentTimestamp();
440
+ const itemsWithMetadata = await Promise.all(files.map(async (file) => {
441
+ const identifier = await generateIdentifier(file.relpath);
442
+ const { size, hash } = await this.computeItemMetadata(file);
443
+ return {
444
+ ...file,
445
+ identifier,
446
+ size_in_bytes: size,
447
+ hash,
448
+ utc_timestamp: frozenAt
449
+ };
450
+ }));
451
+ const uploadInfo = await this.getUploadUrls(baseUri, {
452
+ uuid,
453
+ name,
454
+ creator_username: creatorUsername,
455
+ frozen_at: frozenAt,
456
+ items: itemsWithMetadata.map((item) => ({
457
+ relpath: item.relpath,
458
+ size_in_bytes: item.size_in_bytes,
459
+ hash: item.hash,
460
+ utc_timestamp: item.utc_timestamp
461
+ })),
462
+ tags: options.tags,
463
+ annotations: options.annotations
464
+ });
465
+ const totalBytes = itemsWithMetadata.reduce((sum, item) => sum + item.size_in_bytes, 0);
466
+ let uploadedBytes = 0;
467
+ const readme = options.readme || "---\n";
468
+ await this.uploadText(uploadInfo.upload_urls.readme, readme, options.signal);
469
+ await parallelLimit(itemsWithMetadata, 4, async (item) => {
470
+ const uploadUrl = uploadInfo.upload_urls.items[item.identifier];
471
+ if (!uploadUrl) throw new DServerError(`No upload URL for item ${item.relpath}`, 500);
472
+ let body;
473
+ if (item.content instanceof Blob) body = item.content;
474
+ else if (item.content instanceof ArrayBuffer) body = item.content;
475
+ else body = item.content;
476
+ const response = await this.fetchImpl(uploadUrl.url, {
477
+ method: "PUT",
478
+ body,
479
+ headers: item.contentType ? { "Content-Type": item.contentType } : void 0,
480
+ signal: options.signal
481
+ });
482
+ if (!response.ok) throw new DServerError(`Failed to upload ${item.relpath}`, response.status);
483
+ uploadedBytes += item.size_in_bytes;
484
+ options.onProgress?.(uploadedBytes, totalBytes, item.relpath);
485
+ });
486
+ return this.signalUploadComplete(uploadInfo.uri);
487
+ }
488
+ /**
489
+ * Compute size and hash for a file item
490
+ */
491
+ async computeItemMetadata(item) {
492
+ let size;
493
+ let contentBuffer;
494
+ if (item.content instanceof Blob) {
495
+ size = item.content.size;
496
+ contentBuffer = await item.content.arrayBuffer();
497
+ } else if (item.content instanceof ArrayBuffer) {
498
+ size = item.content.byteLength;
499
+ contentBuffer = item.content;
500
+ } else {
501
+ const encoded = new TextEncoder().encode(item.content);
502
+ size = encoded.length;
503
+ contentBuffer = encoded.buffer;
504
+ }
505
+ const hash = SparkMD5.ArrayBuffer.hash(contentBuffer);
506
+ return {
507
+ size,
508
+ hash
509
+ };
510
+ }
511
+ /**
512
+ * Upload text data to a signed URL
513
+ */
514
+ async uploadText(url, text, signal) {
515
+ const response = await this.fetchImpl(url, {
516
+ method: "PUT",
517
+ body: text,
518
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
519
+ signal
520
+ });
521
+ if (!response.ok) throw new DServerError("Failed to upload text", response.status);
522
+ }
523
+ /**
524
+ * Get server configuration versions
525
+ */
526
+ async getServerVersions() {
527
+ return (await this.request("GET", "/config/versions")).versions;
528
+ }
529
+ /**
530
+ * Check server health (no auth required)
531
+ */
532
+ async checkHealth() {
533
+ const url = `${this.baseUrl}/config/health`;
534
+ const response = await this.fetchImpl(url);
535
+ if (!response.ok) throw new DServerError("Health check failed", response.status);
536
+ return response.json();
537
+ }
538
+ /**
539
+ * Get user summary info
540
+ */
541
+ async getUserSummary(username) {
542
+ return this.request("GET", `/users/${username}/summary`);
543
+ }
544
+ /**
545
+ * Get information on the currently authenticated user.
546
+ */
547
+ async getMe() {
548
+ return this.request("GET", "/me");
549
+ }
550
+ /**
551
+ * Get the summary for the currently authenticated user — no username needed.
552
+ */
553
+ async getMySummary() {
554
+ return this.request("GET", "/me/summary");
555
+ }
556
+ /**
557
+ * Search datasets with pagination
558
+ */
559
+ async searchDatasets(query, pagination) {
560
+ const params = new URLSearchParams();
561
+ if (pagination?.page) params.set("page", String(pagination.page));
562
+ if (pagination?.page_size) params.set("page_size", String(pagination.page_size));
563
+ if (pagination?.sort) params.set("sort", pagination.sort);
564
+ const queryString = params.toString();
565
+ const path = `/uris${queryString ? `?${queryString}` : ""}`;
566
+ const url = `${this.baseUrl}${path}`;
567
+ const response = await this.fetchImpl(url, {
568
+ method: "POST",
569
+ headers: this.getHeaders(),
570
+ body: JSON.stringify(query)
571
+ });
572
+ if (!response.ok) await this.handleErrorResponse(response);
573
+ const data = await response.json();
574
+ return {
575
+ data,
576
+ pagination: parsePaginationHeader(response.headers.get("x-pagination"), pagination?.page_size, data.length)
577
+ };
578
+ }
579
+ /**
580
+ * Read the error body and throw a typed error carrying the server's
581
+ * message so callers can surface the actual reason for the failure.
582
+ */
583
+ async handleErrorResponse(response) {
584
+ const text = await response.text();
585
+ let errorBody = text;
586
+ try {
587
+ errorBody = JSON.parse(text);
588
+ } catch {}
589
+ const serverMessage = extractErrorMessage(errorBody);
590
+ switch (response.status) {
591
+ case 401: throw new AuthenticationError(serverMessage, errorBody);
592
+ case 403: throw new AuthorizationError(serverMessage, errorBody);
593
+ case 404: throw new NotFoundError(serverMessage, errorBody);
594
+ default: throw new DServerError(serverMessage ?? `Request failed: ${response.statusText}`, response.status, response.statusText, errorBody);
595
+ }
596
+ }
597
+ /**
598
+ * Get manifest for a dataset
599
+ */
600
+ async getManifest(uri) {
601
+ const encodedUri = encodeURIComponent(uri);
602
+ return this.request("GET", `/manifests/${encodedUri}`);
603
+ }
604
+ /**
605
+ * Get readme for a dataset
606
+ */
607
+ async getReadme(uri) {
608
+ const encodedUri = encodeURIComponent(uri);
609
+ return this.request("GET", `/readmes/${encodedUri}`);
610
+ }
611
+ /**
612
+ * Set readme for a dataset
613
+ */
614
+ async setReadme(uri, content) {
615
+ const encodedUri = encodeURIComponent(uri);
616
+ return this.request("PUT", `/readmes/${encodedUri}`, { readme: content });
617
+ }
618
+ /**
619
+ * Get tags for a dataset
620
+ */
621
+ async getTags(uri) {
622
+ const encodedUri = encodeURIComponent(uri);
623
+ return this.request("GET", `/tags/${encodedUri}`);
624
+ }
625
+ /**
626
+ * Set all tags for a dataset (replaces existing)
627
+ */
628
+ async setTags(uri, tags) {
629
+ const encodedUri = encodeURIComponent(uri);
630
+ return this.request("PUT", `/tags/${encodedUri}`, { tags });
631
+ }
632
+ /**
633
+ * Add a single tag to a dataset
634
+ */
635
+ async addTag(uri, tag) {
636
+ const encodedUri = encodeURIComponent(uri);
637
+ const encodedTag = encodeURIComponent(tag);
638
+ return this.request("POST", `/tags/${encodedUri}/${encodedTag}`, {});
639
+ }
640
+ /**
641
+ * Remove a single tag from a dataset
642
+ */
643
+ async removeTag(uri, tag) {
644
+ const encodedUri = encodeURIComponent(uri);
645
+ const encodedTag = encodeURIComponent(tag);
646
+ return this.request("DELETE", `/tags/${encodedUri}/${encodedTag}`);
647
+ }
648
+ /**
649
+ * Get annotations for a dataset
650
+ */
651
+ async getAnnotations(uri) {
652
+ const encodedUri = encodeURIComponent(uri);
653
+ return this.request("GET", `/annotations/${encodedUri}`);
654
+ }
655
+ /**
656
+ * Set all annotations for a dataset (replaces existing)
657
+ */
658
+ async setAnnotations(uri, annotations) {
659
+ const encodedUri = encodeURIComponent(uri);
660
+ return this.request("PUT", `/annotations/${encodedUri}`, { annotations });
661
+ }
662
+ /**
663
+ * Set a single annotation
664
+ */
665
+ async setAnnotation(uri, name, value) {
666
+ const encodedUri = encodeURIComponent(uri);
667
+ const encodedName = encodeURIComponent(name);
668
+ return this.request("PUT", `/annotations/${encodedUri}/${encodedName}`, { value });
669
+ }
670
+ /**
671
+ * Delete a single annotation
672
+ */
673
+ async deleteAnnotation(uri, name) {
674
+ const encodedUri = encodeURIComponent(uri);
675
+ const encodedName = encodeURIComponent(name);
676
+ return this.request("DELETE", `/annotations/${encodedUri}/${encodedName}`);
677
+ }
678
+ /**
679
+ * Get current user info (includes is_admin flag)
680
+ */
681
+ async getCurrentUser() {
682
+ return this.request("GET", "/me");
683
+ }
684
+ /**
685
+ * List all users (admin only)
686
+ */
687
+ async listUsers() {
688
+ return this.request("GET", "/users");
689
+ }
690
+ /**
691
+ * Get a specific user
692
+ */
693
+ async getUser(username) {
694
+ const encodedUsername = encodeURIComponent(username);
695
+ return this.request("GET", `/users/${encodedUsername}`);
696
+ }
697
+ /**
698
+ * Create or register a new user (admin only)
699
+ * Note: dserver uses PUT for user creation/update (idempotent operation)
700
+ */
701
+ async createUser(username, options) {
702
+ const encodedUsername = encodeURIComponent(username);
703
+ return this.request("PUT", `/users/${encodedUsername}`, options || {});
704
+ }
705
+ /**
706
+ * Delete a user (admin only)
707
+ */
708
+ async deleteUser(username) {
709
+ const encodedUsername = encodeURIComponent(username);
710
+ await this.request("DELETE", `/users/${encodedUsername}`);
711
+ }
712
+ /**
713
+ * Update user fields (partial update, admin only)
714
+ *
715
+ * @param username - Username to update
716
+ * @param updates - Fields to update (is_admin, display_name)
717
+ * @returns Updated user info
718
+ */
719
+ async updateUser(username, updates) {
720
+ const encodedUsername = encodeURIComponent(username);
721
+ return this.request("PATCH", `/users/${encodedUsername}`, updates);
722
+ }
723
+ /**
724
+ * Update user admin status (admin only)
725
+ * @deprecated Use updateUser() instead for more flexibility
726
+ */
727
+ async updateUserAdmin(username, isAdmin) {
728
+ return this.updateUser(username, { is_admin: isAdmin });
729
+ }
730
+ /**
731
+ * List all base URIs (admin only)
732
+ */
733
+ async listBaseURIs() {
734
+ return this.request("GET", "/base-uris");
735
+ }
736
+ /**
737
+ * Get a specific base URI
738
+ */
739
+ async getBaseURI(baseUri) {
740
+ const encodedUri = encodeURIComponent(baseUri);
741
+ return this.request("GET", `/base-uris/${encodedUri}`);
742
+ }
743
+ /**
744
+ * Register a new base URI (admin only)
745
+ */
746
+ async createBaseURI(baseUri) {
747
+ const encodedUri = encodeURIComponent(baseUri);
748
+ return this.request("POST", `/base-uris/${encodedUri}`, {});
749
+ }
750
+ /**
751
+ * Delete a base URI (admin only)
752
+ */
753
+ async deleteBaseURI(baseUri) {
754
+ const encodedUri = encodeURIComponent(baseUri);
755
+ await this.request("DELETE", `/base-uris/${encodedUri}`);
756
+ }
757
+ /**
758
+ * Grant search permission to a user on a base URI (admin only)
759
+ */
760
+ async grantSearchPermission(username, baseUri) {
761
+ const encodedUsername = encodeURIComponent(username);
762
+ const encodedUri = encodeURIComponent(baseUri);
763
+ return this.request("POST", `/users/${encodedUsername}/search/${encodedUri}`, {});
764
+ }
765
+ /**
766
+ * Revoke search permission from a user on a base URI (admin only)
767
+ */
768
+ async revokeSearchPermission(username, baseUri) {
769
+ const encodedUsername = encodeURIComponent(username);
770
+ const encodedUri = encodeURIComponent(baseUri);
771
+ return this.request("DELETE", `/users/${encodedUsername}/search/${encodedUri}`);
772
+ }
773
+ /**
774
+ * Grant register permission to a user on a base URI (admin only)
775
+ */
776
+ async grantRegisterPermission(username, baseUri) {
777
+ const encodedUsername = encodeURIComponent(username);
778
+ const encodedUri = encodeURIComponent(baseUri);
779
+ return this.request("POST", `/users/${encodedUsername}/register/${encodedUri}`, {});
780
+ }
781
+ /**
782
+ * Revoke register permission from a user on a base URI (admin only)
783
+ */
784
+ async revokeRegisterPermission(username, baseUri) {
785
+ const encodedUsername = encodeURIComponent(username);
786
+ const encodedUri = encodeURIComponent(baseUri);
787
+ return this.request("DELETE", `/users/${encodedUsername}/register/${encodedUri}`);
788
+ }
789
+ /**
790
+ * Get datasets by UUID
791
+ * Returns all instances of a dataset with that UUID across base URIs the user has access to
792
+ *
793
+ * @param uuid - Dataset UUID
794
+ * @returns Array of datasets with that UUID
795
+ */
796
+ async getDatasetsByUuid(uuid) {
797
+ return this.request("GET", `/uuids/${encodeURIComponent(uuid)}`);
798
+ }
799
+ /**
800
+ * Get the dependency graph of a dataset by UUID
801
+ * Returns all datasets in the same dependency graph (bidirectional traversal),
802
+ * fetching every page of the paginated response.
803
+ * Requires dserver-dependency-graph-plugin to be installed
804
+ *
805
+ * @param uuid - Dataset UUID
806
+ * @param dependencyKeys - Optional custom dependency keys (e.g.,
807
+ * ["readme_parsed.derived_from.uuid"]); honored only if the server allows
808
+ * dynamic dependency keys. Omit to use the server's keys.
809
+ * @returns Datasets in the dependency graph, each with derived_from: the
810
+ * UUIDs of its parents within the graph
811
+ */
812
+ async getDependencyGraph(uuid, dependencyKeys) {
813
+ const encodedUuid = encodeURIComponent(uuid);
814
+ const custom = dependencyKeys !== void 0 && dependencyKeys.length > 0;
815
+ const datasets = [];
816
+ for (let page = 1;; page++) {
817
+ const url = `${this.baseUrl}/graph/uuids/${encodedUuid}?page=${page}&page_size=${GRAPH_PAGE_SIZE}`;
818
+ const response = await this.fetchImpl(url, {
819
+ method: custom ? "POST" : "GET",
820
+ headers: this.getHeaders(),
821
+ body: custom ? JSON.stringify({ dependency_keys: dependencyKeys }) : void 0
822
+ });
823
+ if (!response.ok) await this.handleErrorResponse(response);
824
+ const data = await response.json();
825
+ datasets.push(...data);
826
+ const { pages } = parsePaginationHeader(response.headers.get("x-pagination"), GRAPH_PAGE_SIZE, data.length);
827
+ if (page >= pages || data.length === 0) return datasets;
828
+ }
829
+ }
830
+ };
831
+ export { DServerError as _, formatBytes as a, getCurrentTimestamp as c, parseISOTimestamp as d, parsePaginationHeader as f, AuthorizationError as g, AuthenticationError as h, encodeUri as i, isExpired as l, withRetry as m, chunk as n, generateIdentifier as o, timeUntilExpiry as p, delay as r, generateUUID as s, DServerClient as t, parallelLimit as u, NotFoundError as v };
832
+
833
+ //# sourceMappingURL=client.mjs.map