@opendatalabs/vana-sdk
Version:
A TypeScript library for interacting with Vana Network smart contracts.
1 lines • 13.6 kB
Source Map (JSON)
{"version":3,"sources":["../../../src/storage/providers/callback-storage.ts"],"sourcesContent":["/**\n * Provides user-defined storage operations through callback functions.\n *\n * @remarks\n * This module implements a flexible storage provider that delegates all\n * operations to user-provided callbacks. It enables custom storage\n * integrations without modifying the SDK, supporting any backend including\n * HTTP APIs, WebSocket servers, cloud storage services, or local filesystems.\n *\n * @category Storage\n * @module storage/providers/callback-storage\n */\n\nimport type { StorageCallbacks } from \"../../types/config\";\nimport {\n StorageError,\n type StorageProvider,\n type StorageUploadResult,\n type StorageFile,\n type StorageListOptions,\n type StorageProviderConfig,\n} from \"../../types/storage\";\n\n/**\n * Delegates storage operations to user-provided callback functions.\n *\n * @remarks\n * This provider enables custom storage integrations by delegating all\n * operations to user-defined callbacks. It follows the same flexible\n * pattern as relayer callbacks, allowing implementations via HTTP,\n * WebSocket, direct cloud APIs, local filesystem, or any other backend.\n *\n * The provider validates callback results and wraps errors in consistent\n * `StorageError` types for uniform error handling across the SDK.\n *\n * @example\n * ```typescript\n * // HTTP-based implementation\n * const httpCallbacks: StorageCallbacks = {\n * async upload(blob, filename) {\n * const formData = new FormData();\n * formData.append('file', blob, filename);\n * const response = await fetch('/api/storage/upload', {\n * method: 'POST',\n * body: formData\n * });\n * const data = await response.json();\n * return {\n * url: data.url,\n * size: blob.size,\n * contentType: blob.type\n * };\n * },\n * async download(identifier) {\n * const response = await fetch(`/api/storage/download/${identifier}`);\n * return response.blob();\n * }\n * };\n *\n * const storage = new CallbackStorage(httpCallbacks);\n *\n * // Direct S3 implementation\n * const s3Callbacks: StorageCallbacks = {\n * async upload(blob, filename) {\n * const url = await getPresignedUploadUrl(filename);\n * await fetch(url, { method: 'PUT', body: blob });\n * return {\n * url: `s3://my-bucket/${filename}`,\n * size: blob.size,\n * contentType: blob.type\n * };\n * },\n * async download(identifier) {\n * const url = await getPresignedDownloadUrl(identifier);\n * const response = await fetch(url);\n * return response.blob();\n * }\n * };\n * ```\n *\n * @category Storage\n */\nexport class CallbackStorage implements StorageProvider {\n /**\n * Creates a new callback-based storage provider.\n *\n * @param callbacks - User-provided storage operation callbacks.\n * Must include at minimum `upload` and `download` functions.\n * @throws {Error} If required callbacks are missing\n */\n constructor(private readonly callbacks: StorageCallbacks) {\n if (!callbacks.upload || !callbacks.download) {\n throw new Error(\n \"CallbackStorage requires both upload and download callbacks\",\n );\n }\n }\n\n /**\n * Uploads a file using the user-provided callback.\n *\n * @param file - The blob to upload.\n * Can be any Blob-compatible object including File.\n * @param filename - Optional filename for the upload.\n * If not provided, callback may generate a name.\n * @returns Upload result containing URL and metadata\n *\n * @throws {StorageError} With code 'INVALID_UPLOAD_RESULT' if callback returns invalid data\n * @throws {StorageError} With code 'UPLOAD_ERROR' if upload fails\n *\n * @example\n * ```typescript\n * const file = new File(['content'], 'data.json');\n * const result = await storage.upload(file);\n * console.log('Uploaded to:', result.url);\n * ```\n */\n async upload(file: Blob, filename?: string): Promise<StorageUploadResult> {\n try {\n const result = await this.callbacks.upload(file, filename);\n\n // Validate the result has required fields\n if (!result.url || result.url.trim() === \"\") {\n throw new StorageError(\n \"Upload callback returned invalid result: missing or empty url\",\n \"INVALID_UPLOAD_RESULT\",\n \"callback-storage\",\n );\n }\n\n return result;\n } catch (error) {\n if (error instanceof StorageError) {\n throw error;\n }\n throw new StorageError(\n `Upload failed: ${error instanceof Error ? error.message : String(error)}`,\n \"UPLOAD_ERROR\",\n \"callback-storage\",\n { cause: error instanceof Error ? error : undefined },\n );\n }\n }\n\n /**\n * Downloads a file using the user-provided callback.\n *\n * @param url - The URL or identifier to download.\n * If `extractIdentifier` callback is provided, it will be used to extract the identifier.\n * @returns The downloaded file as a Blob\n *\n * @throws {StorageError} With code 'INVALID_DOWNLOAD_RESULT' if callback returns non-Blob\n * @throws {StorageError} With code 'DOWNLOAD_ERROR' if download fails\n *\n * @example\n * ```typescript\n * const blob = await storage.download('https://storage.example.com/file123');\n * const text = await blob.text();\n * ```\n */\n async download(url: string): Promise<Blob> {\n try {\n // Extract identifier if callback is provided, otherwise use URL as-is\n const identifier = this.callbacks.extractIdentifier\n ? this.callbacks.extractIdentifier(url)\n : url;\n\n const blob = await this.callbacks.download(identifier);\n\n if (!(blob instanceof Blob)) {\n throw new StorageError(\n \"Download callback returned invalid result: expected Blob\",\n \"INVALID_DOWNLOAD_RESULT\",\n \"callback-storage\",\n );\n }\n\n return blob;\n } catch (error) {\n if (error instanceof StorageError) {\n throw error;\n }\n throw new StorageError(\n `Download failed: ${error instanceof Error ? error.message : String(error)}`,\n \"DOWNLOAD_ERROR\",\n \"callback-storage\",\n { cause: error instanceof Error ? error : undefined },\n );\n }\n }\n\n /**\n * Lists files using the user-provided callback.\n *\n * @param options - Optional list options.\n * @param options.namePattern - Pattern to filter files by name.\n * Implementation depends on callback.\n * @param options.limit - Maximum number of files to return.\n * Implementation depends on callback.\n * @returns Array of storage file metadata\n *\n * @throws {StorageError} With code 'NOT_SUPPORTED' if list callback not provided\n * @throws {StorageError} With code 'LIST_ERROR' if listing fails\n *\n * @remarks\n * This operation is optional and only available if a `list` callback\n * is provided during construction.\n *\n * @example\n * ```typescript\n * const files = await storage.list({ namePattern: '*.json' });\n * files.forEach(file => console.log(file.name, file.size));\n * ```\n */\n async list(options?: StorageListOptions): Promise<StorageFile[]> {\n if (!this.callbacks.list) {\n throw new StorageError(\n \"List operation not supported - no list callback provided\",\n \"NOT_SUPPORTED\",\n \"callback-storage\",\n );\n }\n\n try {\n const result = await this.callbacks.list(options?.namePattern, options);\n\n // Convert list result to StorageFile format\n return result.items.map((item, index) => ({\n id: item.identifier,\n name: item.identifier.split(\"/\").pop() ?? `file-${index}`,\n url: item.identifier,\n size: item.size ?? 0,\n contentType: \"application/octet-stream\",\n createdAt: item.lastModified ?? new Date(),\n metadata: item.metadata,\n }));\n } catch (error) {\n throw new StorageError(\n `List failed: ${error instanceof Error ? error.message : String(error)}`,\n \"LIST_ERROR\",\n \"callback-storage\",\n { cause: error instanceof Error ? error : undefined },\n );\n }\n }\n\n /**\n * Deletes a file using the user-provided callback.\n *\n * @param url - The URL or identifier to delete.\n * If `extractIdentifier` callback is provided, it will be used to extract the identifier.\n * @returns True if deletion succeeded, false otherwise\n *\n * @throws {StorageError} With code 'NOT_SUPPORTED' if delete callback not provided\n * @throws {StorageError} With code 'DELETE_ERROR' if deletion fails\n *\n * @remarks\n * This operation is optional and only available if a `delete` callback\n * is provided during construction.\n *\n * @example\n * ```typescript\n * const deleted = await storage.delete('https://storage.example.com/file123');\n * if (deleted) {\n * console.log('File deleted successfully');\n * }\n * ```\n */\n async delete(url: string): Promise<boolean> {\n if (!this.callbacks.delete) {\n throw new StorageError(\n \"Delete operation not supported - no delete callback provided\",\n \"NOT_SUPPORTED\",\n \"callback-storage\",\n );\n }\n\n try {\n // Extract identifier if callback is provided, otherwise use URL as-is\n const identifier = this.callbacks.extractIdentifier\n ? this.callbacks.extractIdentifier(url)\n : url;\n\n return await this.callbacks.delete(identifier);\n } catch (error) {\n throw new StorageError(\n `Delete failed: ${error instanceof Error ? error.message : String(error)}`,\n \"DELETE_ERROR\",\n \"callback-storage\",\n { cause: error instanceof Error ? error : undefined },\n );\n }\n }\n\n /**\n * Returns the provider's configuration and capabilities.\n *\n * @returns Configuration object indicating supported features\n *\n * @example\n * ```typescript\n * const config = storage.getConfig();\n * if (config.features.list) {\n * // List operation is supported\n * const files = await storage.list();\n * }\n * ```\n */\n getConfig(): StorageProviderConfig {\n return {\n name: \"callback-storage\",\n type: \"callback\",\n requiresAuth: false,\n features: {\n upload: true,\n download: true,\n list: !!this.callbacks.list,\n delete: !!this.callbacks.delete,\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,qBAOO;AA6DA,MAAM,gBAA2C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQtD,YAA6B,WAA6B;AAA7B;AAC3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