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