import { CreatePreAuthUploadUrlPayload, FileSearchOptions, FileSearchResultSet, FileStorageBase, GetObjectParams, GetObjectMetadataParams, GetObjectStreamParams, ObjectStreamResult, StorageListResult, StorageObjectMetadata, StorageProviderConfig } from '../generic/FileStorageBase.js'; /** * Azure Blob Storage implementation of the FileStorageBase interface. * * This class provides methods for interacting with Azure Blob Storage as a file storage provider. * It implements all the abstract methods defined in FileStorageBase and handles Azure-specific * authentication, authorization, and file operations. * * It requires the following environment variables to be set: * - STORAGE_AZURE_CONTAINER: The name of the Azure Storage container * - STORAGE_AZURE_ACCOUNT_NAME: The Azure Storage account name * - STORAGE_AZURE_ACCOUNT_KEY: The Azure Storage account key * * @example * ```typescript * // Create an instance of AzureFileStorage * const azureStorage = new AzureFileStorage(); * * // Generate a pre-authenticated upload URL * const { UploadUrl } = await azureStorage.CreatePreAuthUploadUrl('documents/report.pdf'); * * // Generate a pre-authenticated download URL * const downloadUrl = await azureStorage.CreatePreAuthDownloadUrl('documents/report.pdf'); * * // List files in a directory * const files = await azureStorage.ListObjects('documents/'); * ``` */ export declare class AzureFileStorage extends FileStorageBase { /** The name of this storage provider, used in error messages */ protected readonly providerName = "Azure Blob Storage"; /** Azure Storage SharedKeyCredential for authentication */ private _sharedKeyCredential; /** The Azure Storage container name */ private _container; /** The Azure Storage account name */ private _azureAccountName; /** ContainerClient for the specified container */ private _containerClient; /** BlobServiceClient for the Azure Storage account */ private _blobServiceClient; /** * Creates a new instance of AzureFileStorage. * * Initializes the connection to Azure Blob Storage using environment variables. * Throws an error if any required environment variables are missing. */ constructor(); /** * Initialize Azure Blob Storage provider. * * **Always call this method** after creating an instance. * * @example Simple Deployment (Environment Variables) * const storage = new AzureFileStorage(); // Constructor loads env vars * await storage.initialize(); // No config - uses env vars * await storage.ListObjects('/'); * * @example Multi-Tenant (Database Credentials) * const storage = new AzureFileStorage(); * await storage.initialize({ * accountId: '12345', * accountName: 'Azure Account', * accountName: 'myaccount', * accountKey: '...', * defaultContainer: 'my-container' * }); * * @param config - Optional. Omit to use env vars, provide to override with database creds. */ initialize(config?: StorageProviderConfig): Promise; /** * Checks if Azure Blob provider is properly configured. * Returns true if account name, account key, and container name are present. * Logs detailed error messages if configuration is incomplete. */ get IsConfigured(): boolean; /** * Creates a BlobClient for the specified object. * * This is a helper method used internally to get a BlobClient instance * for a specific blob (file) in the container. * * @param objectName - The name of the blob for which to create a client * @returns A BlobClient instance for the specified blob * @private */ private _getBlobClient; /** * Normalizes a directory path to ensure it ends with a slash. * * This is a helper method used internally to ensure consistency in * directory path representation. Azure Blob Storage doesn't have actual * directories, so we use a trailing slash to simulate them. * * @param path - The directory path to normalize * @returns The normalized path with a trailing slash * @private */ private _normalizeDirectoryPath; /** * Creates a pre-authenticated upload URL for a blob in Azure Blob Storage. * * This method generates a Shared Access Signature (SAS) URL that allows * for uploading a blob without needing the Azure Storage account credentials. * The URL is valid for 10 minutes and can only be used for writing the specified blob. * * @param objectName - The name of the blob to upload (including any path/directory) * @returns A Promise resolving to an object with the upload URL * * @example * ```typescript * // Generate a pre-authenticated upload URL for a PDF file * const { UploadUrl } = await azureStorage.CreatePreAuthUploadUrl('documents/report.pdf'); * * // The URL can be used with tools like curl to upload the file * // curl -H "x-ms-blob-type: BlockBlob" --upload-file report.pdf --url "https://accountname.blob.core.windows.net/container/documents/report.pdf?sastoken" * console.log(UploadUrl); * ``` */ CreatePreAuthUploadUrl(objectName: string): Promise; /** * Creates a pre-authenticated download URL for a blob in Azure Blob Storage. * * This method generates a Shared Access Signature (SAS) URL that allows * for downloading a blob without needing the Azure Storage account credentials. * The URL is valid for 10 minutes and can only be used for reading the specified blob. * * @param objectName - The name of the blob to download (including any path/directory) * @returns A Promise resolving to the download URL * * @example * ```typescript * // Generate a pre-authenticated download URL for a PDF file * const downloadUrl = await azureStorage.CreatePreAuthDownloadUrl('documents/report.pdf'); * * // The URL can be shared with users or used in applications for direct download * console.log(downloadUrl); * ``` */ CreatePreAuthDownloadUrl(objectName: string): Promise; /** * Moves a blob from one location to another within Azure Blob Storage. * * Since Azure Blob Storage doesn't provide a native move operation, * this method implements move as a copy followed by a delete operation. * It first copies the blob to the new location, and if successful, * deletes the blob from the original location. * * @param oldObjectName - The current name/path of the blob * @param newObjectName - The new name/path for the blob * @returns A Promise resolving to a boolean indicating success * * @example * ```typescript * // Move a file from drafts to published folder * const success = await azureStorage.MoveObject( * 'drafts/report.docx', * 'published/final-report.docx' * ); * * if (success) { * console.log('File successfully moved'); * } else { * console.log('Failed to move file'); * } * ``` */ MoveObject(oldObjectName: string, newObjectName: string): Promise; /** * Deletes a blob from Azure Blob Storage. * * This method attempts to delete the specified blob if it exists. * It returns true if the blob was successfully deleted or if it didn't exist. * * @param objectName - The name of the blob to delete (including any path/directory) * @returns A Promise resolving to a boolean indicating success * * @example * ```typescript * // Delete a temporary file * const deleted = await azureStorage.DeleteObject('temp/report-draft.pdf'); * * if (deleted) { * console.log('File successfully deleted'); * } else { * console.log('Failed to delete file'); * } * ``` */ DeleteObject(objectName: string): Promise; /** * Lists blobs with the specified prefix in Azure Blob Storage. * * This method returns a list of blobs (files) and virtual directories under the * specified path prefix. Since Azure Blob Storage doesn't have actual directories, * this method simulates directory structure by looking at blob names with common * prefixes and using the delimiter to identify "directory" paths. * * @param prefix - The path prefix to list blobs from (e.g., 'documents/') * @param delimiter - The character used to simulate directory structure, defaults to '/' * @returns A Promise resolving to a StorageListResult containing objects and prefixes * * @example * ```typescript * // List all files and directories in the documents folder * const result = await azureStorage.ListObjects('documents/'); * * // Process files * for (const file of result.objects) { * console.log(`File: ${file.name}, Size: ${file.size}, Type: ${file.contentType}`); * } * * // Process subdirectories * for (const dir of result.prefixes) { * console.log(`Directory: ${dir}`); * } * ``` */ ListObjects(prefix: string, delimiter?: string): Promise; /** * Creates a directory (virtual) in Azure Blob Storage. * * Since Azure Blob Storage doesn't have a native directory concept, * this method creates a zero-byte blob with a trailing slash to * simulate a directory. The blob has a special content type to * indicate it's a directory. * * @param directoryPath - The path of the directory to create * @returns A Promise resolving to a boolean indicating success * * @example * ```typescript * // Create a new directory structure * const created = await azureStorage.CreateDirectory('documents/reports/annual/'); * * if (created) { * console.log('Directory created successfully'); * } else { * console.log('Failed to create directory'); * } * ``` */ CreateDirectory(directoryPath: string): Promise; /** * Deletes a directory (virtual) and optionally its contents from Azure Blob Storage. * * For non-recursive deletion, this method simply deletes the directory placeholder blob. * For recursive deletion, it lists all blobs with the directory path as prefix * and deletes them all, including the directory placeholder. * * @param directoryPath - The path of the directory to delete * @param recursive - If true, deletes all contents recursively (default: false) * @returns A Promise resolving to a boolean indicating success * * @example * ```typescript * // Delete an empty directory * const deleted = await azureStorage.DeleteDirectory('documents/temp/'); * * // Delete a directory and all its contents * const recursivelyDeleted = await azureStorage.DeleteDirectory('documents/old_projects/', true); * ``` */ DeleteDirectory(directoryPath: string, recursive?: boolean): Promise; /** * Retrieves metadata for a specific blob in Azure Blob Storage. * * This method fetches the properties of a blob without downloading its content, * which is more efficient for checking file attributes like size, content type, * and last modified date. * * @param params - Object identifier (objectId and fullPath are equivalent for Azure Blob) * @returns A Promise resolving to a StorageObjectMetadata object * @throws Error if the blob doesn't exist or cannot be accessed * * @example * ```typescript * try { * // For Azure Blob, objectId and fullPath are the same (both are the blob name) * const metadata = await azureStorage.GetObjectMetadata({ fullPath: 'documents/report.pdf' }); * // Or equivalently: * const metadata2 = await azureStorage.GetObjectMetadata({ objectId: 'documents/report.pdf' }); * * console.log(`File: ${metadata.name}`); * console.log(`Size: ${metadata.size} bytes`); * console.log(`Last modified: ${metadata.lastModified}`); * } catch (error) { * console.error('File does not exist or cannot be accessed'); * } * ``` */ GetObjectMetadata(params: GetObjectMetadataParams): Promise; /** * Downloads a blob's content from Azure Blob Storage. * * This method retrieves the full content of a blob and returns it as a Buffer * for processing in memory. * * @param params - Object identifier (objectId and fullPath are equivalent for Azure Blob) * @returns A Promise resolving to a Buffer containing the blob's data * @throws Error if the blob doesn't exist or cannot be downloaded * * @example * ```typescript * try { * // For Azure Blob, objectId and fullPath are the same (both are the blob name) * const content = await azureStorage.GetObject({ fullPath: 'documents/config.json' }); * // Or equivalently: * const content2 = await azureStorage.GetObject({ objectId: 'documents/config.json' }); * * // Parse the JSON content * const config = JSON.parse(content.toString('utf8')); * console.log('Configuration loaded:', config); * } catch (error) { * console.error('Failed to download file:', error.message); * } * ``` */ GetObject(params: GetObjectParams): Promise; /** * Azure Blob Storage supports ranged streaming via `BlobClient.download(offset, count)`. */ get SupportsStreaming(): boolean; /** * Streams a blob's content from Azure Blob Storage, optionally honoring a byte range. * * Uses `BlobClient.download(offset, count)`, which returns a Node.js readable stream * (`readableStreamBody`) without buffering the blob in memory. The inclusive * `Range.Start`/`Range.End` are translated to the Azure `offset`/`count` model * (`count = End - Start + 1`). The download response carries `contentType`, * `contentLength`, and (for ranged reads) `contentRange`, which are mapped onto the * {@link ObjectStreamResult}. * * @param params - Object identifier (objectId and fullPath are equivalent for Azure Blob) plus optional Range. * @returns A Promise resolving to an {@link ObjectStreamResult}. * @throws Error if the blob doesn't exist or cannot be streamed. */ GetObjectStream(params: GetObjectStreamParams): Promise; /** * Parses an Azure `Content-Range` value (`bytes start-end/total`) into the structured * form used by {@link ObjectStreamResult.ContentRange}. * * @param contentRange - The raw `contentRange` value from the download response, if present. * @returns The parsed range, or undefined when no (valid) range header was returned. */ private _parseAzureContentRange; /** * Uploads data to a blob in Azure Blob Storage. * * This method directly uploads a Buffer of data to a blob with the specified name. * It's useful for server-side operations where you already have the data in memory. * * @param objectName - The name to assign to the uploaded blob * @param data - The Buffer containing the data to upload * @param contentType - Optional MIME type for the blob (inferred from name if not provided) * @param metadata - Optional key-value pairs of custom metadata to associate with the blob * @returns A Promise resolving to a boolean indicating success * * @example * ```typescript * // Upload a text file * const content = Buffer.from('Hello, World!', 'utf8'); * const uploaded = await azureStorage.PutObject( * 'documents/hello.txt', * content, * 'text/plain', * { author: 'John Doe', department: 'Engineering' } * ); * * if (uploaded) { * console.log('File uploaded successfully'); * } else { * console.log('Failed to upload file'); * } * ``` */ PutObject(objectName: string, data: Buffer, contentType?: string, metadata?: Record): Promise; /** * Copies a blob within Azure Blob Storage. * * This method creates a copy of a blob at a new location without removing the original. * It uses a SAS URL to provide the source blob access for the copy operation. * * @param sourceObjectName - The name of the blob to copy * @param destinationObjectName - The name to assign to the copied blob * @returns A Promise resolving to a boolean indicating success * * @example * ```typescript * // Create a backup copy of an important file * const copied = await azureStorage.CopyObject( * 'documents/contract.pdf', * 'backups/contract_2024-05-16.pdf' * ); * * if (copied) { * console.log('File copied successfully'); * } else { * console.log('Failed to copy file'); * } * ``` */ CopyObject(sourceObjectName: string, destinationObjectName: string): Promise; /** * Checks if a blob exists in Azure Blob Storage. * * This method verifies the existence of a blob without downloading its content, * which is efficient for validation purposes. * * @param objectName - The name of the blob to check * @returns A Promise resolving to a boolean indicating if the blob exists * * @example * ```typescript * // Check if a file exists before attempting to use it * const exists = await azureStorage.ObjectExists('documents/report.pdf'); * * if (exists) { * console.log('File exists, proceeding with download'); * const content = await azureStorage.GetObject('documents/report.pdf'); * // Process the content... * } else { * console.log('File does not exist'); * } * ``` */ ObjectExists(objectName: string): Promise; /** * Checks if a directory (virtual) exists in Azure Blob Storage. * * Since Azure Blob Storage doesn't have a native directory concept, * this method checks for either: * 1. The existence of a directory placeholder blob (zero-byte blob with trailing slash) * 2. The existence of any blobs with the directory path as a prefix * * @param directoryPath - The path of the directory to check * @returns A Promise resolving to a boolean indicating if the directory exists * * @example * ```typescript * // Check if a directory exists before trying to save files to it * const exists = await azureStorage.DirectoryExists('documents/reports/'); * * if (!exists) { * console.log('Directory does not exist, creating it first'); * await azureStorage.CreateDirectory('documents/reports/'); * } * * // Now safe to use the directory * await azureStorage.PutObject('documents/reports/new-report.pdf', fileData); * ``` */ DirectoryExists(directoryPath: string): Promise; /** * Search is not supported by Azure Blob Storage. * Blob Storage is an object storage service without built-in search capabilities. * * To search Azure Blob Storage objects, consider: * - Using Azure Cognitive Search to index blob content * - Maintaining a separate search index (Azure Search, Elasticsearch, etc.) * - Using blob metadata and tags for filtering with ListObjects * - Using Azure Data Lake Analytics for complex queries * * @param query - The search query (not used) * @param options - Search options (not used) * @throws UnsupportedOperationError always */ SearchFiles(query: string, options?: FileSearchOptions): Promise; } //# sourceMappingURL=AzureFileStorage.d.ts.map