@arke-institute/sdk 2.0.0 → 2.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/index.js CHANGED
@@ -9,9 +9,9 @@ var DEFAULT_CONFIG = {
9
9
 
10
10
  // src/client/errors.ts
11
11
  var ArkeError = class extends Error {
12
- constructor(message, code, status, details) {
12
+ constructor(message, code2, status, details) {
13
13
  super(message);
14
- this.code = code;
14
+ this.code = code2;
15
15
  this.status = status;
16
16
  this.details = details;
17
17
  this.name = "ArkeError";
@@ -150,6 +150,532 @@ function createArkeClient(config) {
150
150
  return new ArkeClient(config);
151
151
  }
152
152
 
153
+ // src/operations/upload/cid.ts
154
+ import { CID } from "multiformats/cid";
155
+ import { sha256 } from "multiformats/hashes/sha2";
156
+ import * as raw from "multiformats/codecs/raw";
157
+ async function computeCid(data) {
158
+ let bytes;
159
+ if (data instanceof Blob) {
160
+ const buffer = await data.arrayBuffer();
161
+ bytes = new Uint8Array(buffer);
162
+ } else if (data instanceof ArrayBuffer) {
163
+ bytes = new Uint8Array(data);
164
+ } else {
165
+ bytes = data;
166
+ }
167
+ const hash = await sha256.digest(bytes);
168
+ const cid = CID.create(1, raw.code, hash);
169
+ return cid.toString();
170
+ }
171
+
172
+ // src/operations/upload/engine.ts
173
+ async function parallelLimit(items, concurrency, fn) {
174
+ const results = [];
175
+ let index = 0;
176
+ async function worker() {
177
+ while (index < items.length) {
178
+ const currentIndex = index++;
179
+ const item = items[currentIndex];
180
+ results[currentIndex] = await fn(item, currentIndex);
181
+ }
182
+ }
183
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());
184
+ await Promise.all(workers);
185
+ return results;
186
+ }
187
+ function getParentPath(relativePath) {
188
+ const lastSlash = relativePath.lastIndexOf("/");
189
+ if (lastSlash === -1) return null;
190
+ return relativePath.slice(0, lastSlash);
191
+ }
192
+ async function uploadTree(client, tree, options) {
193
+ const { target, onProgress, concurrency = 5, continueOnError = false, note } = options;
194
+ const errors = [];
195
+ const createdFolders = [];
196
+ const createdFiles = [];
197
+ const reportProgress = (progress) => {
198
+ if (onProgress) {
199
+ onProgress({
200
+ phase: "scanning",
201
+ totalFiles: tree.files.length,
202
+ completedFiles: 0,
203
+ totalFolders: tree.folders.length,
204
+ completedFolders: 0,
205
+ ...progress
206
+ });
207
+ }
208
+ };
209
+ try {
210
+ let collectionId;
211
+ let collectionCid;
212
+ let collectionCreated = false;
213
+ if (target.createCollection) {
214
+ reportProgress({ phase: "scanning", currentFolder: "Creating collection..." });
215
+ const collectionBody = {
216
+ label: target.createCollection.label,
217
+ description: target.createCollection.description,
218
+ roles: target.createCollection.roles,
219
+ note
220
+ };
221
+ const { data, error } = await client.api.POST("/collections", {
222
+ body: collectionBody
223
+ });
224
+ if (error || !data) {
225
+ throw new Error(`Failed to create collection: ${JSON.stringify(error)}`);
226
+ }
227
+ collectionId = data.id;
228
+ collectionCid = data.cid;
229
+ collectionCreated = true;
230
+ } else if (target.collectionId) {
231
+ collectionId = target.collectionId;
232
+ const { data, error } = await client.api.GET("/collections/{id}", {
233
+ params: { path: { id: collectionId } }
234
+ });
235
+ if (error || !data) {
236
+ throw new Error(`Failed to fetch collection: ${JSON.stringify(error)}`);
237
+ }
238
+ collectionCid = data.cid;
239
+ } else {
240
+ throw new Error("Must provide either collectionId or createCollection in target");
241
+ }
242
+ const rootParentId = target.parentId ?? collectionId;
243
+ reportProgress({
244
+ phase: "computing-cids",
245
+ totalFiles: tree.files.length,
246
+ completedFiles: 0
247
+ });
248
+ const preparedFiles = [];
249
+ let cidProgress = 0;
250
+ await parallelLimit(tree.files, concurrency, async (file) => {
251
+ try {
252
+ const data = await file.getData();
253
+ const cid = await computeCid(data);
254
+ preparedFiles.push({
255
+ ...file,
256
+ cid
257
+ });
258
+ cidProgress++;
259
+ reportProgress({
260
+ phase: "computing-cids",
261
+ completedFiles: cidProgress,
262
+ currentFile: file.relativePath
263
+ });
264
+ } catch (err) {
265
+ const errorMsg = err instanceof Error ? err.message : String(err);
266
+ if (continueOnError) {
267
+ errors.push({ path: file.relativePath, error: `CID computation failed: ${errorMsg}` });
268
+ } else {
269
+ throw new Error(`Failed to compute CID for ${file.relativePath}: ${errorMsg}`);
270
+ }
271
+ }
272
+ });
273
+ reportProgress({
274
+ phase: "creating-folders",
275
+ totalFolders: tree.folders.length,
276
+ completedFolders: 0
277
+ });
278
+ const sortedFolders = [...tree.folders].sort(
279
+ (a, b) => a.relativePath.split("/").length - b.relativePath.split("/").length
280
+ );
281
+ for (let i = 0; i < sortedFolders.length; i++) {
282
+ const folder = sortedFolders[i];
283
+ try {
284
+ const folderBody = {
285
+ label: folder.name,
286
+ collection: collectionId,
287
+ note
288
+ };
289
+ const { data, error } = await client.api.POST("/folders", {
290
+ body: folderBody
291
+ });
292
+ if (error || !data) {
293
+ throw new Error(JSON.stringify(error));
294
+ }
295
+ createdFolders.push({
296
+ name: folder.name,
297
+ relativePath: folder.relativePath,
298
+ id: data.id,
299
+ entityCid: data.cid
300
+ });
301
+ reportProgress({
302
+ phase: "creating-folders",
303
+ completedFolders: i + 1,
304
+ currentFolder: folder.relativePath
305
+ });
306
+ } catch (err) {
307
+ const errorMsg = err instanceof Error ? err.message : String(err);
308
+ if (continueOnError) {
309
+ errors.push({ path: folder.relativePath, error: `Folder creation failed: ${errorMsg}` });
310
+ } else {
311
+ throw new Error(`Failed to create folder ${folder.relativePath}: ${errorMsg}`);
312
+ }
313
+ }
314
+ }
315
+ const folderPathToEntity = /* @__PURE__ */ new Map();
316
+ for (const folder of createdFolders) {
317
+ folderPathToEntity.set(folder.relativePath, folder);
318
+ }
319
+ reportProgress({
320
+ phase: "creating-files",
321
+ totalFiles: preparedFiles.length,
322
+ completedFiles: 0
323
+ });
324
+ let fileCreateProgress = 0;
325
+ await parallelLimit(preparedFiles, concurrency, async (file) => {
326
+ try {
327
+ const fileBody = {
328
+ key: file.cid,
329
+ // Use CID as storage key (best practice)
330
+ filename: file.name,
331
+ content_type: file.mimeType,
332
+ size: file.size,
333
+ cid: file.cid,
334
+ collection: collectionId
335
+ };
336
+ const { data, error } = await client.api.POST("/files", {
337
+ body: fileBody
338
+ });
339
+ if (error || !data) {
340
+ throw new Error(JSON.stringify(error));
341
+ }
342
+ createdFiles.push({
343
+ ...file,
344
+ id: data.id,
345
+ entityCid: data.cid,
346
+ uploadUrl: data.upload_url,
347
+ uploadExpiresAt: data.upload_expires_at
348
+ });
349
+ fileCreateProgress++;
350
+ reportProgress({
351
+ phase: "creating-files",
352
+ completedFiles: fileCreateProgress,
353
+ currentFile: file.relativePath
354
+ });
355
+ } catch (err) {
356
+ const errorMsg = err instanceof Error ? err.message : String(err);
357
+ if (continueOnError) {
358
+ errors.push({ path: file.relativePath, error: `File creation failed: ${errorMsg}` });
359
+ } else {
360
+ throw new Error(`Failed to create file ${file.relativePath}: ${errorMsg}`);
361
+ }
362
+ }
363
+ });
364
+ const totalBytes = createdFiles.reduce((sum, f) => sum + f.size, 0);
365
+ let bytesUploaded = 0;
366
+ reportProgress({
367
+ phase: "uploading-content",
368
+ totalFiles: createdFiles.length,
369
+ completedFiles: 0,
370
+ totalBytes,
371
+ bytesUploaded: 0
372
+ });
373
+ let uploadProgress = 0;
374
+ await parallelLimit(createdFiles, concurrency, async (file) => {
375
+ try {
376
+ const data = await file.getData();
377
+ let body;
378
+ if (data instanceof Blob) {
379
+ body = data;
380
+ } else if (data instanceof Uint8Array) {
381
+ const arrayBuffer = new ArrayBuffer(data.byteLength);
382
+ new Uint8Array(arrayBuffer).set(data);
383
+ body = new Blob([arrayBuffer], { type: file.mimeType });
384
+ } else {
385
+ body = new Blob([data], { type: file.mimeType });
386
+ }
387
+ const response = await fetch(file.uploadUrl, {
388
+ method: "PUT",
389
+ body,
390
+ headers: {
391
+ "Content-Type": file.mimeType
392
+ }
393
+ });
394
+ if (!response.ok) {
395
+ throw new Error(`Upload failed with status ${response.status}`);
396
+ }
397
+ bytesUploaded += file.size;
398
+ uploadProgress++;
399
+ reportProgress({
400
+ phase: "uploading-content",
401
+ completedFiles: uploadProgress,
402
+ currentFile: file.relativePath,
403
+ bytesUploaded,
404
+ totalBytes
405
+ });
406
+ } catch (err) {
407
+ const errorMsg = err instanceof Error ? err.message : String(err);
408
+ if (continueOnError) {
409
+ errors.push({ path: file.relativePath, error: `Upload failed: ${errorMsg}` });
410
+ } else {
411
+ throw new Error(`Failed to upload ${file.relativePath}: ${errorMsg}`);
412
+ }
413
+ }
414
+ });
415
+ reportProgress({ phase: "linking" });
416
+ const filePathToEntity = /* @__PURE__ */ new Map();
417
+ for (const file of createdFiles) {
418
+ filePathToEntity.set(file.relativePath, file);
419
+ }
420
+ const parentGroups = /* @__PURE__ */ new Map();
421
+ for (const folder of createdFolders) {
422
+ const parentPath = getParentPath(folder.relativePath);
423
+ let parentId;
424
+ if (parentPath === null) {
425
+ parentId = rootParentId;
426
+ } else {
427
+ const parentFolder = folderPathToEntity.get(parentPath);
428
+ if (!parentFolder) {
429
+ errors.push({
430
+ path: folder.relativePath,
431
+ error: `Parent folder not found: ${parentPath}`
432
+ });
433
+ continue;
434
+ }
435
+ parentId = parentFolder.id;
436
+ }
437
+ if (!parentGroups.has(parentId)) {
438
+ parentGroups.set(parentId, { folderId: parentId, children: [] });
439
+ }
440
+ parentGroups.get(parentId).children.push({ id: folder.id });
441
+ }
442
+ for (const file of createdFiles) {
443
+ const parentPath = getParentPath(file.relativePath);
444
+ let parentId;
445
+ if (parentPath === null) {
446
+ parentId = rootParentId;
447
+ } else {
448
+ const parentFolder = folderPathToEntity.get(parentPath);
449
+ if (!parentFolder) {
450
+ errors.push({
451
+ path: file.relativePath,
452
+ error: `Parent folder not found: ${parentPath}`
453
+ });
454
+ continue;
455
+ }
456
+ parentId = parentFolder.id;
457
+ }
458
+ if (!parentGroups.has(parentId)) {
459
+ parentGroups.set(parentId, { folderId: parentId, children: [] });
460
+ }
461
+ parentGroups.get(parentId).children.push({ id: file.id });
462
+ }
463
+ for (const [parentId, group] of parentGroups) {
464
+ if (group.children.length === 0) continue;
465
+ try {
466
+ let expectTip;
467
+ if (parentId === collectionId) {
468
+ const { data, error: error2 } = await client.api.GET("/collections/{id}", {
469
+ params: { path: { id: collectionId } }
470
+ });
471
+ if (error2 || !data) {
472
+ throw new Error(`Failed to fetch collection CID: ${JSON.stringify(error2)}`);
473
+ }
474
+ expectTip = data.cid;
475
+ } else {
476
+ const { data, error: error2 } = await client.api.GET("/folders/{id}", {
477
+ params: { path: { id: parentId } }
478
+ });
479
+ if (error2 || !data) {
480
+ throw new Error(`Failed to fetch folder CID: ${JSON.stringify(error2)}`);
481
+ }
482
+ expectTip = data.cid;
483
+ }
484
+ const bulkBody = {
485
+ expect_tip: expectTip,
486
+ children: group.children,
487
+ note
488
+ };
489
+ const { error } = await client.api.POST("/folders/{id}/children/bulk", {
490
+ params: { path: { id: parentId } },
491
+ body: bulkBody
492
+ });
493
+ if (error) {
494
+ throw new Error(JSON.stringify(error));
495
+ }
496
+ } catch (err) {
497
+ const errorMsg = err instanceof Error ? err.message : String(err);
498
+ if (continueOnError) {
499
+ errors.push({
500
+ path: `parent:${parentId}`,
501
+ error: `Bulk linking failed: ${errorMsg}`
502
+ });
503
+ } else {
504
+ throw new Error(`Failed to link children to ${parentId}: ${errorMsg}`);
505
+ }
506
+ }
507
+ }
508
+ reportProgress({ phase: "complete" });
509
+ const resultFolders = createdFolders.map((f) => ({
510
+ id: f.id,
511
+ cid: f.entityCid,
512
+ type: "folder",
513
+ relativePath: f.relativePath
514
+ }));
515
+ const resultFiles = createdFiles.map((f) => ({
516
+ id: f.id,
517
+ cid: f.entityCid,
518
+ type: "file",
519
+ relativePath: f.relativePath
520
+ }));
521
+ return {
522
+ success: errors.length === 0,
523
+ collection: {
524
+ id: collectionId,
525
+ cid: collectionCid,
526
+ created: collectionCreated
527
+ },
528
+ folders: resultFolders,
529
+ files: resultFiles,
530
+ errors
531
+ };
532
+ } catch (err) {
533
+ const errorMsg = err instanceof Error ? err.message : String(err);
534
+ reportProgress({
535
+ phase: "error",
536
+ error: errorMsg
537
+ });
538
+ return {
539
+ success: false,
540
+ collection: {
541
+ id: target.collectionId ?? "",
542
+ cid: "",
543
+ created: false
544
+ },
545
+ folders: createdFolders.map((f) => ({
546
+ id: f.id,
547
+ cid: f.entityCid,
548
+ type: "folder",
549
+ relativePath: f.relativePath
550
+ })),
551
+ files: createdFiles.map((f) => ({
552
+ id: f.id,
553
+ cid: f.entityCid,
554
+ type: "file",
555
+ relativePath: f.relativePath
556
+ })),
557
+ errors: [...errors, { path: "", error: errorMsg }]
558
+ };
559
+ }
560
+ }
561
+
562
+ // src/operations/upload/scanners.ts
563
+ function getMimeType(filename) {
564
+ const ext = filename.toLowerCase().split(".").pop() || "";
565
+ const mimeTypes = {
566
+ // Images
567
+ jpg: "image/jpeg",
568
+ jpeg: "image/jpeg",
569
+ png: "image/png",
570
+ gif: "image/gif",
571
+ webp: "image/webp",
572
+ svg: "image/svg+xml",
573
+ ico: "image/x-icon",
574
+ bmp: "image/bmp",
575
+ tiff: "image/tiff",
576
+ tif: "image/tiff",
577
+ // Documents
578
+ pdf: "application/pdf",
579
+ doc: "application/msword",
580
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
581
+ xls: "application/vnd.ms-excel",
582
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
583
+ ppt: "application/vnd.ms-powerpoint",
584
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
585
+ odt: "application/vnd.oasis.opendocument.text",
586
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
587
+ odp: "application/vnd.oasis.opendocument.presentation",
588
+ // Text
589
+ txt: "text/plain",
590
+ md: "text/markdown",
591
+ csv: "text/csv",
592
+ html: "text/html",
593
+ htm: "text/html",
594
+ css: "text/css",
595
+ xml: "text/xml",
596
+ rtf: "application/rtf",
597
+ // Code
598
+ js: "text/javascript",
599
+ mjs: "text/javascript",
600
+ ts: "text/typescript",
601
+ jsx: "text/javascript",
602
+ tsx: "text/typescript",
603
+ json: "application/json",
604
+ yaml: "text/yaml",
605
+ yml: "text/yaml",
606
+ // Archives
607
+ zip: "application/zip",
608
+ tar: "application/x-tar",
609
+ gz: "application/gzip",
610
+ rar: "application/vnd.rar",
611
+ "7z": "application/x-7z-compressed",
612
+ // Audio
613
+ mp3: "audio/mpeg",
614
+ wav: "audio/wav",
615
+ ogg: "audio/ogg",
616
+ m4a: "audio/mp4",
617
+ flac: "audio/flac",
618
+ // Video
619
+ mp4: "video/mp4",
620
+ webm: "video/webm",
621
+ avi: "video/x-msvideo",
622
+ mov: "video/quicktime",
623
+ mkv: "video/x-matroska",
624
+ // Fonts
625
+ woff: "font/woff",
626
+ woff2: "font/woff2",
627
+ ttf: "font/ttf",
628
+ otf: "font/otf",
629
+ // Other
630
+ wasm: "application/wasm"
631
+ };
632
+ return mimeTypes[ext] || "application/octet-stream";
633
+ }
634
+ async function scanDirectory(directoryPath, options = {}) {
635
+ const fs = await import("fs/promises");
636
+ const path = await import("path");
637
+ const { ignore = ["node_modules", ".git", ".DS_Store"], includeHidden = false } = options;
638
+ const files = [];
639
+ const folders = [];
640
+ const rootName = path.basename(directoryPath);
641
+ async function scanDir(dirPath, relativePath) {
642
+ const entries = await fs.readdir(dirPath, { withFileTypes: true });
643
+ for (const entry of entries) {
644
+ const name = entry.name;
645
+ if (!includeHidden && name.startsWith(".")) {
646
+ continue;
647
+ }
648
+ if (ignore.some((pattern) => name === pattern || name.match(pattern))) {
649
+ continue;
650
+ }
651
+ const fullPath = path.join(dirPath, name);
652
+ const entryRelativePath = relativePath ? `${relativePath}/${name}` : name;
653
+ if (entry.isDirectory()) {
654
+ folders.push({
655
+ name,
656
+ relativePath: entryRelativePath
657
+ });
658
+ await scanDir(fullPath, entryRelativePath);
659
+ } else if (entry.isFile()) {
660
+ const stat = await fs.stat(fullPath);
661
+ files.push({
662
+ name,
663
+ relativePath: entryRelativePath,
664
+ size: stat.size,
665
+ mimeType: getMimeType(name),
666
+ getData: async () => {
667
+ const buffer = await fs.readFile(fullPath);
668
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
669
+ }
670
+ });
671
+ }
672
+ }
673
+ }
674
+ await scanDir(directoryPath, "");
675
+ folders.sort((a, b) => a.relativePath.split("/").length - b.relativePath.split("/").length);
676
+ return { files, folders };
677
+ }
678
+
153
679
  // src/operations/folders.ts
154
680
  var FolderOperations = class {
155
681
  constructor(client) {
@@ -158,15 +684,32 @@ var FolderOperations = class {
158
684
  /**
159
685
  * Upload a local directory to Arke
160
686
  *
161
- * TODO: Implement this method
162
- * Steps:
163
- * 1. Scan directory structure
164
- * 2. Create folder hierarchy (depth-first)
165
- * 3. Upload files in parallel (with concurrency limit)
166
- * 4. Create bidirectional relationships (folder contains file)
687
+ * @deprecated Use uploadTree and scanDirectory instead
167
688
  */
168
- async uploadDirectory(_localPath, _options) {
169
- throw new Error("FolderOperations.uploadDirectory is not yet implemented");
689
+ async uploadDirectory(localPath, options) {
690
+ const tree = await scanDirectory(localPath);
691
+ const result = await uploadTree(this.client, tree, {
692
+ target: {
693
+ collectionId: options.collectionId,
694
+ parentId: options.parentFolderId
695
+ },
696
+ concurrency: options.concurrency,
697
+ onProgress: options.onProgress ? (p) => {
698
+ options.onProgress({
699
+ phase: p.phase === "computing-cids" || p.phase === "creating-folders" ? "creating-folders" : p.phase === "creating-files" || p.phase === "uploading-content" ? "uploading-files" : p.phase === "linking" ? "linking" : p.phase === "complete" ? "complete" : "scanning",
700
+ totalFiles: p.totalFiles,
701
+ completedFiles: p.completedFiles,
702
+ totalFolders: p.totalFolders,
703
+ completedFolders: p.completedFolders,
704
+ currentFile: p.currentFile
705
+ });
706
+ } : void 0
707
+ });
708
+ return {
709
+ rootFolder: result.folders[0] || null,
710
+ folders: result.folders,
711
+ files: result.files
712
+ };
170
713
  }
171
714
  };
172
715