@arke-institute/sdk 2.3.12 → 2.3.14

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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/ArkeClient.ts","../src/client/config.ts","../src/client/errors.ts","../src/operations/upload/engine.ts","../src/operations/upload/cid.ts","../src/operations/folders.ts","../src/operations/batch.ts","../src/operations/crypto.ts"],"sourcesContent":["/**\n * Main Arke SDK Client\n *\n * Provides type-safe access to the Arke API using openapi-fetch.\n */\n\nimport createClient, { type Client } from 'openapi-fetch';\nimport type { paths } from '../generated/types.js';\nimport { ArkeClientConfig, DEFAULT_CONFIG } from './config.js';\n\nexport type ArkeApiClient = Client<paths>;\n\n/**\n * Check if a token is an API key (starts with 'ak_' or 'uk_')\n */\nexport function isApiKey(token: string): boolean {\n return token.startsWith('ak_') || token.startsWith('uk_');\n}\n\n/**\n * Get the appropriate Authorization header value for a token\n * - API keys (ak_*, uk_*) use: ApiKey {token}\n * - JWT tokens use: Bearer {token}\n */\nexport function getAuthorizationHeader(token: string): string {\n if (isApiKey(token)) {\n return `ApiKey ${token}`;\n }\n return `Bearer ${token}`;\n}\n\n/**\n * Type-safe client for the Arke API\n *\n * @example\n * ```typescript\n * // With JWT token\n * const arke = new ArkeClient({ authToken: 'your-jwt-token' });\n *\n * // With API key (agent or user)\n * const arke = new ArkeClient({ authToken: 'ak_your-agent-api-key' });\n * const arke = new ArkeClient({ authToken: 'uk_your-user-api-key' });\n *\n * // Create an entity\n * const { data, error } = await arke.api.POST('/entities', {\n * body: {\n * collection_id: '01ABC...',\n * type: 'document',\n * properties: { title: 'My Document' }\n * }\n * });\n *\n * // Get an entity\n * const { data } = await arke.api.GET('/entities/{id}', {\n * params: { path: { id: '01XYZ...' } }\n * });\n * ```\n */\nexport class ArkeClient {\n /**\n * The underlying openapi-fetch client with full type safety\n * Use this for all API calls: arke.api.GET, arke.api.POST, etc.\n */\n public api: ArkeApiClient;\n\n private config: ArkeClientConfig;\n\n constructor(config: ArkeClientConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n this.api = this.createClient();\n }\n\n private createClient(): ArkeApiClient {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...this.config.headers,\n };\n\n if (this.config.authToken) {\n headers['Authorization'] = getAuthorizationHeader(this.config.authToken);\n }\n\n if (this.config.network === 'test') {\n headers['X-Arke-Network'] = 'test';\n }\n\n return createClient<paths>({\n baseUrl: this.config.baseUrl ?? DEFAULT_CONFIG.baseUrl,\n headers,\n });\n }\n\n /**\n * Update the authentication token\n * Recreates the underlying client with new headers\n */\n setAuthToken(token: string): void {\n this.config.authToken = token;\n this.api = this.createClient();\n }\n\n /**\n * Clear the authentication token\n */\n clearAuthToken(): void {\n this.config.authToken = undefined;\n this.api = this.createClient();\n }\n\n /**\n * Get the current configuration\n */\n getConfig(): Readonly<ArkeClientConfig> {\n return { ...this.config };\n }\n\n /**\n * Get the base URL\n */\n get baseUrl(): string {\n return this.config.baseUrl ?? DEFAULT_CONFIG.baseUrl;\n }\n\n /**\n * Check if client is authenticated\n */\n get isAuthenticated(): boolean {\n return !!this.config.authToken;\n }\n}\n\n/**\n * Create a new ArkeClient instance\n * Convenience function for those who prefer functional style\n */\nexport function createArkeClient(config?: ArkeClientConfig): ArkeClient {\n return new ArkeClient(config);\n}\n\n// Re-export types and errors\nexport type { ArkeClientConfig } from './config.js';\nexport * from './errors.js';\n","/**\n * SDK configuration types\n */\n\nexport interface ArkeClientConfig {\n /**\n * Base URL for the Arke API\n * @default 'https://arke-v1.arke.institute'\n */\n baseUrl?: string;\n\n /**\n * Authentication token - accepts either:\n * - JWT token from Supabase auth (sent as Bearer)\n * - Agent API key with 'ak_' prefix (sent as ApiKey)\n * - User API key with 'uk_' prefix (sent as ApiKey)\n *\n * The correct Authorization header format is auto-detected from the token prefix.\n */\n authToken?: string;\n\n /**\n * Network to use ('main' or 'test')\n * Test network uses 'II' prefixed IDs and isolated data\n * @default 'main'\n */\n network?: 'main' | 'test';\n\n /**\n * Callback to refresh auth token when expired\n * Called automatically on 401 responses\n */\n onTokenRefresh?: () => Promise<string>;\n\n /**\n * Custom headers to include in all requests\n */\n headers?: Record<string, string>;\n}\n\nexport const DEFAULT_CONFIG: Required<Pick<ArkeClientConfig, 'baseUrl' | 'network'>> = {\n baseUrl: 'https://arke-v1.arke.institute',\n network: 'main',\n};\n","/**\n * SDK error classes\n */\n\n/**\n * Base error class for all Arke SDK errors\n */\nexport class ArkeError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly status?: number,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'ArkeError';\n // Maintains proper stack trace for where error was thrown\n Error.captureStackTrace?.(this, this.constructor);\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n status: this.status,\n details: this.details,\n };\n }\n}\n\n/**\n * CAS (Compare-And-Swap) conflict - entity was modified by another request\n */\nexport class CASConflictError extends ArkeError {\n constructor(\n public readonly expectedTip?: string,\n public readonly actualTip?: string\n ) {\n super(\n 'Entity was modified by another request. Refresh and retry with the current tip.',\n 'CAS_CONFLICT',\n 409,\n { expectedTip, actualTip }\n );\n this.name = 'CASConflictError';\n }\n}\n\n/**\n * Resource not found\n */\nexport class NotFoundError extends ArkeError {\n constructor(resourceType: string, id: string) {\n super(`${resourceType} not found: ${id}`, 'NOT_FOUND', 404, { resourceType, id });\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * Validation error - invalid request data\n */\nexport class ValidationError extends ArkeError {\n constructor(\n message: string,\n public readonly field?: string,\n details?: unknown\n ) {\n super(message, 'VALIDATION_ERROR', 400, details ?? { field });\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Authentication required or invalid\n */\nexport class AuthenticationError extends ArkeError {\n constructor(message = 'Authentication required') {\n super(message, 'AUTH_REQUIRED', 401);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Permission denied\n */\nexport class ForbiddenError extends ArkeError {\n constructor(action?: string, resource?: string) {\n const msg = action\n ? `Permission denied: ${action}${resource ? ` on ${resource}` : ''}`\n : 'Permission denied';\n super(msg, 'FORBIDDEN', 403, { action, resource });\n this.name = 'ForbiddenError';\n }\n}\n\n/**\n * Parse API error response into appropriate error class\n */\nexport function parseApiError(status: number, body: unknown): ArkeError {\n const errorBody = body as { error?: string; message?: string; details?: unknown } | null;\n const message = errorBody?.error ?? errorBody?.message ?? 'Unknown error';\n\n switch (status) {\n case 400:\n return new ValidationError(message, undefined, errorBody?.details);\n\n case 401:\n return new AuthenticationError(message);\n\n case 403:\n return new ForbiddenError(message);\n\n case 404:\n return new NotFoundError('Resource', 'unknown');\n\n case 409: {\n // Parse CAS conflict details if available\n const details = errorBody?.details as { expected?: string; actual?: string } | undefined;\n return new CASConflictError(details?.expected, details?.actual);\n }\n\n default:\n return new ArkeError(message, 'API_ERROR', status, errorBody?.details);\n }\n}\n","/**\n * Upload Engine\n *\n * Core upload implementation optimized for fast tree visibility:\n * 1. Create folders by depth (with unidirectional 'in' → parent)\n * 2. Create file entities (metadata only, high parallelism)\n * 3. Backlink parents with 'contains' relationships\n * → Tree is now browsable! Users can explore structure immediately.\n * 4. Upload file content via POST /files/{id}/content (byte-based pool, ~200MB in flight)\n * - Direct upload to API endpoint\n * - API streams to R2, computes CID, updates entity atomically\n *\n * Byte-based pool (for uploads):\n * - Maintains ~200MB of data in flight at all times\n * - When a file completes, next file starts immediately (no gaps)\n * - Small files: Many upload in parallel\n * - Large files: Fewer upload in parallel (bandwidth-limited)\n * - Single file > 200MB: Uploads alone when pool is empty\n *\n * This minimizes time-to-browse by:\n * - Creating all entities before uploading content\n * - Using unidirectional 'in' relationship on entity creation\n * - Adding all 'contains' relationships in a single PUT per parent\n */\n\nimport type { ArkeClient } from '../../client/ArkeClient.js';\nimport type { components } from '../../generated/types.js';\nimport type {\n UploadTree,\n UploadOptions,\n UploadResult,\n UploadProgress,\n CreatedFolder,\n CreatedFile,\n CreatedEntity,\n UploadFolder,\n} from './types.js';\n\ntype CreateCollectionRequest = components['schemas']['CreateCollectionRequest'];\ntype CreateFolderRequest = components['schemas']['CreateFolderRequest'];\ntype CreateFileRequest = components['schemas']['CreateFileRequest'];\ntype UpdateFolderRequest = components['schemas']['UpdateFolderRequest'];\ntype UpdateCollectionRequest = components['schemas']['UpdateCollectionRequest'];\n\n// Phase constants\nconst PHASE_COUNT = 3; // creating, backlinking, uploading (excluding complete/error)\nconst PHASE_INDEX: Record<string, number> = {\n creating: 0,\n backlinking: 1,\n uploading: 2,\n complete: 3,\n error: -1,\n};\n\n// =============================================================================\n// Concurrency Utilities\n// =============================================================================\n\n/**\n * Simple concurrency limiter for parallel operations.\n */\nasync function parallelLimit<T, R>(\n items: T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>\n): Promise<R[]> {\n const results: R[] = [];\n let index = 0;\n\n async function worker(): Promise<void> {\n while (index < items.length) {\n const currentIndex = index++;\n const item = items[currentIndex]!;\n results[currentIndex] = await fn(item, currentIndex);\n }\n }\n\n const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());\n await Promise.all(workers);\n\n return results;\n}\n\n// =============================================================================\n// Byte-Based Pool\n// =============================================================================\n\n/** Target bytes in flight (~200MB) */\nconst TARGET_BYTES_IN_FLIGHT = 200 * 1024 * 1024;\n\n/**\n * Pool that maintains a target number of bytes in flight.\n *\n * When a file completes, its bytes are released and the next\n * waiting file can start immediately. This keeps the pipeline full.\n *\n * - Small files: Many run in parallel (up to ~200MB worth)\n * - Large files: Fewer run in parallel\n * - Single file > 200MB: Runs alone (allowed when pool is empty)\n */\nclass BytePool {\n private bytesInFlight = 0;\n private waitQueue: Array<() => void> = [];\n\n constructor(private targetBytes: number = TARGET_BYTES_IN_FLIGHT) {}\n\n async run<T>(size: number, fn: () => Promise<T>): Promise<T> {\n // Wait until we have room\n // Exception: if pool is empty, always allow (handles files > targetBytes)\n while (this.bytesInFlight > 0 && this.bytesInFlight + size > this.targetBytes) {\n await new Promise<void>((resolve) => this.waitQueue.push(resolve));\n }\n\n this.bytesInFlight += size;\n try {\n return await fn();\n } finally {\n this.bytesInFlight -= size;\n // Wake up next waiting task\n const next = this.waitQueue.shift();\n if (next) next();\n }\n }\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Parse folder path to get parent path.\n * e.g., \"docs/images/photos\" -> \"docs/images\"\n */\nfunction getParentPath(relativePath: string): string | null {\n const lastSlash = relativePath.lastIndexOf('/');\n if (lastSlash === -1) return null;\n return relativePath.slice(0, lastSlash);\n}\n\n/**\n * Group folders by depth level.\n */\nfunction groupFoldersByDepth(folders: UploadFolder[]): Map<number, UploadFolder[]> {\n const byDepth = new Map<number, UploadFolder[]>();\n\n for (const folder of folders) {\n const depth = folder.relativePath.split('/').length - 1;\n if (!byDepth.has(depth)) byDepth.set(depth, []);\n byDepth.get(depth)!.push(folder);\n }\n\n return byDepth;\n}\n\n// =============================================================================\n// Main Upload Function\n// =============================================================================\n\n/**\n * Main upload function.\n * Orchestrates the entire upload process with optimized relationship strategy.\n */\nexport async function uploadTree(\n client: ArkeClient,\n tree: UploadTree,\n options: UploadOptions\n): Promise<UploadResult> {\n const { target, onProgress, concurrency = 10, continueOnError = false, note } = options;\n\n const errors: Array<{ path: string; error: string }> = [];\n const createdFolders: CreatedFolder[] = [];\n const createdFiles: CreatedFile[] = [];\n\n // Maps for tracking (include label for peer_label in relationships)\n const foldersByPath = new Map<string, { id: string; cid: string; label: string }>();\n\n // Calculate totals\n const totalEntities = tree.files.length + tree.folders.length;\n const totalBytes = tree.files.reduce((sum, f) => sum + f.size, 0);\n let completedEntities = 0;\n let bytesUploaded = 0;\n\n // Helper to report progress\n const reportProgress = (progress: Partial<UploadProgress>) => {\n if (onProgress) {\n const phase = progress.phase || 'creating';\n const phaseIndex = PHASE_INDEX[phase] ?? -1;\n\n // Calculate phase percent based on current phase\n let phasePercent = 0;\n if (phase === 'creating') {\n // Creating phase: progress is based on entities created\n const done = progress.completedEntities ?? completedEntities;\n phasePercent = totalEntities > 0 ? Math.round((done / totalEntities) * 100) : 100;\n } else if (phase === 'backlinking') {\n // Backlinking phase: progress is based on parents updated\n const done = progress.completedParents ?? 0;\n const total = progress.totalParents ?? 0;\n phasePercent = total > 0 ? Math.round((done / total) * 100) : 100;\n } else if (phase === 'uploading') {\n // Uploading phase: progress is based on bytes uploaded\n const done = progress.bytesUploaded ?? bytesUploaded;\n phasePercent = totalBytes > 0 ? Math.round((done / totalBytes) * 100) : 100;\n } else if (phase === 'complete') {\n phasePercent = 100;\n }\n\n onProgress({\n phase,\n phaseIndex,\n phaseCount: PHASE_COUNT,\n phasePercent,\n totalEntities,\n completedEntities,\n totalParents: 0,\n completedParents: 0,\n totalBytes,\n bytesUploaded,\n ...progress,\n } as UploadProgress);\n }\n };\n\n try {\n // ─────────────────────────────────────────────────────────────────────────\n // SETUP: Resolve or create collection\n // ─────────────────────────────────────────────────────────────────────────\n let collectionId: string;\n let collectionCid: string;\n let collectionLabel: string;\n let collectionCreated = false;\n\n if (target.createCollection) {\n const collectionBody: CreateCollectionRequest = {\n label: target.createCollection.label,\n description: target.createCollection.description,\n roles: target.createCollection.roles,\n note,\n };\n\n const { data, error } = await client.api.POST('/collections', {\n body: collectionBody,\n });\n\n if (error || !data) {\n throw new Error(`Failed to create collection: ${JSON.stringify(error)}`);\n }\n\n collectionId = data.id;\n collectionCid = data.cid;\n collectionLabel = target.createCollection.label;\n collectionCreated = true;\n } else if (target.collectionId) {\n collectionId = target.collectionId;\n\n const { data, error } = await client.api.GET('/collections/{id}', {\n params: { path: { id: collectionId } },\n });\n\n if (error || !data) {\n throw new Error(`Failed to fetch collection: ${JSON.stringify(error)}`);\n }\n\n collectionCid = data.cid;\n collectionLabel = (data.properties?.label as string) ?? collectionId;\n } else {\n throw new Error('Must provide either collectionId or createCollection in target');\n }\n\n // Determine the parent for root-level items\n const rootParentId = target.parentId ?? collectionId;\n let rootParentLabel = collectionLabel;\n let rootParentType: 'collection' | 'folder' = 'collection';\n\n // If a specific parent folder is provided, fetch its label\n if (target.parentId && target.parentId !== collectionId) {\n const { data: parentData, error: parentError } = await client.api.GET('/folders/{id}', {\n params: { path: { id: target.parentId } },\n });\n if (parentError || !parentData) {\n throw new Error(`Failed to fetch parent folder: ${JSON.stringify(parentError)}`);\n }\n rootParentLabel = (parentData.properties?.label as string) ?? target.parentId;\n rootParentType = 'folder';\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 1: Create entities (folders by depth, then files)\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'creating', completedEntities: 0 });\n\n // Group folders by depth\n const foldersByDepth = groupFoldersByDepth(tree.folders);\n const sortedDepths = [...foldersByDepth.keys()].sort((a, b) => a - b);\n\n // Create folders depth by depth (parents before children)\n for (const depth of sortedDepths) {\n const foldersAtDepth = foldersByDepth.get(depth)!;\n\n await Promise.all(\n foldersAtDepth.map(async (folder) => {\n try {\n const parentPath = getParentPath(folder.relativePath);\n const parentInfo = parentPath ? foldersByPath.get(parentPath)! : null;\n const parentId = parentInfo ? parentInfo.id : rootParentId;\n const parentType = parentInfo ? 'folder' : rootParentType;\n const parentLabel = parentInfo ? parentInfo.label : rootParentLabel;\n\n const folderBody: CreateFolderRequest = {\n label: folder.name,\n collection: collectionId,\n note,\n relationships: [{ predicate: 'in', peer: parentId, peer_type: parentType, peer_label: parentLabel }],\n };\n\n const { data, error } = await client.api.POST('/folders', {\n body: folderBody,\n });\n\n if (error || !data) {\n throw new Error(JSON.stringify(error));\n }\n\n // Track folder (include label for peer_label in child relationships)\n foldersByPath.set(folder.relativePath, { id: data.id, cid: data.cid, label: folder.name });\n createdFolders.push({\n name: folder.name,\n relativePath: folder.relativePath,\n id: data.id,\n entityCid: data.cid,\n });\n\n completedEntities++;\n reportProgress({\n phase: 'creating',\n completedEntities,\n currentItem: folder.relativePath,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: folder.relativePath, error: `Folder creation failed: ${errorMsg}` });\n completedEntities++;\n } else {\n throw new Error(`Failed to create folder ${folder.relativePath}: ${errorMsg}`);\n }\n }\n })\n );\n }\n\n // Create file entities (metadata only, no content upload yet)\n // Use simple concurrency limit for API calls\n const FILE_CREATION_CONCURRENCY = 50;\n\n await parallelLimit(tree.files, FILE_CREATION_CONCURRENCY, async (file) => {\n try {\n const parentPath = getParentPath(file.relativePath);\n const parentInfo = parentPath ? foldersByPath.get(parentPath)! : null;\n const parentId = parentInfo ? parentInfo.id : rootParentId;\n const parentType = parentInfo ? 'folder' : rootParentType;\n const parentLabel = parentInfo ? parentInfo.label : rootParentLabel;\n\n // Create file entity with 'in' relationship (include peer_label for display)\n // Server computes CID when content is uploaded\n const fileBody: CreateFileRequest = {\n key: crypto.randomUUID(), // Generate unique storage key\n filename: file.name,\n label: file.name, // Display label for the file\n content_type: file.mimeType,\n size: file.size,\n collection: collectionId,\n relationships: [{ predicate: 'in', peer: parentId, peer_type: parentType, peer_label: parentLabel }],\n };\n\n const { data, error } = await client.api.POST('/files', {\n body: fileBody,\n });\n\n if (error || !data) {\n throw new Error(`Entity creation failed: ${JSON.stringify(error)}`);\n }\n\n // Track file for later upload\n createdFiles.push({\n ...file,\n id: data.id,\n entityCid: data.cid,\n });\n\n completedEntities++;\n reportProgress({\n phase: 'creating',\n completedEntities,\n currentItem: file.relativePath,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: file.relativePath, error: errorMsg });\n completedEntities++;\n } else {\n throw new Error(`Failed to create file ${file.relativePath}: ${errorMsg}`);\n }\n }\n });\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 2: Backlink - Update each parent with 'contains' relationships\n // ─────────────────────────────────────────────────────────────────────────\n\n // Build parent -> children map (include label for peer_label)\n const childrenByParent = new Map<string, Array<{ id: string; type: 'file' | 'folder'; label: string }>>();\n\n // Add folders as children of their parents\n for (const folder of createdFolders) {\n const parentPath = getParentPath(folder.relativePath);\n const parentId = parentPath ? foldersByPath.get(parentPath)!.id : rootParentId;\n\n if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);\n childrenByParent.get(parentId)!.push({ id: folder.id, type: 'folder', label: folder.name });\n }\n\n // Add files as children of their parents\n for (const file of createdFiles) {\n const parentPath = getParentPath(file.relativePath);\n const parentId = parentPath ? foldersByPath.get(parentPath)!.id : rootParentId;\n\n if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);\n childrenByParent.get(parentId)!.push({ id: file.id, type: 'file', label: file.name });\n }\n\n const totalParents = childrenByParent.size;\n let completedParents = 0;\n\n reportProgress({ phase: 'backlinking', totalParents, completedParents: 0 });\n\n // Update all parents in parallel - each parent gets one PUT with all its children\n const parentEntries = [...childrenByParent.entries()];\n\n await parallelLimit(parentEntries, concurrency, async ([parentId, children]) => {\n try {\n const isCollection = parentId === collectionId;\n\n // Build relationships_add array with all children (include peer_label for display)\n const relationshipsAdd = children.map((child) => ({\n predicate: 'contains' as const,\n peer: child.id,\n peer_type: child.type,\n peer_label: child.label,\n }));\n\n if (isCollection) {\n // Get current collection CID for CAS\n const { data: collData, error: getError } = await client.api.GET('/collections/{id}', {\n params: { path: { id: parentId } },\n });\n if (getError || !collData) {\n throw new Error(`Failed to fetch collection: ${JSON.stringify(getError)}`);\n }\n\n // Update collection with relationships_add\n const updateBody: UpdateCollectionRequest = {\n expect_tip: collData.cid,\n relationships_add: relationshipsAdd,\n note: note ? `${note} (backlink)` : 'Upload backlink',\n };\n\n const { error } = await client.api.PUT('/collections/{id}', {\n params: { path: { id: parentId } },\n body: updateBody,\n });\n\n if (error) {\n throw new Error(JSON.stringify(error));\n }\n } else {\n // Get current folder CID for CAS\n const { data: folderData, error: getError } = await client.api.GET('/folders/{id}', {\n params: { path: { id: parentId } },\n });\n if (getError || !folderData) {\n throw new Error(`Failed to fetch folder: ${JSON.stringify(getError)}`);\n }\n\n // Update folder with relationships_add\n const updateBody: UpdateFolderRequest = {\n expect_tip: folderData.cid,\n relationships_add: relationshipsAdd,\n note: note ? `${note} (backlink)` : 'Upload backlink',\n };\n\n const { error } = await client.api.PUT('/folders/{id}', {\n params: { path: { id: parentId } },\n body: updateBody,\n });\n\n if (error) {\n throw new Error(JSON.stringify(error));\n }\n }\n\n completedParents++;\n reportProgress({\n phase: 'backlinking',\n totalParents,\n completedParents,\n currentItem: `parent:${parentId}`,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: `parent:${parentId}`, error: `Backlink failed: ${errorMsg}` });\n completedParents++;\n } else {\n throw new Error(`Failed to backlink parent ${parentId}: ${errorMsg}`);\n }\n }\n });\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 3: Upload file content directly to API\n // Tree is now browsable! Users can explore while content uploads.\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'uploading', bytesUploaded: 0 });\n\n // Use byte-based pool to maintain ~200MB in flight\n const pool = new BytePool();\n\n await Promise.all(\n createdFiles.map(async (file) => {\n await pool.run(file.size, async () => {\n try {\n // Get file data\n const fileData = await file.getData();\n\n let body: Blob;\n if (fileData instanceof Blob) {\n body = fileData;\n } else if (fileData instanceof Uint8Array) {\n const arrayBuffer = new ArrayBuffer(fileData.byteLength);\n new Uint8Array(arrayBuffer).set(fileData);\n body = new Blob([arrayBuffer], { type: file.mimeType });\n } else {\n body = new Blob([fileData], { type: file.mimeType });\n }\n\n // Upload content directly to API endpoint\n // The API streams to R2, computes CID, and updates the entity atomically\n const { error: uploadError } = await client.api.POST('/files/{id}/content', {\n params: { path: { id: file.id } },\n body: body as unknown as Record<string, never>,\n bodySerializer: (b: unknown) => b as BodyInit,\n headers: { 'Content-Type': file.mimeType },\n } as Parameters<typeof client.api.POST>[1]);\n\n if (uploadError) {\n throw new Error(`Upload failed: ${JSON.stringify(uploadError)}`);\n }\n\n bytesUploaded += file.size;\n reportProgress({\n phase: 'uploading',\n bytesUploaded,\n currentItem: file.relativePath,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: file.relativePath, error: `Upload failed: ${errorMsg}` });\n } else {\n throw new Error(`Failed to upload ${file.relativePath}: ${errorMsg}`);\n }\n }\n });\n })\n );\n\n // ─────────────────────────────────────────────────────────────────────────\n // Complete!\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'complete', totalParents, completedParents, bytesUploaded });\n\n const resultFolders: CreatedEntity[] = createdFolders.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'folder' as const,\n relativePath: f.relativePath,\n }));\n\n const resultFiles: CreatedEntity[] = createdFiles.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'file' as const,\n relativePath: f.relativePath,\n }));\n\n return {\n success: errors.length === 0,\n collection: {\n id: collectionId,\n cid: collectionCid,\n created: collectionCreated,\n },\n folders: resultFolders,\n files: resultFiles,\n errors,\n };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n\n reportProgress({\n phase: 'error',\n error: errorMsg,\n });\n\n return {\n success: false,\n collection: {\n id: target.collectionId ?? '',\n cid: '',\n created: false,\n },\n folders: createdFolders.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'folder' as const,\n relativePath: f.relativePath,\n })),\n files: createdFiles.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'file' as const,\n relativePath: f.relativePath,\n })),\n errors: [...errors, { path: '', error: errorMsg }],\n };\n }\n}\n","/**\n * CID Computation Utility\n *\n * Computes IPFS CIDv1 (base32) for file content.\n * Uses raw codec (0x55) and SHA-256 hash.\n *\n * Note: This module is not used internally by the upload engine (the server\n * computes CIDs from uploaded content). It is exported for convenience in case\n * you want to verify entity CIDs, detect duplicates before upload, or perform\n * other content-addressed operations.\n */\n\nimport { CID } from 'multiformats/cid';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport * as raw from 'multiformats/codecs/raw';\n\n/**\n * Compute CIDv1 for binary content.\n * Returns base32 encoded string (bafk... prefix for raw codec).\n *\n * @param data - Binary content as ArrayBuffer, Uint8Array, or Blob\n * @returns CIDv1 string in base32 encoding\n *\n * @example\n * ```typescript\n * const cid = await computeCid(new TextEncoder().encode('hello world'));\n * // Returns: \"bafkreifzjut3te2nhyekklss27nh3k72ysco7y32koao5eei66wof36n5e\"\n * ```\n */\nexport async function computeCid(data: ArrayBuffer | Uint8Array | Blob): Promise<string> {\n // Convert to Uint8Array\n let bytes: Uint8Array;\n\n if (data instanceof Blob) {\n const buffer = await data.arrayBuffer();\n bytes = new Uint8Array(buffer);\n } else if (data instanceof ArrayBuffer) {\n bytes = new Uint8Array(data);\n } else {\n bytes = data;\n }\n\n // Compute SHA-256 hash\n const hash = await sha256.digest(bytes);\n\n // Create CIDv1 with raw codec\n const cid = CID.create(1, raw.code, hash);\n\n // Return base32 encoded string\n return cid.toString();\n}\n\n/**\n * Verify a CID matches the content.\n *\n * @param data - Binary content\n * @param expectedCid - CID to verify against\n * @returns true if CID matches\n */\nexport async function verifyCid(\n data: ArrayBuffer | Uint8Array | Blob,\n expectedCid: string\n): Promise<boolean> {\n const computed = await computeCid(data);\n return computed === expectedCid;\n}\n","/**\n * Folder Operations (Legacy)\n *\n * @deprecated Use the new upload module instead:\n * ```typescript\n * import { uploadTree, buildUploadTree } from '@arke-institute/sdk/operations';\n *\n * const tree = buildUploadTree([\n * { path: 'docs/readme.md', data: readmeBuffer },\n * { path: 'images/logo.png', data: logoBlob },\n * ]);\n * const result = await uploadTree(client, tree, {\n * target: { collectionId: '...' },\n * });\n * ```\n */\n\nimport type { ArkeClient } from '../client/ArkeClient.js';\n\n/**\n * @deprecated Use UploadProgress from upload module\n */\nexport interface UploadProgress {\n phase: 'scanning' | 'creating-folders' | 'uploading-files' | 'linking' | 'complete';\n totalFiles: number;\n completedFiles: number;\n totalFolders: number;\n completedFolders: number;\n currentFile?: string;\n}\n\n/**\n * @deprecated Use UploadOptions from upload module\n */\nexport interface UploadDirectoryOptions {\n /** Collection to upload into */\n collectionId: string;\n /** Parent folder ID (optional - creates at root if not provided) */\n parentFolderId?: string;\n /** Progress callback */\n onProgress?: (progress: UploadProgress) => void;\n /** Max concurrent uploads */\n concurrency?: number;\n}\n\n/**\n * @deprecated Use UploadResult from upload module\n */\nexport interface UploadDirectoryResult {\n /** Root folder entity */\n rootFolder: unknown;\n /** All created folder entities */\n folders: unknown[];\n /** All created file entities */\n files: unknown[];\n}\n\n/**\n * Folder operations helper\n *\n * @deprecated Use uploadTree and buildUploadTree functions instead:\n * ```typescript\n * import { uploadTree, buildUploadTree } from '@arke-institute/sdk/operations';\n *\n * const tree = buildUploadTree([\n * { path: 'docs/readme.md', data: readmeBuffer },\n * ]);\n * const result = await uploadTree(client, tree, {\n * target: { collectionId: '...' },\n * });\n * ```\n */\nexport class FolderOperations {\n constructor(private client: ArkeClient) {\n void client; // Suppress unused warning\n }\n\n /**\n * Upload a local directory to Arke\n *\n * @deprecated This method has been removed. Use uploadTree and buildUploadTree instead.\n */\n async uploadDirectory(\n _localPath: string,\n _options: UploadDirectoryOptions\n ): Promise<UploadDirectoryResult> {\n throw new Error(\n 'FolderOperations.uploadDirectory has been removed. ' +\n 'Use uploadTree() with buildUploadTree() instead. ' +\n 'See: https://github.com/arke-institute/arke-sdk#upload-module'\n );\n }\n}\n","/**\n * Batch Operations\n *\n * High-level operations for bulk entity and relationship management.\n *\n * TODO: Implement batch operations\n * - createEntities: Create multiple entities in parallel\n * - updateEntities: Update multiple entities in parallel\n * - createRelationships: Create multiple relationships in parallel\n */\n\nimport type { ArkeClient } from '../client/ArkeClient.js';\n\nexport interface BatchCreateOptions {\n /** Max concurrent operations */\n concurrency?: number;\n /** Continue on individual failures */\n continueOnError?: boolean;\n /** Progress callback */\n onProgress?: (completed: number, total: number) => void;\n}\n\nexport interface BatchResult<T> {\n /** Successfully completed operations */\n succeeded: T[];\n /** Failed operations with errors */\n failed: Array<{ input: unknown; error: Error }>;\n}\n\n/**\n * Batch operations helper\n *\n * @example\n * ```typescript\n * const batch = new BatchOperations(arkeClient);\n * const result = await batch.createEntities([\n * { type: 'document', properties: { title: 'Doc 1' } },\n * { type: 'document', properties: { title: 'Doc 2' } },\n * ], { concurrency: 5 });\n * ```\n */\nexport class BatchOperations {\n constructor(private client: ArkeClient) {}\n\n /**\n * Create multiple entities in parallel\n *\n * TODO: Implement this method\n */\n async createEntities(\n _entities: Array<{\n collectionId: string;\n type: string;\n properties?: Record<string, unknown>;\n }>,\n _options?: BatchCreateOptions\n ): Promise<BatchResult<unknown>> {\n throw new Error('BatchOperations.createEntities is not yet implemented');\n }\n\n /**\n * Create multiple relationships in parallel\n *\n * TODO: Implement this method\n */\n async createRelationships(\n _relationships: Array<{\n sourceId: string;\n targetId: string;\n predicate: string;\n bidirectional?: boolean;\n properties?: Record<string, unknown>;\n }>,\n _options?: BatchCreateOptions\n ): Promise<BatchResult<unknown>> {\n throw new Error('BatchOperations.createRelationships is not yet implemented');\n }\n}\n","/**\n * Crypto Operations\n *\n * Cryptographic utilities for agents and content addressing.\n *\n * TODO: Implement crypto operations\n * - generateKeyPair: Generate Ed25519 key pair for agent authentication\n * - signPayload: Sign a payload with agent private key\n * - computeCID: Compute IPFS CID for content\n */\n\n/**\n * Ed25519 key pair for agent authentication\n */\nexport interface KeyPair {\n /** Public key in base64 */\n publicKey: string;\n /** Private key in base64 (keep secret!) */\n privateKey: string;\n}\n\n/**\n * Signed payload with signature\n */\nexport interface SignedPayload {\n /** Original payload */\n payload: string;\n /** Ed25519 signature in base64 */\n signature: string;\n /** Timestamp of signature */\n timestamp: number;\n}\n\n/**\n * Crypto operations helper\n *\n * @example\n * ```typescript\n * // Generate key pair for a new agent\n * const { publicKey, privateKey } = await CryptoOperations.generateKeyPair();\n *\n * // Sign a payload\n * const signed = await CryptoOperations.signPayload(privateKey, payload);\n * ```\n */\nexport class CryptoOperations {\n /**\n * Generate an Ed25519 key pair for agent authentication\n *\n * TODO: Implement using Node.js crypto or Web Crypto API\n */\n static async generateKeyPair(): Promise<KeyPair> {\n throw new Error('CryptoOperations.generateKeyPair is not yet implemented');\n }\n\n /**\n * Sign a payload with an Ed25519 private key\n *\n * TODO: Implement signature generation\n */\n static async signPayload(_privateKey: string, _payload: string): Promise<SignedPayload> {\n throw new Error('CryptoOperations.signPayload is not yet implemented');\n }\n\n /**\n * Verify an Ed25519 signature\n *\n * TODO: Implement signature verification\n */\n static async verifySignature(\n _publicKey: string,\n _payload: string,\n _signature: string\n ): Promise<boolean> {\n throw new Error('CryptoOperations.verifySignature is not yet implemented');\n }\n\n /**\n * Compute IPFS CID for content\n *\n * TODO: Implement using multiformats library\n */\n static async computeCID(_content: Uint8Array): Promise<string> {\n throw new Error('CryptoOperations.computeCID is not yet implemented');\n }\n}\n"],"mappings":";AAMA,OAAO,kBAAmC;;;ACkCnC,IAAM,iBAA0E;AAAA,EACrF,SAAS;AAAA,EACT,SAAS;AACX;;;ACpCO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YACE,SACgBA,OACA,QACA,SAChB;AACA,UAAM,OAAO;AAJG,gBAAAA;AACA;AACA;AAGhB,SAAK,OAAO;AAEZ,UAAM,oBAAoB,MAAM,KAAK,WAAW;AAAA,EAClD;AAAA,EAEA,SAAS;AACP,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,SAAS,KAAK;AAAA,MACd,MAAM,KAAK;AAAA,MACX,QAAQ,KAAK;AAAA,MACb,SAAS,KAAK;AAAA,IAChB;AAAA,EACF;AACF;AAKO,IAAM,mBAAN,cAA+B,UAAU;AAAA,EAC9C,YACkB,aACA,WAChB;AACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA,EAAE,aAAa,UAAU;AAAA,IAC3B;AARgB;AACA;AAQhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,gBAAN,cAA4B,UAAU;AAAA,EAC3C,YAAY,cAAsB,IAAY;AAC5C,UAAM,GAAG,YAAY,eAAe,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AAC9B;;;AGrDA,IAAM,yBAAyB,MAAM,OAAO;;;AC5E5C,SAAS,WAAW;AACpB,SAAS,cAAc;AACvB,YAAY,SAAS;;;AC0Dd,IAAM,mBAAN,MAAuB;AAAA,EAC5B,YAAoB,QAAoB;AAApB;AAClB,SAAK;AAAA,EACP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,gBACJ,YACA,UACgC;AAChC,UAAM,IAAI;AAAA,MACR;AAAA,IAGF;AAAA,EACF;AACF;;;ACnDO,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YAAoB,QAAoB;AAApB;AAAA,EAAqB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOzC,MAAM,eACJ,WAKA,UAC+B;AAC/B,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,oBACJ,gBAOA,UAC+B;AAC/B,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AACF;;;AChCO,IAAM,mBAAN,MAAuB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,aAAa,kBAAoC;AAC/C,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa,YAAY,aAAqB,UAA0C;AACtF,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa,gBACX,YACA,UACA,YACkB;AAClB,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa,WAAW,UAAuC;AAC7D,UAAM,IAAI,MAAM,oDAAoD;AAAA,EACtE;AACF;","names":["code"]}
1
+ {"version":3,"sources":["../src/client/ArkeClient.ts","../src/client/config.ts","../src/client/errors.ts","../src/operations/upload/engine.ts","../src/operations/upload/cid.ts","../src/operations/folders.ts","../src/operations/batch.ts","../src/operations/crypto.ts"],"sourcesContent":["/**\n * Main Arke SDK Client\n *\n * Provides type-safe access to the Arke API using openapi-fetch.\n */\n\nimport createClient, { type Client } from 'openapi-fetch';\nimport type { paths } from '../generated/types.js';\nimport { ArkeClientConfig, DEFAULT_CONFIG } from './config.js';\n\nexport type ArkeApiClient = Client<paths>;\n\n/**\n * Check if a token is an API key (starts with 'ak_' or 'uk_')\n */\nexport function isApiKey(token: string): boolean {\n return token.startsWith('ak_') || token.startsWith('uk_');\n}\n\n/**\n * Get the appropriate Authorization header value for a token\n * - API keys (ak_*, uk_*) use: ApiKey {token}\n * - JWT tokens use: Bearer {token}\n */\nexport function getAuthorizationHeader(token: string): string {\n if (isApiKey(token)) {\n return `ApiKey ${token}`;\n }\n return `Bearer ${token}`;\n}\n\n/**\n * Type-safe client for the Arke API\n *\n * @example\n * ```typescript\n * // With JWT token\n * const arke = new ArkeClient({ authToken: 'your-jwt-token' });\n *\n * // With API key (agent or user)\n * const arke = new ArkeClient({ authToken: 'ak_your-agent-api-key' });\n * const arke = new ArkeClient({ authToken: 'uk_your-user-api-key' });\n *\n * // Create an entity\n * const { data, error } = await arke.api.POST('/entities', {\n * body: {\n * collection_id: '01ABC...',\n * type: 'document',\n * properties: { title: 'My Document' }\n * }\n * });\n *\n * // Get an entity\n * const { data } = await arke.api.GET('/entities/{id}', {\n * params: { path: { id: '01XYZ...' } }\n * });\n * ```\n */\nexport class ArkeClient {\n /**\n * The underlying openapi-fetch client with full type safety\n * Use this for all API calls: arke.api.GET, arke.api.POST, etc.\n */\n public api: ArkeApiClient;\n\n private config: ArkeClientConfig;\n\n constructor(config: ArkeClientConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n this.api = this.createClient();\n }\n\n private createClient(): ArkeApiClient {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...this.config.headers,\n };\n\n if (this.config.authToken) {\n headers['Authorization'] = getAuthorizationHeader(this.config.authToken);\n }\n\n if (this.config.network === 'test') {\n headers['X-Arke-Network'] = 'test';\n }\n\n return createClient<paths>({\n baseUrl: this.config.baseUrl ?? DEFAULT_CONFIG.baseUrl,\n headers,\n });\n }\n\n /**\n * Update the authentication token\n * Recreates the underlying client with new headers\n */\n setAuthToken(token: string): void {\n this.config.authToken = token;\n this.api = this.createClient();\n }\n\n /**\n * Clear the authentication token\n */\n clearAuthToken(): void {\n this.config.authToken = undefined;\n this.api = this.createClient();\n }\n\n /**\n * Get the current configuration\n */\n getConfig(): Readonly<ArkeClientConfig> {\n return { ...this.config };\n }\n\n /**\n * Get the base URL\n */\n get baseUrl(): string {\n return this.config.baseUrl ?? DEFAULT_CONFIG.baseUrl;\n }\n\n /**\n * Check if client is authenticated\n */\n get isAuthenticated(): boolean {\n return !!this.config.authToken;\n }\n\n /**\n * Get file content as a Blob\n *\n * This is a convenience method that handles the binary response parsing\n * that openapi-fetch doesn't handle automatically.\n *\n * @example\n * ```typescript\n * const { data, error } = await arke.getFileContent('01ABC...');\n * if (data) {\n * const text = await data.text();\n * // or\n * const arrayBuffer = await data.arrayBuffer();\n * }\n * ```\n */\n async getFileContent(\n fileId: string\n ): Promise<{ data: Blob | undefined; error: unknown }> {\n const { data, error } = await this.api.GET('/files/{id}/content', {\n params: { path: { id: fileId } },\n parseAs: 'blob',\n });\n return { data: data as Blob | undefined, error };\n }\n\n /**\n * Get file content as an ArrayBuffer\n *\n * This is a convenience method that handles the binary response parsing\n * that openapi-fetch doesn't handle automatically.\n *\n * @example\n * ```typescript\n * const { data, error } = await arke.getFileContentAsArrayBuffer('01ABC...');\n * if (data) {\n * const bytes = new Uint8Array(data);\n * }\n * ```\n */\n async getFileContentAsArrayBuffer(\n fileId: string\n ): Promise<{ data: ArrayBuffer | undefined; error: unknown }> {\n const { data, error } = await this.api.GET('/files/{id}/content', {\n params: { path: { id: fileId } },\n parseAs: 'arrayBuffer',\n });\n return { data: data as ArrayBuffer | undefined, error };\n }\n\n /**\n * Get file content as a ReadableStream\n *\n * This is a convenience method for streaming large files.\n *\n * @example\n * ```typescript\n * const { data, error } = await arke.getFileContentAsStream('01ABC...');\n * if (data) {\n * const reader = data.getReader();\n * // Process chunks...\n * }\n * ```\n */\n async getFileContentAsStream(\n fileId: string\n ): Promise<{ data: ReadableStream<Uint8Array> | null | undefined; error: unknown }> {\n const { data, error } = await this.api.GET('/files/{id}/content', {\n params: { path: { id: fileId } },\n parseAs: 'stream',\n });\n return { data: data as ReadableStream<Uint8Array> | null | undefined, error };\n }\n}\n\n/**\n * Create a new ArkeClient instance\n * Convenience function for those who prefer functional style\n */\nexport function createArkeClient(config?: ArkeClientConfig): ArkeClient {\n return new ArkeClient(config);\n}\n\n// Re-export types and errors\nexport type { ArkeClientConfig } from './config.js';\nexport * from './errors.js';\n","/**\n * SDK configuration types\n */\n\nexport interface ArkeClientConfig {\n /**\n * Base URL for the Arke API\n * @default 'https://arke-v1.arke.institute'\n */\n baseUrl?: string;\n\n /**\n * Authentication token - accepts either:\n * - JWT token from Supabase auth (sent as Bearer)\n * - Agent API key with 'ak_' prefix (sent as ApiKey)\n * - User API key with 'uk_' prefix (sent as ApiKey)\n *\n * The correct Authorization header format is auto-detected from the token prefix.\n */\n authToken?: string;\n\n /**\n * Network to use ('main' or 'test')\n * Test network uses 'II' prefixed IDs and isolated data\n * @default 'main'\n */\n network?: 'main' | 'test';\n\n /**\n * Callback to refresh auth token when expired\n * Called automatically on 401 responses\n */\n onTokenRefresh?: () => Promise<string>;\n\n /**\n * Custom headers to include in all requests\n */\n headers?: Record<string, string>;\n}\n\nexport const DEFAULT_CONFIG: Required<Pick<ArkeClientConfig, 'baseUrl' | 'network'>> = {\n baseUrl: 'https://arke-v1.arke.institute',\n network: 'main',\n};\n","/**\n * SDK error classes\n */\n\n/**\n * Base error class for all Arke SDK errors\n */\nexport class ArkeError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly status?: number,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'ArkeError';\n // Maintains proper stack trace for where error was thrown\n Error.captureStackTrace?.(this, this.constructor);\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n status: this.status,\n details: this.details,\n };\n }\n}\n\n/**\n * CAS (Compare-And-Swap) conflict - entity was modified by another request\n */\nexport class CASConflictError extends ArkeError {\n constructor(\n public readonly expectedTip?: string,\n public readonly actualTip?: string\n ) {\n super(\n 'Entity was modified by another request. Refresh and retry with the current tip.',\n 'CAS_CONFLICT',\n 409,\n { expectedTip, actualTip }\n );\n this.name = 'CASConflictError';\n }\n}\n\n/**\n * Resource not found\n */\nexport class NotFoundError extends ArkeError {\n constructor(resourceType: string, id: string) {\n super(`${resourceType} not found: ${id}`, 'NOT_FOUND', 404, { resourceType, id });\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * Validation error - invalid request data\n */\nexport class ValidationError extends ArkeError {\n constructor(\n message: string,\n public readonly field?: string,\n details?: unknown\n ) {\n super(message, 'VALIDATION_ERROR', 400, details ?? { field });\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Authentication required or invalid\n */\nexport class AuthenticationError extends ArkeError {\n constructor(message = 'Authentication required') {\n super(message, 'AUTH_REQUIRED', 401);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Permission denied\n */\nexport class ForbiddenError extends ArkeError {\n constructor(action?: string, resource?: string) {\n const msg = action\n ? `Permission denied: ${action}${resource ? ` on ${resource}` : ''}`\n : 'Permission denied';\n super(msg, 'FORBIDDEN', 403, { action, resource });\n this.name = 'ForbiddenError';\n }\n}\n\n/**\n * Parse API error response into appropriate error class\n */\nexport function parseApiError(status: number, body: unknown): ArkeError {\n const errorBody = body as { error?: string; message?: string; details?: unknown } | null;\n const message = errorBody?.error ?? errorBody?.message ?? 'Unknown error';\n\n switch (status) {\n case 400:\n return new ValidationError(message, undefined, errorBody?.details);\n\n case 401:\n return new AuthenticationError(message);\n\n case 403:\n return new ForbiddenError(message);\n\n case 404:\n return new NotFoundError('Resource', 'unknown');\n\n case 409: {\n // Parse CAS conflict details if available\n const details = errorBody?.details as { expected?: string; actual?: string } | undefined;\n return new CASConflictError(details?.expected, details?.actual);\n }\n\n default:\n return new ArkeError(message, 'API_ERROR', status, errorBody?.details);\n }\n}\n","/**\n * Upload Engine\n *\n * Core upload implementation optimized for fast tree visibility:\n * 1. Create folders by depth (with unidirectional 'in' → parent)\n * 2. Create file entities (metadata only, high parallelism)\n * 3. Backlink parents with 'contains' relationships\n * → Tree is now browsable! Users can explore structure immediately.\n * 4. Upload file content via POST /files/{id}/content (byte-based pool, ~200MB in flight)\n * - Direct upload to API endpoint\n * - API streams to R2, computes CID, updates entity atomically\n *\n * Byte-based pool (for uploads):\n * - Maintains ~200MB of data in flight at all times\n * - When a file completes, next file starts immediately (no gaps)\n * - Small files: Many upload in parallel\n * - Large files: Fewer upload in parallel (bandwidth-limited)\n * - Single file > 200MB: Uploads alone when pool is empty\n *\n * This minimizes time-to-browse by:\n * - Creating all entities before uploading content\n * - Using unidirectional 'in' relationship on entity creation\n * - Adding all 'contains' relationships in a single PUT per parent\n */\n\nimport type { ArkeClient } from '../../client/ArkeClient.js';\nimport type { components } from '../../generated/types.js';\nimport type {\n UploadTree,\n UploadOptions,\n UploadResult,\n UploadProgress,\n CreatedFolder,\n CreatedFile,\n CreatedEntity,\n UploadFolder,\n} from './types.js';\n\ntype CreateCollectionRequest = components['schemas']['CreateCollectionRequest'];\ntype CreateFolderRequest = components['schemas']['CreateFolderRequest'];\ntype CreateFileRequest = components['schemas']['CreateFileRequest'];\ntype UpdateFolderRequest = components['schemas']['UpdateFolderRequest'];\ntype UpdateCollectionRequest = components['schemas']['UpdateCollectionRequest'];\n\n// Phase constants\nconst PHASE_COUNT = 3; // creating, backlinking, uploading (excluding complete/error)\nconst PHASE_INDEX: Record<string, number> = {\n creating: 0,\n backlinking: 1,\n uploading: 2,\n complete: 3,\n error: -1,\n};\n\n// =============================================================================\n// Concurrency Utilities\n// =============================================================================\n\n/**\n * Simple concurrency limiter for parallel operations.\n */\nasync function parallelLimit<T, R>(\n items: T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>\n): Promise<R[]> {\n const results: R[] = [];\n let index = 0;\n\n async function worker(): Promise<void> {\n while (index < items.length) {\n const currentIndex = index++;\n const item = items[currentIndex]!;\n results[currentIndex] = await fn(item, currentIndex);\n }\n }\n\n const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());\n await Promise.all(workers);\n\n return results;\n}\n\n// =============================================================================\n// Byte-Based Pool\n// =============================================================================\n\n/** Target bytes in flight (~200MB) */\nconst TARGET_BYTES_IN_FLIGHT = 200 * 1024 * 1024;\n\n/**\n * Pool that maintains a target number of bytes in flight.\n *\n * When a file completes, its bytes are released and the next\n * waiting file can start immediately. This keeps the pipeline full.\n *\n * - Small files: Many run in parallel (up to ~200MB worth)\n * - Large files: Fewer run in parallel\n * - Single file > 200MB: Runs alone (allowed when pool is empty)\n */\nclass BytePool {\n private bytesInFlight = 0;\n private waitQueue: Array<() => void> = [];\n\n constructor(private targetBytes: number = TARGET_BYTES_IN_FLIGHT) {}\n\n async run<T>(size: number, fn: () => Promise<T>): Promise<T> {\n // Wait until we have room\n // Exception: if pool is empty, always allow (handles files > targetBytes)\n while (this.bytesInFlight > 0 && this.bytesInFlight + size > this.targetBytes) {\n await new Promise<void>((resolve) => this.waitQueue.push(resolve));\n }\n\n this.bytesInFlight += size;\n try {\n return await fn();\n } finally {\n this.bytesInFlight -= size;\n // Wake up next waiting task\n const next = this.waitQueue.shift();\n if (next) next();\n }\n }\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Parse folder path to get parent path.\n * e.g., \"docs/images/photos\" -> \"docs/images\"\n */\nfunction getParentPath(relativePath: string): string | null {\n const lastSlash = relativePath.lastIndexOf('/');\n if (lastSlash === -1) return null;\n return relativePath.slice(0, lastSlash);\n}\n\n/**\n * Group folders by depth level.\n */\nfunction groupFoldersByDepth(folders: UploadFolder[]): Map<number, UploadFolder[]> {\n const byDepth = new Map<number, UploadFolder[]>();\n\n for (const folder of folders) {\n const depth = folder.relativePath.split('/').length - 1;\n if (!byDepth.has(depth)) byDepth.set(depth, []);\n byDepth.get(depth)!.push(folder);\n }\n\n return byDepth;\n}\n\n// =============================================================================\n// Main Upload Function\n// =============================================================================\n\n/**\n * Main upload function.\n * Orchestrates the entire upload process with optimized relationship strategy.\n */\nexport async function uploadTree(\n client: ArkeClient,\n tree: UploadTree,\n options: UploadOptions\n): Promise<UploadResult> {\n const { target, onProgress, concurrency = 10, continueOnError = false, note } = options;\n\n const errors: Array<{ path: string; error: string }> = [];\n const createdFolders: CreatedFolder[] = [];\n const createdFiles: CreatedFile[] = [];\n\n // Maps for tracking (include label for peer_label in relationships)\n const foldersByPath = new Map<string, { id: string; cid: string; label: string }>();\n\n // Calculate totals\n const totalEntities = tree.files.length + tree.folders.length;\n const totalBytes = tree.files.reduce((sum, f) => sum + f.size, 0);\n let completedEntities = 0;\n let bytesUploaded = 0;\n\n // Helper to report progress\n const reportProgress = (progress: Partial<UploadProgress>) => {\n if (onProgress) {\n const phase = progress.phase || 'creating';\n const phaseIndex = PHASE_INDEX[phase] ?? -1;\n\n // Calculate phase percent based on current phase\n let phasePercent = 0;\n if (phase === 'creating') {\n // Creating phase: progress is based on entities created\n const done = progress.completedEntities ?? completedEntities;\n phasePercent = totalEntities > 0 ? Math.round((done / totalEntities) * 100) : 100;\n } else if (phase === 'backlinking') {\n // Backlinking phase: progress is based on parents updated\n const done = progress.completedParents ?? 0;\n const total = progress.totalParents ?? 0;\n phasePercent = total > 0 ? Math.round((done / total) * 100) : 100;\n } else if (phase === 'uploading') {\n // Uploading phase: progress is based on bytes uploaded\n const done = progress.bytesUploaded ?? bytesUploaded;\n phasePercent = totalBytes > 0 ? Math.round((done / totalBytes) * 100) : 100;\n } else if (phase === 'complete') {\n phasePercent = 100;\n }\n\n onProgress({\n phase,\n phaseIndex,\n phaseCount: PHASE_COUNT,\n phasePercent,\n totalEntities,\n completedEntities,\n totalParents: 0,\n completedParents: 0,\n totalBytes,\n bytesUploaded,\n ...progress,\n } as UploadProgress);\n }\n };\n\n try {\n // ─────────────────────────────────────────────────────────────────────────\n // SETUP: Resolve or create collection\n // ─────────────────────────────────────────────────────────────────────────\n let collectionId: string;\n let collectionCid: string;\n let collectionLabel: string;\n let collectionCreated = false;\n\n if (target.createCollection) {\n const collectionBody: CreateCollectionRequest = {\n label: target.createCollection.label,\n description: target.createCollection.description,\n roles: target.createCollection.roles,\n note,\n };\n\n const { data, error } = await client.api.POST('/collections', {\n body: collectionBody,\n });\n\n if (error || !data) {\n throw new Error(`Failed to create collection: ${JSON.stringify(error)}`);\n }\n\n collectionId = data.id;\n collectionCid = data.cid;\n collectionLabel = target.createCollection.label;\n collectionCreated = true;\n } else if (target.collectionId) {\n collectionId = target.collectionId;\n\n const { data, error } = await client.api.GET('/collections/{id}', {\n params: { path: { id: collectionId } },\n });\n\n if (error || !data) {\n throw new Error(`Failed to fetch collection: ${JSON.stringify(error)}`);\n }\n\n collectionCid = data.cid;\n collectionLabel = (data.properties?.label as string) ?? collectionId;\n } else {\n throw new Error('Must provide either collectionId or createCollection in target');\n }\n\n // Determine the parent for root-level items\n const rootParentId = target.parentId ?? collectionId;\n let rootParentLabel = collectionLabel;\n let rootParentType: 'collection' | 'folder' = 'collection';\n\n // If a specific parent folder is provided, fetch its label\n if (target.parentId && target.parentId !== collectionId) {\n const { data: parentData, error: parentError } = await client.api.GET('/folders/{id}', {\n params: { path: { id: target.parentId } },\n });\n if (parentError || !parentData) {\n throw new Error(`Failed to fetch parent folder: ${JSON.stringify(parentError)}`);\n }\n rootParentLabel = (parentData.properties?.label as string) ?? target.parentId;\n rootParentType = 'folder';\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 1: Create entities (folders by depth, then files)\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'creating', completedEntities: 0 });\n\n // Group folders by depth\n const foldersByDepth = groupFoldersByDepth(tree.folders);\n const sortedDepths = [...foldersByDepth.keys()].sort((a, b) => a - b);\n\n // Create folders depth by depth (parents before children)\n for (const depth of sortedDepths) {\n const foldersAtDepth = foldersByDepth.get(depth)!;\n\n await Promise.all(\n foldersAtDepth.map(async (folder) => {\n try {\n const parentPath = getParentPath(folder.relativePath);\n const parentInfo = parentPath ? foldersByPath.get(parentPath)! : null;\n const parentId = parentInfo ? parentInfo.id : rootParentId;\n const parentType = parentInfo ? 'folder' : rootParentType;\n const parentLabel = parentInfo ? parentInfo.label : rootParentLabel;\n\n const folderBody: CreateFolderRequest = {\n label: folder.name,\n collection: collectionId,\n note,\n relationships: [{ predicate: 'in', peer: parentId, peer_type: parentType, peer_label: parentLabel }],\n };\n\n const { data, error } = await client.api.POST('/folders', {\n body: folderBody,\n });\n\n if (error || !data) {\n throw new Error(JSON.stringify(error));\n }\n\n // Track folder (include label for peer_label in child relationships)\n foldersByPath.set(folder.relativePath, { id: data.id, cid: data.cid, label: folder.name });\n createdFolders.push({\n name: folder.name,\n relativePath: folder.relativePath,\n id: data.id,\n entityCid: data.cid,\n });\n\n completedEntities++;\n reportProgress({\n phase: 'creating',\n completedEntities,\n currentItem: folder.relativePath,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: folder.relativePath, error: `Folder creation failed: ${errorMsg}` });\n completedEntities++;\n } else {\n throw new Error(`Failed to create folder ${folder.relativePath}: ${errorMsg}`);\n }\n }\n })\n );\n }\n\n // Create file entities (metadata only, no content upload yet)\n // Use simple concurrency limit for API calls\n const FILE_CREATION_CONCURRENCY = 50;\n\n await parallelLimit(tree.files, FILE_CREATION_CONCURRENCY, async (file) => {\n try {\n const parentPath = getParentPath(file.relativePath);\n const parentInfo = parentPath ? foldersByPath.get(parentPath)! : null;\n const parentId = parentInfo ? parentInfo.id : rootParentId;\n const parentType = parentInfo ? 'folder' : rootParentType;\n const parentLabel = parentInfo ? parentInfo.label : rootParentLabel;\n\n // Create file entity with 'in' relationship (include peer_label for display)\n // Server computes CID when content is uploaded\n const fileBody: CreateFileRequest = {\n key: crypto.randomUUID(), // Generate unique storage key\n filename: file.name,\n label: file.name, // Display label for the file\n content_type: file.mimeType,\n size: file.size,\n collection: collectionId,\n relationships: [{ predicate: 'in', peer: parentId, peer_type: parentType, peer_label: parentLabel }],\n };\n\n const { data, error } = await client.api.POST('/files', {\n body: fileBody,\n });\n\n if (error || !data) {\n throw new Error(`Entity creation failed: ${JSON.stringify(error)}`);\n }\n\n // Track file for later upload\n createdFiles.push({\n ...file,\n id: data.id,\n entityCid: data.cid,\n });\n\n completedEntities++;\n reportProgress({\n phase: 'creating',\n completedEntities,\n currentItem: file.relativePath,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: file.relativePath, error: errorMsg });\n completedEntities++;\n } else {\n throw new Error(`Failed to create file ${file.relativePath}: ${errorMsg}`);\n }\n }\n });\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 2: Backlink - Update each parent with 'contains' relationships\n // ─────────────────────────────────────────────────────────────────────────\n\n // Build parent -> children map (include label for peer_label)\n const childrenByParent = new Map<string, Array<{ id: string; type: 'file' | 'folder'; label: string }>>();\n\n // Add folders as children of their parents\n for (const folder of createdFolders) {\n const parentPath = getParentPath(folder.relativePath);\n const parentId = parentPath ? foldersByPath.get(parentPath)!.id : rootParentId;\n\n if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);\n childrenByParent.get(parentId)!.push({ id: folder.id, type: 'folder', label: folder.name });\n }\n\n // Add files as children of their parents\n for (const file of createdFiles) {\n const parentPath = getParentPath(file.relativePath);\n const parentId = parentPath ? foldersByPath.get(parentPath)!.id : rootParentId;\n\n if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);\n childrenByParent.get(parentId)!.push({ id: file.id, type: 'file', label: file.name });\n }\n\n const totalParents = childrenByParent.size;\n let completedParents = 0;\n\n reportProgress({ phase: 'backlinking', totalParents, completedParents: 0 });\n\n // Update all parents in parallel - each parent gets one PUT with all its children\n const parentEntries = [...childrenByParent.entries()];\n\n await parallelLimit(parentEntries, concurrency, async ([parentId, children]) => {\n try {\n const isCollection = parentId === collectionId;\n\n // Build relationships_add array with all children (include peer_label for display)\n const relationshipsAdd = children.map((child) => ({\n predicate: 'contains' as const,\n peer: child.id,\n peer_type: child.type,\n peer_label: child.label,\n }));\n\n if (isCollection) {\n // Get current collection CID for CAS\n const { data: collData, error: getError } = await client.api.GET('/collections/{id}', {\n params: { path: { id: parentId } },\n });\n if (getError || !collData) {\n throw new Error(`Failed to fetch collection: ${JSON.stringify(getError)}`);\n }\n\n // Update collection with relationships_add\n const updateBody: UpdateCollectionRequest = {\n expect_tip: collData.cid,\n relationships_add: relationshipsAdd,\n note: note ? `${note} (backlink)` : 'Upload backlink',\n };\n\n const { error } = await client.api.PUT('/collections/{id}', {\n params: { path: { id: parentId } },\n body: updateBody,\n });\n\n if (error) {\n throw new Error(JSON.stringify(error));\n }\n } else {\n // Get current folder CID for CAS\n const { data: folderData, error: getError } = await client.api.GET('/folders/{id}', {\n params: { path: { id: parentId } },\n });\n if (getError || !folderData) {\n throw new Error(`Failed to fetch folder: ${JSON.stringify(getError)}`);\n }\n\n // Update folder with relationships_add\n const updateBody: UpdateFolderRequest = {\n expect_tip: folderData.cid,\n relationships_add: relationshipsAdd,\n note: note ? `${note} (backlink)` : 'Upload backlink',\n };\n\n const { error } = await client.api.PUT('/folders/{id}', {\n params: { path: { id: parentId } },\n body: updateBody,\n });\n\n if (error) {\n throw new Error(JSON.stringify(error));\n }\n }\n\n completedParents++;\n reportProgress({\n phase: 'backlinking',\n totalParents,\n completedParents,\n currentItem: `parent:${parentId}`,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: `parent:${parentId}`, error: `Backlink failed: ${errorMsg}` });\n completedParents++;\n } else {\n throw new Error(`Failed to backlink parent ${parentId}: ${errorMsg}`);\n }\n }\n });\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 3: Upload file content directly to API\n // Tree is now browsable! Users can explore while content uploads.\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'uploading', bytesUploaded: 0 });\n\n // Use byte-based pool to maintain ~200MB in flight\n const pool = new BytePool();\n\n await Promise.all(\n createdFiles.map(async (file) => {\n await pool.run(file.size, async () => {\n try {\n // Get file data\n const fileData = await file.getData();\n\n let body: Blob;\n if (fileData instanceof Blob) {\n body = fileData;\n } else if (fileData instanceof Uint8Array) {\n const arrayBuffer = new ArrayBuffer(fileData.byteLength);\n new Uint8Array(arrayBuffer).set(fileData);\n body = new Blob([arrayBuffer], { type: file.mimeType });\n } else {\n body = new Blob([fileData], { type: file.mimeType });\n }\n\n // Upload content directly to API endpoint\n // The API streams to R2, computes CID, and updates the entity atomically\n const { error: uploadError } = await client.api.POST('/files/{id}/content', {\n params: { path: { id: file.id } },\n body: body as unknown as Record<string, never>,\n bodySerializer: (b: unknown) => b as BodyInit,\n headers: { 'Content-Type': file.mimeType },\n } as Parameters<typeof client.api.POST>[1]);\n\n if (uploadError) {\n throw new Error(`Upload failed: ${JSON.stringify(uploadError)}`);\n }\n\n bytesUploaded += file.size;\n reportProgress({\n phase: 'uploading',\n bytesUploaded,\n currentItem: file.relativePath,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: file.relativePath, error: `Upload failed: ${errorMsg}` });\n } else {\n throw new Error(`Failed to upload ${file.relativePath}: ${errorMsg}`);\n }\n }\n });\n })\n );\n\n // ─────────────────────────────────────────────────────────────────────────\n // Complete!\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'complete', totalParents, completedParents, bytesUploaded });\n\n const resultFolders: CreatedEntity[] = createdFolders.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'folder' as const,\n relativePath: f.relativePath,\n }));\n\n const resultFiles: CreatedEntity[] = createdFiles.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'file' as const,\n relativePath: f.relativePath,\n }));\n\n return {\n success: errors.length === 0,\n collection: {\n id: collectionId,\n cid: collectionCid,\n created: collectionCreated,\n },\n folders: resultFolders,\n files: resultFiles,\n errors,\n };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n\n reportProgress({\n phase: 'error',\n error: errorMsg,\n });\n\n return {\n success: false,\n collection: {\n id: target.collectionId ?? '',\n cid: '',\n created: false,\n },\n folders: createdFolders.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'folder' as const,\n relativePath: f.relativePath,\n })),\n files: createdFiles.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'file' as const,\n relativePath: f.relativePath,\n })),\n errors: [...errors, { path: '', error: errorMsg }],\n };\n }\n}\n","/**\n * CID Computation Utility\n *\n * Computes IPFS CIDv1 (base32) for file content.\n * Uses raw codec (0x55) and SHA-256 hash.\n *\n * Note: This module is not used internally by the upload engine (the server\n * computes CIDs from uploaded content). It is exported for convenience in case\n * you want to verify entity CIDs, detect duplicates before upload, or perform\n * other content-addressed operations.\n */\n\nimport { CID } from 'multiformats/cid';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport * as raw from 'multiformats/codecs/raw';\n\n/**\n * Compute CIDv1 for binary content.\n * Returns base32 encoded string (bafk... prefix for raw codec).\n *\n * @param data - Binary content as ArrayBuffer, Uint8Array, or Blob\n * @returns CIDv1 string in base32 encoding\n *\n * @example\n * ```typescript\n * const cid = await computeCid(new TextEncoder().encode('hello world'));\n * // Returns: \"bafkreifzjut3te2nhyekklss27nh3k72ysco7y32koao5eei66wof36n5e\"\n * ```\n */\nexport async function computeCid(data: ArrayBuffer | Uint8Array | Blob): Promise<string> {\n // Convert to Uint8Array\n let bytes: Uint8Array;\n\n if (data instanceof Blob) {\n const buffer = await data.arrayBuffer();\n bytes = new Uint8Array(buffer);\n } else if (data instanceof ArrayBuffer) {\n bytes = new Uint8Array(data);\n } else {\n bytes = data;\n }\n\n // Compute SHA-256 hash\n const hash = await sha256.digest(bytes);\n\n // Create CIDv1 with raw codec\n const cid = CID.create(1, raw.code, hash);\n\n // Return base32 encoded string\n return cid.toString();\n}\n\n/**\n * Verify a CID matches the content.\n *\n * @param data - Binary content\n * @param expectedCid - CID to verify against\n * @returns true if CID matches\n */\nexport async function verifyCid(\n data: ArrayBuffer | Uint8Array | Blob,\n expectedCid: string\n): Promise<boolean> {\n const computed = await computeCid(data);\n return computed === expectedCid;\n}\n","/**\n * Folder Operations (Legacy)\n *\n * @deprecated Use the new upload module instead:\n * ```typescript\n * import { uploadTree, buildUploadTree } from '@arke-institute/sdk/operations';\n *\n * const tree = buildUploadTree([\n * { path: 'docs/readme.md', data: readmeBuffer },\n * { path: 'images/logo.png', data: logoBlob },\n * ]);\n * const result = await uploadTree(client, tree, {\n * target: { collectionId: '...' },\n * });\n * ```\n */\n\nimport type { ArkeClient } from '../client/ArkeClient.js';\n\n/**\n * @deprecated Use UploadProgress from upload module\n */\nexport interface UploadProgress {\n phase: 'scanning' | 'creating-folders' | 'uploading-files' | 'linking' | 'complete';\n totalFiles: number;\n completedFiles: number;\n totalFolders: number;\n completedFolders: number;\n currentFile?: string;\n}\n\n/**\n * @deprecated Use UploadOptions from upload module\n */\nexport interface UploadDirectoryOptions {\n /** Collection to upload into */\n collectionId: string;\n /** Parent folder ID (optional - creates at root if not provided) */\n parentFolderId?: string;\n /** Progress callback */\n onProgress?: (progress: UploadProgress) => void;\n /** Max concurrent uploads */\n concurrency?: number;\n}\n\n/**\n * @deprecated Use UploadResult from upload module\n */\nexport interface UploadDirectoryResult {\n /** Root folder entity */\n rootFolder: unknown;\n /** All created folder entities */\n folders: unknown[];\n /** All created file entities */\n files: unknown[];\n}\n\n/**\n * Folder operations helper\n *\n * @deprecated Use uploadTree and buildUploadTree functions instead:\n * ```typescript\n * import { uploadTree, buildUploadTree } from '@arke-institute/sdk/operations';\n *\n * const tree = buildUploadTree([\n * { path: 'docs/readme.md', data: readmeBuffer },\n * ]);\n * const result = await uploadTree(client, tree, {\n * target: { collectionId: '...' },\n * });\n * ```\n */\nexport class FolderOperations {\n constructor(private client: ArkeClient) {\n void client; // Suppress unused warning\n }\n\n /**\n * Upload a local directory to Arke\n *\n * @deprecated This method has been removed. Use uploadTree and buildUploadTree instead.\n */\n async uploadDirectory(\n _localPath: string,\n _options: UploadDirectoryOptions\n ): Promise<UploadDirectoryResult> {\n throw new Error(\n 'FolderOperations.uploadDirectory has been removed. ' +\n 'Use uploadTree() with buildUploadTree() instead. ' +\n 'See: https://github.com/arke-institute/arke-sdk#upload-module'\n );\n }\n}\n","/**\n * Batch Operations\n *\n * High-level operations for bulk entity and relationship management.\n *\n * TODO: Implement batch operations\n * - createEntities: Create multiple entities in parallel\n * - updateEntities: Update multiple entities in parallel\n * - createRelationships: Create multiple relationships in parallel\n */\n\nimport type { ArkeClient } from '../client/ArkeClient.js';\n\nexport interface BatchCreateOptions {\n /** Max concurrent operations */\n concurrency?: number;\n /** Continue on individual failures */\n continueOnError?: boolean;\n /** Progress callback */\n onProgress?: (completed: number, total: number) => void;\n}\n\nexport interface BatchResult<T> {\n /** Successfully completed operations */\n succeeded: T[];\n /** Failed operations with errors */\n failed: Array<{ input: unknown; error: Error }>;\n}\n\n/**\n * Batch operations helper\n *\n * @example\n * ```typescript\n * const batch = new BatchOperations(arkeClient);\n * const result = await batch.createEntities([\n * { type: 'document', properties: { title: 'Doc 1' } },\n * { type: 'document', properties: { title: 'Doc 2' } },\n * ], { concurrency: 5 });\n * ```\n */\nexport class BatchOperations {\n constructor(private client: ArkeClient) {}\n\n /**\n * Create multiple entities in parallel\n *\n * TODO: Implement this method\n */\n async createEntities(\n _entities: Array<{\n collectionId: string;\n type: string;\n properties?: Record<string, unknown>;\n }>,\n _options?: BatchCreateOptions\n ): Promise<BatchResult<unknown>> {\n throw new Error('BatchOperations.createEntities is not yet implemented');\n }\n\n /**\n * Create multiple relationships in parallel\n *\n * TODO: Implement this method\n */\n async createRelationships(\n _relationships: Array<{\n sourceId: string;\n targetId: string;\n predicate: string;\n bidirectional?: boolean;\n properties?: Record<string, unknown>;\n }>,\n _options?: BatchCreateOptions\n ): Promise<BatchResult<unknown>> {\n throw new Error('BatchOperations.createRelationships is not yet implemented');\n }\n}\n","/**\n * Crypto Operations\n *\n * Cryptographic utilities for agents and content addressing.\n *\n * TODO: Implement crypto operations\n * - generateKeyPair: Generate Ed25519 key pair for agent authentication\n * - signPayload: Sign a payload with agent private key\n * - computeCID: Compute IPFS CID for content\n */\n\n/**\n * Ed25519 key pair for agent authentication\n */\nexport interface KeyPair {\n /** Public key in base64 */\n publicKey: string;\n /** Private key in base64 (keep secret!) */\n privateKey: string;\n}\n\n/**\n * Signed payload with signature\n */\nexport interface SignedPayload {\n /** Original payload */\n payload: string;\n /** Ed25519 signature in base64 */\n signature: string;\n /** Timestamp of signature */\n timestamp: number;\n}\n\n/**\n * Crypto operations helper\n *\n * @example\n * ```typescript\n * // Generate key pair for a new agent\n * const { publicKey, privateKey } = await CryptoOperations.generateKeyPair();\n *\n * // Sign a payload\n * const signed = await CryptoOperations.signPayload(privateKey, payload);\n * ```\n */\nexport class CryptoOperations {\n /**\n * Generate an Ed25519 key pair for agent authentication\n *\n * TODO: Implement using Node.js crypto or Web Crypto API\n */\n static async generateKeyPair(): Promise<KeyPair> {\n throw new Error('CryptoOperations.generateKeyPair is not yet implemented');\n }\n\n /**\n * Sign a payload with an Ed25519 private key\n *\n * TODO: Implement signature generation\n */\n static async signPayload(_privateKey: string, _payload: string): Promise<SignedPayload> {\n throw new Error('CryptoOperations.signPayload is not yet implemented');\n }\n\n /**\n * Verify an Ed25519 signature\n *\n * TODO: Implement signature verification\n */\n static async verifySignature(\n _publicKey: string,\n _payload: string,\n _signature: string\n ): Promise<boolean> {\n throw new Error('CryptoOperations.verifySignature is not yet implemented');\n }\n\n /**\n * Compute IPFS CID for content\n *\n * TODO: Implement using multiformats library\n */\n static async computeCID(_content: Uint8Array): Promise<string> {\n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C/C,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa,YAAY,aAAqB,UAA0C;AACtF,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa,gBACX,YACA,UACA,YACkB;AAClB,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa,WAAW,UAAuC;AAC7D,UAAM,IAAI,MAAM,oDAAoD;AAAA,EACtE;AACF;","names":["code"]}
@@ -1,5 +1,5 @@
1
- import { A as ArkeClient, j as UploadTree, k as UploadOptions, l as UploadResult } from '../crypto-D7rJLGQQ.cjs';
2
- export { f as BatchCreateOptions, B as BatchOperations, h as BatchResult, p as CreatedEntity, C as CryptoOperations, F as FolderOperations, K as KeyPair, S as SignedPayload, d as UploadDirectoryOptions, e as UploadDirectoryResult, m as UploadFile, n as UploadFolder, U as UploadProgress, o as UploadTarget } from '../crypto-D7rJLGQQ.cjs';
1
+ import { A as ArkeClient, j as UploadTree, k as UploadOptions, l as UploadResult } from '../crypto-k-x66Nei.cjs';
2
+ export { f as BatchCreateOptions, B as BatchOperations, h as BatchResult, p as CreatedEntity, C as CryptoOperations, F as FolderOperations, K as KeyPair, S as SignedPayload, d as UploadDirectoryOptions, e as UploadDirectoryResult, m as UploadFile, n as UploadFolder, U as UploadProgress, o as UploadTarget } from '../crypto-k-x66Nei.cjs';
3
3
  import 'openapi-fetch';
4
4
  import '../generated/index.cjs';
5
5
 
@@ -1,5 +1,5 @@
1
- import { A as ArkeClient, j as UploadTree, k as UploadOptions, l as UploadResult } from '../crypto-s98kufbt.js';
2
- export { f as BatchCreateOptions, B as BatchOperations, h as BatchResult, p as CreatedEntity, C as CryptoOperations, F as FolderOperations, K as KeyPair, S as SignedPayload, d as UploadDirectoryOptions, e as UploadDirectoryResult, m as UploadFile, n as UploadFolder, U as UploadProgress, o as UploadTarget } from '../crypto-s98kufbt.js';
1
+ import { A as ArkeClient, j as UploadTree, k as UploadOptions, l as UploadResult } from '../crypto-Fh8b6rTi.js';
2
+ export { f as BatchCreateOptions, B as BatchOperations, h as BatchResult, p as CreatedEntity, C as CryptoOperations, F as FolderOperations, K as KeyPair, S as SignedPayload, d as UploadDirectoryOptions, e as UploadDirectoryResult, m as UploadFile, n as UploadFolder, U as UploadProgress, o as UploadTarget } from '../crypto-Fh8b6rTi.js';
3
3
  import 'openapi-fetch';
4
4
  import '../generated/index.js';
5
5