@od-oneapp/storage 2026.1.1301
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/README.md +854 -0
- package/dist/client-next.d.mts +61 -0
- package/dist/client-next.d.mts.map +1 -0
- package/dist/client-next.mjs +111 -0
- package/dist/client-next.mjs.map +1 -0
- package/dist/client-utils-Dx6W25iz.d.mts +43 -0
- package/dist/client-utils-Dx6W25iz.d.mts.map +1 -0
- package/dist/client.d.mts +28 -0
- package/dist/client.d.mts.map +1 -0
- package/dist/client.mjs +183 -0
- package/dist/client.mjs.map +1 -0
- package/dist/env-BVHLmQdh.mjs +128 -0
- package/dist/env-BVHLmQdh.mjs.map +1 -0
- package/dist/env.mjs +3 -0
- package/dist/health-check-D7LnnDec.mjs +746 -0
- package/dist/health-check-D7LnnDec.mjs.map +1 -0
- package/dist/health-check-im_huJ59.d.mts +116 -0
- package/dist/health-check-im_huJ59.d.mts.map +1 -0
- package/dist/index.d.mts +60 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +3 -0
- package/dist/keys.d.mts +37 -0
- package/dist/keys.d.mts.map +1 -0
- package/dist/keys.mjs +253 -0
- package/dist/keys.mjs.map +1 -0
- package/dist/server-edge.d.mts +28 -0
- package/dist/server-edge.d.mts.map +1 -0
- package/dist/server-edge.mjs +88 -0
- package/dist/server-edge.mjs.map +1 -0
- package/dist/server-next.d.mts +183 -0
- package/dist/server-next.d.mts.map +1 -0
- package/dist/server-next.mjs +1353 -0
- package/dist/server-next.mjs.map +1 -0
- package/dist/server.d.mts +70 -0
- package/dist/server.d.mts.map +1 -0
- package/dist/server.mjs +384 -0
- package/dist/server.mjs.map +1 -0
- package/dist/types.d.mts +321 -0
- package/dist/types.d.mts.map +1 -0
- package/dist/types.mjs +3 -0
- package/dist/validation.d.mts +101 -0
- package/dist/validation.d.mts.map +1 -0
- package/dist/validation.mjs +590 -0
- package/dist/validation.mjs.map +1 -0
- package/dist/vercel-blob-07Sx0Akn.d.mts +31 -0
- package/dist/vercel-blob-07Sx0Akn.d.mts.map +1 -0
- package/dist/vercel-blob-DA8HaYuw.mjs +158 -0
- package/dist/vercel-blob-DA8HaYuw.mjs.map +1 -0
- package/package.json +111 -0
- package/src/actions/blob-upload.ts +171 -0
- package/src/actions/index.ts +23 -0
- package/src/actions/mediaActions.ts +1071 -0
- package/src/actions/productMediaActions.ts +538 -0
- package/src/auth-helpers.ts +386 -0
- package/src/capabilities.ts +225 -0
- package/src/client-next.ts +184 -0
- package/src/client-utils.ts +292 -0
- package/src/client.ts +102 -0
- package/src/constants.ts +88 -0
- package/src/health-check.ts +81 -0
- package/src/multi-storage.ts +230 -0
- package/src/multipart.ts +497 -0
- package/src/retry-utils.test.ts +118 -0
- package/src/retry-utils.ts +59 -0
- package/src/server-edge.ts +129 -0
- package/src/server-next.ts +14 -0
- package/src/server.ts +666 -0
- package/src/validation.test.ts +312 -0
- package/src/validation.ts +827 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"health-check-D7LnnDec.mjs","names":["require","loadProvider"],"sources":["../providers/cloudflare-images.ts","../providers/cloudflare-r2.ts","../src/constants.ts","../src/multi-storage.ts","../src/multipart.ts","../src/capabilities.ts","../src/health-check.ts"],"sourcesContent":["/**\n * @fileoverview Cloudflare Images storage provider\n *\n * Lazy shim around the monorepo integration package.\n *\n * Why:\n * - `@integrations/*` packages are monorepo-private and may not be installed in extracted apps.\n * - This avoids hard module resolution failures during bundling/build; the integration is only\n * required if the provider is instantiated.\n */\n\nimport { createRequire } from 'node:module';\n\nimport type { StorageProvider } from '../types';\n\nconst require = createRequire(import.meta.url);\n\nfunction loadProvider(): new (...args: unknown[]) => StorageProvider {\n const mod = require('@integrations/cloudflare/storage-provider/images') as {\n CloudflareImagesProvider: new (...args: unknown[]) => StorageProvider;\n };\n return mod.CloudflareImagesProvider;\n}\n\nexport const CloudflareImagesProvider: new (...args: unknown[]) => StorageProvider =\n class CloudflareImagesProviderShim {\n constructor(...args: unknown[]) {\n const Provider = loadProvider();\n // eslint-disable-next-line no-constructor-return\n return new Provider(...args) as unknown as StorageProvider;\n }\n } as unknown as new (...args: unknown[]) => StorageProvider;\n","/**\n * @fileoverview Cloudflare R2 storage provider\n *\n * Lazy shim around the monorepo integration package.\n *\n * Why:\n * - `@integrations/*` packages are monorepo-private and may not be installed in extracted apps.\n * - This avoids hard module resolution failures during bundling/build; the integration is only\n * required if the provider is instantiated.\n */\n\nimport { createRequire } from 'node:module';\n\nimport type { StorageProvider } from '../types';\n\nconst require = createRequire(import.meta.url);\n\nfunction loadProvider(): new (...args: unknown[]) => StorageProvider {\n const mod = require('@integrations/cloudflare/storage-provider/r2') as {\n CloudflareR2Provider: new (...args: unknown[]) => StorageProvider;\n };\n return mod.CloudflareR2Provider;\n}\n\nexport const CloudflareR2Provider: new (...args: unknown[]) => StorageProvider = class CloudflareR2ProviderShim {\n constructor(...args: unknown[]) {\n const Provider = loadProvider();\n // eslint-disable-next-line no-constructor-return\n return new Provider(...args) as unknown as StorageProvider;\n }\n} as unknown as new (...args: unknown[]) => StorageProvider;\n","/**\n * @fileoverview Storage Package Constants\n *\n * Centralized constants for storage operations to avoid magic numbers\n * and improve maintainability.\n *\n * Includes:\n * - URL expiration times\n * - File size limits\n * - Multipart upload thresholds\n * - Retry configuration\n * - Rate limiting settings\n *\n * @module @repo/storage/constants\n */\n\nexport const STORAGE_CONSTANTS = {\n // URL Expiration Times (seconds)\n DEFAULT_URL_EXPIRY_SECONDS: 3600, // 1 hour\n PRODUCT_URL_EXPIRY_SECONDS: 3600, // 1 hour for product photos\n UPLOAD_URL_EXPIRY_SECONDS: 1800, // 30 minutes for uploads\n ADMIN_URL_EXPIRY_SECONDS: 7200, // 2 hours for admin operations\n\n // File Size Limits (bytes)\n MULTIPART_THRESHOLD_BYTES: 100 * 1024 * 1024, // 100MB - use multipart above this\n DEFAULT_PART_SIZE_BYTES: 5 * 1024 * 1024, // 5MB default part size\n DEFAULT_MAX_PART_SIZE_BYTES: 25 * 1024 * 1024, // 25MB max part size\n DEFAULT_QUEUE_SIZE: 4, // Concurrent upload parts\n\n // Batch Operations\n DEFAULT_BATCH_SIZE: 5, // Process 5 items concurrently\n MAX_BATCH_SIZE: 50, // Maximum batch size\n\n // Timeouts (milliseconds)\n DEFAULT_REQUEST_TIMEOUT_MS: 30000, // 30 seconds\n DEFAULT_UPLOAD_TIMEOUT_MS: 300000, // 5 minutes for uploads\n DEFAULT_DOWNLOAD_TIMEOUT_MS: 60000, // 1 minute for downloads\n\n // Retry Configuration\n DEFAULT_MAX_RETRIES: 3,\n RETRY_BASE_DELAY_MS: 1000, // 1 second base delay\n\n // Key Validation\n MAX_KEY_LENGTH: 1024,\n MAX_FILENAME_LENGTH: 255,\n\n // Rate Limiting (requests per window)\n DEFAULT_RATE_LIMIT_REQUESTS: 100,\n DEFAULT_RATE_LIMIT_WINDOW_MS: 60 * 1000, // 1 minute\n\n // Health Check\n HEALTH_CHECK_KEY: '__health_check__',\n} as const;\n\n/**\n * File size thresholds for multipart upload decisions\n */\nexport const MULTIPART_THRESHOLDS = {\n SMALL_FILE: 100 * 1024 * 1024, // < 100MB - use simple upload\n MEDIUM_FILE: 1024 * 1024 * 1024, // < 1GB - use 10MB parts\n LARGE_FILE: Infinity, // >= 1GB - use 25MB parts\n} as const;\n\n/**\n * Part sizes based on file size\n */\nexport const PART_SIZES = {\n SMALL: 5 * 1024 * 1024, // 5MB for files < 100MB\n MEDIUM: 10 * 1024 * 1024, // 10MB for files < 1GB\n LARGE: 25 * 1024 * 1024, // 25MB for files >= 1GB\n} as const;\n\n/**\n * Default storage capabilities for providers that don't implement getCapabilities()\n * Single source of truth for capability defaults\n */\nexport const DEFAULT_STORAGE_CAPABILITIES = {\n multipart: false,\n presignedUrls: false,\n progressTracking: false,\n abortSignal: false,\n metadata: false,\n customDomains: false,\n edgeCompatible: false,\n versioning: false,\n encryption: false,\n directoryListing: false,\n} as const;\n","/**\n * @fileoverview Multi-storage provider manager\n *\n * Manages multiple storage providers with routing and fallback capabilities.\n * Allows using different providers for different use cases or as backups.\n *\n * Features:\n * - Provider routing based on key patterns\n * - Fallback to default provider\n * - Unified API across multiple providers\n *\n * @module @repo/storage/multi-storage\n */\n\nimport { CloudflareImagesProvider } from '../providers/cloudflare-images';\nimport { CloudflareR2Provider } from '../providers/cloudflare-r2';\nimport { VercelBlobProvider } from '../providers/vercel-blob';\nimport {\n type ListOptions,\n type MultiStorageConfig,\n type StorageConfig,\n type StorageObject,\n type StorageProvider,\n type UploadOptions,\n} from '../types';\n\nexport class MultiStorageManager {\n private providers: Map<string, StorageProvider> = new Map();\n private defaultProvider: string;\n private routing: MultiStorageConfig['routing'];\n\n constructor(config: MultiStorageConfig) {\n // Initialize all providers\n for (const [name, providerConfig] of Object.entries(config.providers)) {\n this.providers.set(name, this.createProvider(providerConfig));\n }\n\n // Set default provider\n const firstProvider = Object.keys(config.providers)[0];\n this.defaultProvider = config.defaultProvider ?? firstProvider ?? '';\n if (!this.defaultProvider) {\n throw new Error('No storage providers configured');\n }\n\n this.routing = config.routing;\n }\n\n private createProvider(config: StorageConfig): StorageProvider {\n switch (config.provider) {\n case 'multi':\n throw new Error('Multi provider cannot be nested');\n\n case 'cloudflare-r2':\n if (!config.cloudflareR2) {\n throw new Error('Cloudflare R2 configuration is required');\n }\n // Handle array of R2 configs\n if (Array.isArray(config.cloudflareR2)) {\n if (config.cloudflareR2.length === 0) {\n throw new Error('No R2 configurations provided');\n }\n const firstR2Config = config.cloudflareR2[0];\n if (!firstR2Config) {\n throw new Error('First R2 configuration is undefined');\n }\n // Use first one for single provider (backward compatibility)\n return new CloudflareR2Provider(firstR2Config);\n }\n return new CloudflareR2Provider(config.cloudflareR2);\n\n case 'cloudflare-images':\n if (!config.cloudflareImages) {\n throw new Error('Cloudflare Images configuration is required');\n }\n return new CloudflareImagesProvider(config.cloudflareImages);\n\n case 'vercel-blob':\n if (!config.vercelBlob?.token) {\n throw new Error('Vercel Blob token is required');\n }\n return new VercelBlobProvider(config.vercelBlob.token);\n\n default:\n throw new Error(`Unknown storage provider: ${config.provider}`);\n }\n }\n\n private getProviderForKey(key: string): { provider: StorageProvider; providerName: string } {\n // Check routing rules\n if (this.routing) {\n // Check file type routing\n const extension = key.split('.').pop()?.toLowerCase();\n\n // Image routing\n if (this.routing.images && this.isImageFile(extension)) {\n const provider = this.providers.get(this.routing.images);\n if (provider) {\n return { provider, providerName: this.routing.images };\n }\n }\n\n // Document routing\n if (this.routing.documents && this.isDocumentFile(extension)) {\n const provider = this.providers.get(this.routing.documents);\n if (provider) {\n return { provider, providerName: this.routing.documents };\n }\n }\n\n // Custom routing rules\n for (const [pattern, providerName] of Object.entries(this.routing)) {\n if (pattern !== 'images' && pattern !== 'documents' && providerName) {\n // Simple pattern matching (could be enhanced with regex)\n if (key.includes(pattern)) {\n const provider = this.providers.get(providerName);\n if (provider) {\n return { provider, providerName };\n }\n }\n }\n }\n }\n\n // Fall back to default provider\n const provider = this.providers.get(this.defaultProvider);\n if (!provider) {\n throw new Error(`Default provider '${this.defaultProvider}' not found`);\n }\n\n return { provider, providerName: this.defaultProvider };\n }\n\n private isImageFile(extension?: string): boolean {\n const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'svg', 'ico'];\n return extension ? imageExtensions.includes(extension) : false;\n }\n\n private isDocumentFile(extension?: string): boolean {\n const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv'];\n return extension ? documentExtensions.includes(extension) : false;\n }\n\n // Get a specific provider by name\n getProvider(name: string): StorageProvider | undefined {\n return this.providers.get(name);\n }\n\n // Storage operations that route to appropriate provider\n async delete(key: string): Promise<void> {\n const { provider } = this.getProviderForKey(key);\n return provider.delete(key);\n }\n\n async download(key: string): Promise<Blob> {\n const { provider } = this.getProviderForKey(key);\n return provider.download(key);\n }\n\n async exists(key: string): Promise<boolean> {\n const { provider } = this.getProviderForKey(key);\n return provider.exists(key);\n }\n\n async getMetadata(key: string): Promise<StorageObject> {\n const { provider } = this.getProviderForKey(key);\n return provider.getMetadata(key);\n }\n\n async getUrl(key: string, options?: { expiresIn?: number }): Promise<string> {\n const { provider } = this.getProviderForKey(key);\n return provider.getUrl(key, options);\n }\n\n async list(options?: ListOptions & { provider?: string }): Promise<StorageObject[]> {\n // If specific provider requested, use it\n if (options?.provider) {\n const provider = this.providers.get(options.provider);\n if (!provider) {\n throw new Error(`Provider '${options.provider}' not found`);\n }\n return provider.list(options);\n }\n\n // Otherwise, list from all providers\n const allResults: StorageObject[] = [];\n for (const provider of this.providers.values()) {\n const results = await provider.list(options);\n allResults.push(...results);\n }\n return allResults;\n }\n\n async upload(\n key: string,\n data: ArrayBuffer | Blob | Buffer | File | ReadableStream,\n options?: UploadOptions & { provider?: string },\n ): Promise<StorageObject> {\n let provider: StorageProvider;\n\n // If specific provider requested, use it\n if (options?.provider) {\n const requestedProvider = this.providers.get(options.provider);\n if (!requestedProvider) {\n throw new Error(`Provider '${options.provider}' not found`);\n }\n provider = requestedProvider;\n } else {\n // Otherwise, use routing logic\n const { provider: routedProvider } = this.getProviderForKey(key);\n provider = routedProvider;\n }\n\n return provider.upload(key, data, options);\n }\n\n // Extended methods for Cloudflare Images\n async getCloudflareImagesProvider(): Promise<InstanceType<typeof CloudflareImagesProvider> | undefined> {\n for (const provider of this.providers.values()) {\n if (provider instanceof CloudflareImagesProvider) {\n return provider;\n }\n }\n return undefined;\n }\n\n // Get all provider names\n getProviderNames(): string[] {\n return Array.from(this.providers.keys());\n }\n}\n","/**\n * @fileoverview Unified Multipart Upload Manager\n *\n * Provides a consistent interface for multipart uploads across all storage providers.\n * Handles provider-specific differences and provides retry logic, progress tracking,\n * and error recovery.\n *\n * Features:\n * - Automatic part size calculation\n * - Concurrent part uploads\n * - Progress tracking\n * - Resume support\n * - Error recovery\n *\n * @module @repo/storage/multipart\n */\n\nimport { logWarn } from '@repo/shared/logs';\n\nimport {\n type MultipartUploadResult as BaseMultipartUploadResult,\n type MultipartUploadOptions,\n type StorageProvider,\n type UploadOptions,\n type UploadProgress,\n} from '../types';\n\nimport { MULTIPART_THRESHOLDS, PART_SIZES, STORAGE_CONSTANTS } from './constants';\n\nexport interface MultipartUploadState {\n uploadId: string;\n key: string;\n provider: string;\n parts: Array<{\n partNumber: number;\n etag?: string;\n size: number;\n uploaded: boolean;\n }>;\n totalSize: number;\n uploadedSize: number;\n completed: boolean;\n aborted: boolean;\n error?: string;\n}\n\n/**\n * Extended multipart upload result with detailed part information\n * Extends the base MultipartUploadResult from types.ts\n */\nexport interface MultipartUploadResult extends BaseMultipartUploadResult {\n parts: Array<{ partNumber: number; etag: string; size: number }>;\n totalParts: number;\n}\n\nexport class MultipartUploadManager {\n private provider: StorageProvider;\n private state: MultipartUploadState | null = null;\n private abortController: AbortController | null = null;\n\n constructor(provider: StorageProvider) {\n this.provider = provider;\n }\n\n /**\n * Check if provider supports multipart uploads\n */\n supportsMultipart(): boolean {\n const capabilities = this.provider.getCapabilities?.();\n return capabilities?.multipart ?? false;\n }\n\n /**\n * Create a new multipart upload\n *\n * @param key - Storage key\n * @param totalSize - Total file size in bytes\n * @param options - Upload options\n * @returns Upload state\n */\n async createUpload(\n key: string,\n totalSize: number,\n options: MultipartUploadOptions = {},\n ): Promise<MultipartUploadState> {\n if (!this.supportsMultipart()) {\n throw new Error('Provider does not support multipart uploads');\n }\n\n if (this.state && !this.state.completed && !this.state.aborted) {\n throw new Error('Upload already in progress. Abort current upload first.');\n }\n\n // Calculate optimal part size\n const partSize = this.calculatePartSize(totalSize, options.partSize);\n const totalParts = Math.ceil(totalSize / partSize);\n\n // Create multipart upload\n const uploadOptions: UploadOptions = {\n onProgress: options.onProgress\n ? (progress: UploadProgress) => {\n options.onProgress?.({\n key: progress.key,\n loaded: progress.loaded,\n total: progress.total,\n part: progress.part ?? 0,\n percentage: progress.percentage ?? 0,\n });\n }\n : undefined,\n };\n const result = await this.provider.createMultipartUpload?.(key, uploadOptions);\n\n if (!result) {\n throw new Error('Failed to create multipart upload');\n }\n\n // Initialize state\n this.state = {\n uploadId: result.uploadId,\n key: result.key,\n provider: this.getProviderName(),\n parts: Array.from({ length: totalParts }, (_, i) => ({\n partNumber: i + 1,\n size: i === totalParts - 1 ? totalSize - i * partSize : partSize,\n uploaded: false,\n })),\n totalSize,\n uploadedSize: 0,\n completed: false,\n aborted: false,\n };\n\n this.abortController = new AbortController();\n\n return this.state;\n }\n\n /**\n * Upload a part\n *\n * @param partNumber - Part number (1-based)\n * @param data - Part data\n * @param options - Upload options\n * @returns Upload result\n */\n async uploadPart(\n partNumber: number,\n data: ArrayBuffer | Blob | Buffer,\n options: UploadOptions = {},\n ): Promise<{ etag: string; partNumber: number; size: number }> {\n if (!this.state) {\n throw new Error('No active upload. Call createUpload first.');\n }\n\n if (this.state.completed || this.state.aborted) {\n throw new Error('Upload is completed or aborted');\n }\n\n const part = this.state.parts.find(p => p.partNumber === partNumber);\n if (!part) {\n throw new Error(`Part ${partNumber} not found`);\n }\n\n if (part.uploaded) {\n throw new Error(`Part ${partNumber} already uploaded`);\n }\n\n // Check abort signal\n if (this.abortController?.signal.aborted) {\n throw new Error('Upload aborted');\n }\n\n try {\n // Upload part with retry logic\n const result = await this.uploadPartWithRetry(partNumber, data, options);\n\n // Update state\n part.etag = result.etag;\n part.uploaded = true;\n this.state.uploadedSize += part.size;\n\n // Report progress\n if (options.onProgress) {\n options.onProgress({\n key: this.state.key,\n loaded: this.state.uploadedSize,\n total: this.state.totalSize,\n part: partNumber,\n percentage: (this.state.uploadedSize / this.state.totalSize) * 100,\n });\n }\n\n return result;\n } catch (error) {\n this.state.error = error instanceof Error ? error.message : String(error);\n throw error;\n }\n }\n\n /**\n * Complete the multipart upload\n *\n * @returns Final upload result\n */\n async completeUpload(): Promise<MultipartUploadResult> {\n if (!this.state) {\n throw new Error('No active upload. Call createUpload first.');\n }\n\n if (this.state.completed) {\n throw new Error('Upload already completed');\n }\n\n if (this.state.aborted) {\n throw new Error('Upload was aborted');\n }\n\n // Check if all parts are uploaded\n const unuploadedParts = this.state.parts.filter(p => !p.uploaded);\n if (unuploadedParts.length > 0) {\n throw new Error(`Upload incomplete: ${unuploadedParts.length} parts not uploaded`);\n }\n\n try {\n // Complete multipart upload\n const parts = this.state.parts\n .filter(p => p.etag)\n .map(p => ({ partNumber: p.partNumber, etag: p.etag ?? '' }))\n .filter(p => p.etag !== '');\n\n const result = await this.provider.completeMultipartUpload?.(this.state.uploadId, parts);\n\n if (!result) {\n throw new Error('Failed to complete multipart upload');\n }\n\n // Update state\n this.state.completed = true;\n\n return {\n ...result,\n key: result.key ?? this.state.key,\n uploadId: this.state.uploadId,\n parts: this.state.parts\n .filter(p => p.etag)\n .map(p => ({\n partNumber: p.partNumber,\n etag: p.etag ?? '',\n size: p.size,\n })),\n totalParts: this.state.parts.length,\n };\n } catch (error) {\n this.state.error = error instanceof Error ? error.message : String(error);\n throw error;\n }\n }\n\n /**\n * Abort the multipart upload\n */\n async abortUpload(): Promise<void> {\n if (!this.state) {\n return;\n }\n\n if (this.state.completed) {\n return;\n }\n\n // Signal abort\n this.abortController?.abort();\n this.state.aborted = true;\n\n try {\n // Abort on provider\n await this.provider.abortMultipartUpload?.(this.state.uploadId);\n } catch (error) {\n // Log error but don't throw - we want to clean up state\n\n // Use structured logging instead of console.warn\n logWarn('Failed to abort upload on provider', {\n error: error instanceof Error ? error.message : String(error),\n uploadId: this.state.uploadId,\n key: this.state.key,\n });\n }\n\n // Reset state\n this.state = null;\n this.abortController = null;\n }\n\n /**\n * Get current upload state\n */\n getState(): MultipartUploadState | null {\n return this.state;\n }\n\n /**\n * Resume upload from state (for recovery)\n *\n * @param state - Previous upload state\n */\n async resumeUpload(state: MultipartUploadState): Promise<void> {\n if (this.state && !this.state.completed && !this.state.aborted) {\n throw new Error('Upload already in progress');\n }\n\n this.state = { ...state };\n this.abortController = new AbortController();\n }\n\n /**\n * Upload file in chunks automatically\n *\n * @param key - Storage key\n * @param data - File data\n * @param options - Upload options\n * @returns Upload result\n */\n async uploadFile(\n key: string,\n data: ArrayBuffer | Blob | Buffer,\n options: MultipartUploadOptions = {},\n ): Promise<MultipartUploadResult> {\n const totalSize =\n data instanceof ArrayBuffer\n ? data.byteLength\n : data instanceof Buffer\n ? data.length\n : (data as Blob).size;\n\n // Create upload\n await this.createUpload(key, totalSize, options);\n\n const partSize = this.calculatePartSize(totalSize, options.partSize);\n const totalParts = Math.ceil(totalSize / partSize);\n\n // Upload parts\n for (let i = 0; i < totalParts; i++) {\n const start = i * partSize;\n const end = Math.min(start + partSize, totalSize);\n const partData = data.slice(start, end);\n\n await this.uploadPart(i + 1, partData, {\n onProgress: options.onProgress\n ? (progress: UploadProgress) => {\n options.onProgress?.({\n key: progress.key,\n loaded: progress.loaded,\n total: progress.total,\n part: progress.part ?? 0,\n percentage: progress.percentage ?? 0,\n });\n }\n : undefined,\n });\n }\n\n // Complete upload\n return await this.completeUpload();\n }\n\n private async uploadPartWithRetry(\n partNumber: number,\n data: ArrayBuffer | Blob | Buffer,\n options: UploadOptions,\n maxRetries: number = 3,\n ): Promise<{ etag: string; partNumber: number; size: number }> {\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n if (!this.state?.uploadId) {\n throw new Error('Upload ID not initialized');\n }\n\n const result = await this.provider.uploadPart?.(this.state.uploadId, partNumber, data, {\n ...options,\n abortSignal: this.abortController?.signal,\n });\n\n if (!result) {\n throw new Error('Failed to upload part');\n }\n\n return {\n etag: result.etag ?? '',\n partNumber: result.partNumber ?? partNumber,\n size:\n data instanceof ArrayBuffer\n ? data.byteLength\n : data instanceof Buffer\n ? data.length\n : (data as Blob).size,\n };\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Don't retry on abort\n if (this.abortController?.signal.aborted) {\n throw lastError;\n }\n\n // Don't retry on validation errors\n if (lastError.message.includes('validation') || lastError.message.includes('invalid')) {\n throw lastError;\n }\n\n // Wait before retry (exponential backoff)\n if (attempt < maxRetries) {\n await new Promise(resolve =>\n setTimeout(resolve, Math.pow(2, attempt) * STORAGE_CONSTANTS.RETRY_BASE_DELAY_MS),\n );\n }\n }\n }\n\n throw lastError ?? new Error('Upload failed after retries');\n }\n\n private calculatePartSize(totalSize: number, userPartSize?: number): number {\n if (userPartSize) {\n return Math.min(userPartSize, totalSize);\n }\n\n // Use constants for part size thresholds\n if (totalSize < MULTIPART_THRESHOLDS.SMALL_FILE) {\n return PART_SIZES.SMALL;\n } else if (totalSize < MULTIPART_THRESHOLDS.MEDIUM_FILE) {\n return PART_SIZES.MEDIUM;\n } else {\n // Scale part size to ensure we never exceed 10,000 parts (S3/R2 limit)\n const maxParts = 9999; // Stay safely under 10,000 limit\n const minPartSize = Math.ceil(totalSize / maxParts);\n return Math.max(PART_SIZES.LARGE, minPartSize);\n }\n }\n\n private getProviderName(): string {\n return this.provider.constructor.name;\n }\n}\n\n/**\n * Create a multipart upload manager for a provider\n *\n * @param provider - Storage provider\n * @returns Multipart upload manager\n */\nexport function createMultipartUploadManager(provider: StorageProvider): MultipartUploadManager {\n if (!hasMultipartSupport(provider)) {\n throw new Error('The provided storage provider does not support multipart uploads');\n }\n return new MultipartUploadManager(provider);\n}\n\n/**\n * Determines whether the given storage provider supports multipart uploads.\n *\n * @param provider - The storage provider to check\n * @returns `true` if the provider supports multipart uploads, `false` otherwise.\n */\nexport function hasMultipartSupport(provider: StorageProvider): boolean {\n const capabilities = provider.getCapabilities?.();\n return capabilities?.multipart ?? false;\n}\n\n/**\n * Selects an appropriate multipart upload part size for a file.\n *\n * If `userPartSize` is provided, it will be capped at the file size; otherwise the part size\n * is chosen from configured thresholds for small, medium, or large files.\n *\n * @param fileSize - File size in bytes\n * @param userPartSize - Optional user-specified part size in bytes; capped to `fileSize` when provided\n * @returns The selected part size in bytes\n */\nexport function getOptimalPartSize(fileSize: number, userPartSize?: number): number {\n if (userPartSize) {\n return Math.min(userPartSize, fileSize);\n }\n\n if (fileSize < MULTIPART_THRESHOLDS.SMALL_FILE) {\n return PART_SIZES.SMALL;\n } else if (fileSize < MULTIPART_THRESHOLDS.MEDIUM_FILE) {\n return PART_SIZES.MEDIUM;\n } else {\n // Scale part size to ensure we never exceed 10,000 parts (S3/R2 limit)\n const maxParts = 9999; // Stay safely under 10,000 limit\n const minPartSize = Math.ceil(fileSize / maxParts);\n return Math.max(PART_SIZES.LARGE, minPartSize);\n }\n}\n","/**\n * @fileoverview Storage Provider Capabilities Utilities\n *\n * Provides utilities for checking storage provider capabilities and feature support.\n * Helps determine which features are available for each provider.\n *\n * @module @repo/storage/capabilities\n */\n\nimport { DEFAULT_STORAGE_CAPABILITIES, MULTIPART_THRESHOLDS } from './constants';\n\nimport type { StorageCapabilities, StorageProvider } from '../types';\n\n/**\n * Check if a storage provider has a specific capability\n * @param provider - The storage provider to check\n * @param capability - The capability to check for\n * @returns True if the provider supports the capability\n */\nexport function hasCapability(\n provider: StorageProvider,\n capability: keyof StorageCapabilities,\n): boolean {\n const capabilities = provider.getCapabilities?.();\n return capabilities?.[capability] ?? false;\n}\n\n/**\n * Check if a storage provider supports multiple capabilities\n * @param provider - The storage provider to check\n * @param capabilities - Array of capabilities to check for\n * @returns True if the provider supports all capabilities\n */\nexport function hasAllCapabilities(\n provider: StorageProvider,\n capabilities: Array<keyof StorageCapabilities>,\n): boolean {\n return capabilities.every(capability => hasCapability(provider, capability));\n}\n\n/**\n * Check if a storage provider supports any of the specified capabilities\n * @param provider - The storage provider to check\n * @param capabilities - Array of capabilities to check for\n * @returns True if the provider supports at least one capability\n */\nexport function hasAnyCapability(\n provider: StorageProvider,\n capabilities: Array<keyof StorageCapabilities>,\n): boolean {\n return capabilities.some(capability => hasCapability(provider, capability));\n}\n\n/**\n * Get all capabilities supported by a storage provider\n * @param provider - The storage provider to check\n * @returns Object with all capabilities and their support status\n */\nexport function getProviderCapabilities(provider: StorageProvider): StorageCapabilities {\n return provider.getCapabilities?.() ?? { ...DEFAULT_STORAGE_CAPABILITIES };\n}\n\n/**\n * Get a human-readable description of provider capabilities\n * @param provider - The storage provider to describe\n * @returns String describing the provider's capabilities\n */\nexport function describeProviderCapabilities(provider: StorageProvider): string {\n const capabilities = getProviderCapabilities(provider);\n const supportedFeatures: string[] = [];\n const unsupportedFeatures: string[] = [];\n\n if (capabilities.multipart) supportedFeatures.push('multipart uploads');\n else unsupportedFeatures.push('multipart uploads');\n\n if (capabilities.presignedUrls) supportedFeatures.push('presigned URLs');\n else unsupportedFeatures.push('presigned URLs');\n\n if (capabilities.progressTracking) supportedFeatures.push('progress tracking');\n else unsupportedFeatures.push('progress tracking');\n\n if (capabilities.abortSignal) supportedFeatures.push('abort signals');\n else unsupportedFeatures.push('abort signals');\n\n if (capabilities.metadata) supportedFeatures.push('metadata');\n else unsupportedFeatures.push('metadata');\n\n if (capabilities.customDomains) supportedFeatures.push('custom domains');\n else unsupportedFeatures.push('custom domains');\n\n if (capabilities.edgeCompatible) supportedFeatures.push('edge runtime');\n else unsupportedFeatures.push('edge runtime');\n\n let description = `Provider supports: ${supportedFeatures.join(', ')}`;\n\n if (unsupportedFeatures.length > 0) {\n description += `\\nProvider does not support: ${unsupportedFeatures.join(', ')}`;\n }\n\n return description;\n}\n\n/**\n * Validate that a provider supports the required capabilities for an operation\n * @param provider - The storage provider to validate\n * @param requiredCapabilities - Capabilities required for the operation\n * @throws Error if provider doesn't support required capabilities\n */\nexport function validateProviderCapabilities(\n provider: StorageProvider,\n requiredCapabilities: Array<keyof StorageCapabilities>,\n): void {\n const missingCapabilities = requiredCapabilities.filter(\n capability => !hasCapability(provider, capability),\n );\n\n if (missingCapabilities.length > 0) {\n const providerName = provider.constructor.name;\n throw new Error(\n `Provider ${providerName} does not support required capabilities: ${missingCapabilities.join(', ')}`,\n );\n }\n}\n\n/**\n * Get the best provider for a specific use case based on capabilities\n * @param providers - Array of storage providers to choose from\n * @param requiredCapabilities - Capabilities required for the use case\n * @returns The best provider or null if none meet the requirements\n */\nexport function getBestProvider(\n providers: StorageProvider[],\n requiredCapabilities: Array<keyof StorageCapabilities>,\n): StorageProvider | null {\n const suitableProviders = providers.filter(provider =>\n hasAllCapabilities(provider, requiredCapabilities),\n );\n\n if (suitableProviders.length === 0) {\n return null;\n }\n\n // If multiple providers are suitable, prefer edge-compatible ones\n const edgeCompatible = suitableProviders.filter(provider =>\n hasCapability(provider, 'edgeCompatible'),\n );\n\n return edgeCompatible.length > 0 ? (edgeCompatible[0] ?? null) : (suitableProviders[0] ?? null);\n}\n\n/**\n * Builds a map from provider names to their reported storage capabilities.\n *\n * @param providers - Array of entries each containing a `name` (used as the map key) and a `provider` instance\n * @returns A mapping from each provider name to its `StorageCapabilities`\n */\nexport function getCapabilityMatrix(\n providers: Array<{ name: string; provider: StorageProvider }>,\n): Record<string, StorageCapabilities> {\n const matrix: Record<string, StorageCapabilities> = {};\n\n for (const { name, provider } of providers) {\n matrix[name] = getProviderCapabilities(provider);\n }\n\n return matrix;\n}\n\n/**\n * Evaluate a storage provider's suitability for a specific file and produce actionable recommendations and warnings.\n *\n * @param provider - The storage provider to evaluate\n * @param fileSize - File size in bytes\n * @param fileType - MIME type of the file\n * @returns An object with `suitable` (`true` if there are no warnings, `false` otherwise), `recommendations` (suggested actions to improve handling), and `warnings` (issues that reduce suitability)\n */\nexport function checkProviderSuitability(\n provider: StorageProvider,\n fileSize: number,\n fileType: string,\n): {\n suitable: boolean;\n recommendations: string[];\n warnings: string[];\n} {\n const capabilities = getProviderCapabilities(provider);\n const recommendations: string[] = [];\n const warnings: string[] = [];\n\n // Check file size suitability\n if (fileSize > MULTIPART_THRESHOLDS.SMALL_FILE) {\n // > 100MB\n if (!capabilities.multipart) {\n warnings.push('Large file detected but provider does not support multipart uploads');\n } else {\n recommendations.push('Use multipart upload for this large file');\n }\n }\n\n // Check file type suitability\n if (fileType.startsWith('image/')) {\n if (capabilities.metadata) {\n recommendations.push('Consider storing image metadata for better organization');\n }\n }\n\n if (fileType.startsWith('video/')) {\n if (!capabilities.multipart) {\n warnings.push('Video files are typically large and benefit from multipart uploads');\n }\n }\n\n // Check edge compatibility\n if (fileType.startsWith('text/') && !capabilities.edgeCompatible) {\n recommendations.push('Text files could be processed in edge runtime for better performance');\n }\n\n const suitable = warnings.length === 0;\n\n return {\n suitable,\n recommendations,\n warnings,\n };\n}\n","/**\n * @fileoverview Health check utilities for storage providers\n *\n * Provides health check functionality to verify storage provider availability\n * and performance. Useful for monitoring and alerting.\n *\n * @module @repo/storage/health-check\n */\n\nimport type { StorageProvider } from '../types';\n\n/**\n * Health check result with status and metrics\n */\nexport interface HealthCheckResult {\n status: 'healthy' | 'degraded' | 'unhealthy';\n latencyMs: number;\n error?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Check the health of a storage provider\n *\n * @param provider - The storage provider to check\n * @returns Health check result with status and latency\n */\nexport async function checkProviderHealth(provider: StorageProvider): Promise<HealthCheckResult> {\n const startTime = Date.now();\n\n try {\n // Perform a lightweight operation to check provider health\n // Using list with limit 1 as a health check probe\n await provider.list({ limit: 1 });\n\n const latencyMs = Date.now() - startTime;\n\n // Define health thresholds\n const HEALTHY_THRESHOLD_MS = 1000; // < 1s is healthy\n const DEGRADED_THRESHOLD_MS = 3000; // 1-3s is degraded\n\n let status: 'healthy' | 'degraded' | 'unhealthy';\n if (latencyMs < HEALTHY_THRESHOLD_MS) {\n status = 'healthy';\n } else if (latencyMs < DEGRADED_THRESHOLD_MS) {\n status = 'degraded';\n } else {\n status = 'unhealthy';\n }\n\n return {\n status,\n latencyMs,\n details: {\n provider: provider.constructor.name,\n threshold_healthy_ms: HEALTHY_THRESHOLD_MS,\n threshold_degraded_ms: DEGRADED_THRESHOLD_MS,\n },\n };\n } catch (error) {\n const latencyMs = Date.now() - startTime;\n return {\n status: 'unhealthy',\n latencyMs,\n error: error instanceof Error ? error.message : String(error),\n details: {\n provider: provider.constructor.name,\n },\n };\n }\n}\n\n/**\n * Perform a comprehensive health check on storage system\n *\n * @param provider - The storage provider to check\n * @returns Detailed health check result\n */\nexport async function storageHeal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B,MAAM,wBAAwB;EAE9B,IAAI;AACJ,MAAI,YAAY,qBACd,UAAS;WACA,YAAY,sBACrB,UAAS;MAET,UAAS;AAGX,SAAO;GACL;GACA;GACA,SAAS;IACP,UAAU,SAAS,YAAY;IAC/B,sBAAsB;IACtB,uBAAuB;IACxB;GACF;UACM,OAAO;AAEd,SAAO;GACL,QAAQ;GACR,WAHgB,KAAK,KAAK,GAAG;GAI7B,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC7D,SAAS,EACP,UAAU,SAAS,YAAY,MAChC;GACF;;;;;;;;;AAUL,eAAsB,mBAAmB,UAAuD;AAC9F,QAAO,oBAAoB,SAAS"}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { ListOptions, MultiStorageConfig, MultipartUploadOptions, MultipartUploadResult as MultipartUploadResult$1, StorageCapabilities, StorageObject, StorageProvider, UploadOptions } from "./types.mjs";
|
|
2
|
+
|
|
3
|
+
//#region providers/cloudflare-images.d.ts
|
|
4
|
+
declare const CloudflareImagesProvider: new (...args: unknown[]) => StorageProvider;
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/multi-storage.d.ts
|
|
7
|
+
declare class MultiStorageManager {
|
|
8
|
+
private providers;
|
|
9
|
+
private defaultProvider;
|
|
10
|
+
private routing;
|
|
11
|
+
constructor(config: MultiStorageConfig);
|
|
12
|
+
private createProvider;
|
|
13
|
+
private getProviderForKey;
|
|
14
|
+
private isImageFile;
|
|
15
|
+
private isDocumentFile;
|
|
16
|
+
getProvider(name: string): StorageProvider | undefined;
|
|
17
|
+
delete(key: string): Promise<void>;
|
|
18
|
+
download(key: string): Promise<Blob>;
|
|
19
|
+
exists(key: string): Promise<boolean>;
|
|
20
|
+
getMetadata(key: string): Promise<StorageObject>;
|
|
21
|
+
getUrl(key: string, options?: {
|
|
22
|
+
expiresIn?: number;
|
|
23
|
+
}): Promise<string>;
|
|
24
|
+
list(options?: ListOptions & {
|
|
25
|
+
provider?: string;
|
|
26
|
+
}): Promise<StorageObject[]>;
|
|
27
|
+
upload(key: string, data: ArrayBuffer | Blob | Buffer | File | ReadableStream, options?: UploadOptions & {
|
|
28
|
+
provider?: string;
|
|
29
|
+
}): Promise<StorageObject>;
|
|
30
|
+
getCloudflareImagesProvider(): Promise<InstanceType<typeof CloudflareImagesProvider> | undefined>;
|
|
31
|
+
getProviderNames(): string[];
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region providers/cloudflare-r2.d.ts
|
|
35
|
+
declare const CloudflareR2Provider: new (...args: unknown[]) => StorageProvider;
|
|
36
|
+
//#endregion
|
|
37
|
+
//#region src/multipart.d.ts
|
|
38
|
+
interface MultipartUploadState {
|
|
39
|
+
uploadId: string;
|
|
40
|
+
key: string;
|
|
41
|
+
provider: string;
|
|
42
|
+
parts: Array<{
|
|
43
|
+
partNumber: number;
|
|
44
|
+
etag?: string;
|
|
45
|
+
size: number;
|
|
46
|
+
uploaded: boolean;
|
|
47
|
+
}>;
|
|
48
|
+
totalSize: number;
|
|
49
|
+
uploadedSize: number;
|
|
50
|
+
completed: boolean;
|
|
51
|
+
aborted: boolean;
|
|
52
|
+
error?: string;
|
|
53
|
+
}
|
|
54
|
+
interface MultipartUploadResult extends MultipartUploadResult$1 {
|
|
55
|
+
parts: Array<{
|
|
56
|
+
partNumber: number;
|
|
57
|
+
etag: string;
|
|
58
|
+
size: number;
|
|
59
|
+
}>;
|
|
60
|
+
totalParts: number;
|
|
61
|
+
}
|
|
62
|
+
declare class MultipartUploadManager {
|
|
63
|
+
private provider;
|
|
64
|
+
private state;
|
|
65
|
+
private abortController;
|
|
66
|
+
constructor(provider: StorageProvider);
|
|
67
|
+
supportsMultipart(): boolean;
|
|
68
|
+
createUpload(key: string, totalSize: number, options?: MultipartUploadOptions): Promise<MultipartUploadState>;
|
|
69
|
+
uploadPart(partNumber: number, data: ArrayBuffer | Blob | Buffer, options?: UploadOptions): Promise<{
|
|
70
|
+
etag: string;
|
|
71
|
+
partNumber: number;
|
|
72
|
+
size: number;
|
|
73
|
+
}>;
|
|
74
|
+
completeUpload(): Promise<MultipartUploadResult>;
|
|
75
|
+
abortUpload(): Promise<void>;
|
|
76
|
+
getState(): MultipartUploadState | null;
|
|
77
|
+
resumeUpload(state: MultipartUploadState): Promise<void>;
|
|
78
|
+
uploadFile(key: string, data: ArrayBuffer | Blob | Buffer, options?: MultipartUploadOptions): Promise<MultipartUploadResult>;
|
|
79
|
+
private uploadPartWithRetry;
|
|
80
|
+
private calculatePartSize;
|
|
81
|
+
private getProviderName;
|
|
82
|
+
}
|
|
83
|
+
declare function createMultipartUploadManager(provider: StorageProvider): MultipartUploadManager;
|
|
84
|
+
declare function hasMultipartSupport(provider: StorageProvider): boolean;
|
|
85
|
+
declare function getOptimalPartSize(fileSize: number, userPartSize?: number): number;
|
|
86
|
+
//#endregion
|
|
87
|
+
//#region src/capabilities.d.ts
|
|
88
|
+
declare function hasCapability(provider: StorageProvider, capability: keyof StorageCapabilities): boolean;
|
|
89
|
+
declare function hasAllCapabilities(provider: StorageProvider, capabilities: Array<keyof StorageCapabilities>): boolean;
|
|
90
|
+
declare function hasAnyCapability(provider: StorageProvider, capabilities: Array<keyof StorageCapabilities>): boolean;
|
|
91
|
+
declare function getProviderCapabilities(provider: StorageProvider): StorageCapabilities;
|
|
92
|
+
declare function describeProviderCapabilities(provider: StorageProvider): string;
|
|
93
|
+
declare function validateProviderCapabilities(provider: StorageProvider, requiredCapabilities: Array<keyof StorageCapabilities>): void;
|
|
94
|
+
declare function getBestProvider(providers: StorageProvider[], requiredCapabilities: Array<keyof StorageCapabilities>): StorageProvider | null;
|
|
95
|
+
declare function getCapabilityMatrix(providers: Array<{
|
|
96
|
+
name: string;
|
|
97
|
+
provider: StorageProvider;
|
|
98
|
+
}>): Record<string, StorageCapabilities>;
|
|
99
|
+
declare function checkProviderSuitability(provider: StorageProvider, fileSize: number, fileType: string): {
|
|
100
|
+
suitable: boolean;
|
|
101
|
+
recommendations: string[];
|
|
102
|
+
warnings: string[];
|
|
103
|
+
};
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/health-check.d.ts
|
|
106
|
+
interface HealthCheckResult {
|
|
107
|
+
status: 'healthy' | 'degraded' | 'unhealthy';
|
|
108
|
+
latencyMs: number;
|
|
109
|
+
error?: string;
|
|
110
|
+
details?: Record<string, unknown>;
|
|
111
|
+
}
|
|
112
|
+
declare function checkProviderHealth(provider: StorageProvider): Promise<HealthCheckResult>;
|
|
113
|
+
declare function storageHealthCheck(provider: StorageProvider): Promise<HealthCheckResult>;
|
|
114
|
+
//#endregion
|
|
115
|
+
export { getOptimalPartSize as _, describeProviderCapabilities as a, MultiStorageManager as b, getProviderCapabilities as c, hasCapability as d, validateProviderCapabilities as f, createMultipartUploadManager as g, MultipartUploadState as h, checkProviderSuitability as i, hasAllCapabilities as l, MultipartUploadResult as m, checkProviderHealth as n, getBestProvider as o, MultipartUploadManager as p, storageHealthCheck as r, getCapabilityMatrix as s, HealthCheckResult as t, hasAnyCapability as u, hasMultipartSupport as v, CloudflareImagesProvider as x, CloudflareR2Provider as y };
|
|
116
|
+
//# sourceMappingURL=health-check-im_huJ59.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"health-check-im_huJ59.d.mts","names":[],"sources":["../providers/cloudflare-images.ts","../src/multi-storage.ts","../providers/cloudflare-r2.ts","../src/multipart.ts","../src/capabilities.ts","../src/health-check.ts"],"mappings":";;;cAwBa,wBAAA,UAAkC,IAAA,gBAAoB,eAAA;;;cCEtD,mBAAA;EAAA,QACH,SAAA;EAAA,QACA,eAAA;EAAA,QACA,OAAA;cAEI,MAAA,EAAQ,kBAAA;EAAA,QAgBZ,cAAA;EAAA,QAwCA,iBAAA;EAAA,QA6CA,WAAA;EAAA,QAKA,cAAA;EAMR,WAAA,CAAY,IAAA,WAAe,eAAA;EAKrB,MAAA,CAAO,GAAA,WAAc,OAAA;EAKrB,QAAA,CAAS,GAAA,WAAc,OAAA,CA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EACf,MAAA;EACA,SAAA;EACA,KAAA;EACA,OAAA,GAAU,MAAA;AAAA;AAAA,iBASU,mBAAA,CAAoB,QAAA,EAAU,eAAA,GAAkB,OAAA,CAAQ,iBAAA;AAAA,iBAmDxD,kBAAA,CAAmB,QAAA,EAAU,eAAA,GAAkB,OAAA,CAAQ,iBAAA"}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
//#region env.d.ts
|
|
2
|
+
declare const env: Readonly<{
|
|
3
|
+
VERCEL_BLOB_READ_WRITE_TOKEN?: string | undefined;
|
|
4
|
+
CLOUDFLARE_IMAGES_ACCOUNT_ID?: string | undefined;
|
|
5
|
+
CLOUDFLARE_IMAGES_API_TOKEN?: string | undefined;
|
|
6
|
+
CLOUDFLARE_IMAGES_DELIVERY_URL?: string | undefined;
|
|
7
|
+
CLOUDFLARE_IMAGES_SIGNING_KEY?: string | undefined;
|
|
8
|
+
R2_ACCESS_KEY_ID?: string | undefined;
|
|
9
|
+
R2_ACCOUNT_ID?: string | undefined;
|
|
10
|
+
R2_BUCKET?: string | undefined;
|
|
11
|
+
R2_SECRET_ACCESS_KEY?: string | undefined;
|
|
12
|
+
R2_CREDENTIALS?: {
|
|
13
|
+
bucket: string;
|
|
14
|
+
accountId: string;
|
|
15
|
+
accessKeyId: string;
|
|
16
|
+
secretAccessKey: string;
|
|
17
|
+
name?: string | undefined;
|
|
18
|
+
}[] | undefined;
|
|
19
|
+
STORAGE_CONFIG?: any;
|
|
20
|
+
STORAGE_PROVIDER?: "vercel-blob" | "cloudflare-r2" | "cloudflare-images" | "multi" | undefined;
|
|
21
|
+
STORAGE_LOG_LEVEL: "error" | "info" | "warn";
|
|
22
|
+
STORAGE_LOG_PERFORMANCE: boolean;
|
|
23
|
+
STORAGE_LOG_PROVIDER: "console" | "sentry" | "pino";
|
|
24
|
+
STORAGE_MAX_FILE_SIZE: number;
|
|
25
|
+
STORAGE_MAX_FILES_PER_UPLOAD: number;
|
|
26
|
+
STORAGE_RATE_LIMIT_REQUESTS: number;
|
|
27
|
+
STORAGE_RATE_LIMIT_WINDOW_MS: number;
|
|
28
|
+
STORAGE_ENFORCE_AUTH: boolean;
|
|
29
|
+
STORAGE_ENABLE_RATE_LIMIT: boolean;
|
|
30
|
+
STORAGE_ENFORCE_CSRF: boolean;
|
|
31
|
+
}>;
|
|
32
|
+
declare function safeEnv(): typeof env;
|
|
33
|
+
declare function getEnvWithDefaults(): {
|
|
34
|
+
VERCEL_BLOB_READ_WRITE_TOKEN: string;
|
|
35
|
+
CLOUDFLARE_IMAGES_ACCOUNT_ID: string;
|
|
36
|
+
CLOUDFLARE_IMAGES_API_TOKEN: string;
|
|
37
|
+
CLOUDFLARE_IMAGES_DELIVERY_URL: string;
|
|
38
|
+
CLOUDFLARE_IMAGES_SIGNING_KEY: string;
|
|
39
|
+
R2_ACCESS_KEY_ID: string;
|
|
40
|
+
R2_ACCOUNT_ID: string;
|
|
41
|
+
R2_BUCKET: string;
|
|
42
|
+
R2_SECRET_ACCESS_KEY: string;
|
|
43
|
+
R2_CREDENTIALS: string;
|
|
44
|
+
STORAGE_CONFIG: string;
|
|
45
|
+
STORAGE_LOG_LEVEL: string;
|
|
46
|
+
STORAGE_LOG_PERFORMANCE: boolean;
|
|
47
|
+
STORAGE_LOG_PROVIDER: string;
|
|
48
|
+
STORAGE_PROVIDER: string;
|
|
49
|
+
STORAGE_MAX_FILE_SIZE: number;
|
|
50
|
+
STORAGE_MAX_FILES_PER_UPLOAD: number;
|
|
51
|
+
STORAGE_RATE_LIMIT_REQUESTS: number;
|
|
52
|
+
STORAGE_RATE_LIMIT_WINDOW_MS: number;
|
|
53
|
+
STORAGE_ENFORCE_AUTH: boolean;
|
|
54
|
+
STORAGE_ENABLE_RATE_LIMIT: boolean;
|
|
55
|
+
STORAGE_ENFORCE_CSRF: boolean;
|
|
56
|
+
};
|
|
57
|
+
type Env = typeof env;
|
|
58
|
+
//#endregion
|
|
59
|
+
export { Env, env, getEnvWithDefaults, safeEnv };
|
|
60
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../env.ts"],"mappings":";cAmBa,GAAA,EAAG,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+GA,OAAA,CAAA,UAAkB,GAAA;AAAA,iBAWlB,kBAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;KAwCJ,GAAA,UAAa,GAAA"}
|
package/dist/index.mjs
ADDED
package/dist/keys.d.mts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
//#region keys.d.ts
|
|
2
|
+
type KeyPattern = 'timestamped' | 'uuid' | 'random' | 'custom';
|
|
3
|
+
interface KeyGenerationOptions {
|
|
4
|
+
pattern?: KeyPattern;
|
|
5
|
+
prefix?: string;
|
|
6
|
+
suffix?: string;
|
|
7
|
+
extension?: string;
|
|
8
|
+
includeTimestamp?: boolean;
|
|
9
|
+
customFormat?: (base: string) => string;
|
|
10
|
+
}
|
|
11
|
+
declare function generateStorageKey(options?: KeyGenerationOptions): string;
|
|
12
|
+
declare function parseStorageKey(key: string): {
|
|
13
|
+
prefix?: string;
|
|
14
|
+
path: string;
|
|
15
|
+
filename: string;
|
|
16
|
+
name: string;
|
|
17
|
+
extension: string;
|
|
18
|
+
isTimestamped: boolean;
|
|
19
|
+
isUuid: boolean;
|
|
20
|
+
};
|
|
21
|
+
declare function validateStorageKey(key: string, options?: {
|
|
22
|
+
required?: boolean;
|
|
23
|
+
maxLength?: number;
|
|
24
|
+
allowedExtensions?: string[];
|
|
25
|
+
forbiddenPatterns?: RegExp[];
|
|
26
|
+
allowEmpty?: boolean;
|
|
27
|
+
}): {
|
|
28
|
+
valid: boolean;
|
|
29
|
+
errors: string[];
|
|
30
|
+
};
|
|
31
|
+
declare function normalizeStorageKey(key: string): string;
|
|
32
|
+
declare function sanitizeStorageKey(key: string): string;
|
|
33
|
+
declare function generateMultipleKeys(count: number, options?: KeyGenerationOptions): string[];
|
|
34
|
+
declare function isKeyPattern(key: string, pattern: KeyPattern): boolean;
|
|
35
|
+
//#endregion
|
|
36
|
+
export { KeyGenerationOptions, KeyPattern, generateMultipleKeys, generateStorageKey, isKeyPattern, normalizeStorageKey, parseStorageKey, sanitizeStorageKey, validateStorageKey };
|
|
37
|
+
//# sourceMappingURL=keys.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keys.d.mts","names":[],"sources":["../keys.ts"],"mappings":";KAwBY,UAAA;AAAA,UAKK,oBAAA;EACf,OAAA,GAAU,UAAA;EACV,MAAA;EACA,MAAA;EACA,SAAA;EACA,gBAAA;EACA,YAAA,IAAgB,IAAA;AAAA;AAAA,iBA2BF,kBAAA,CAAmB,OAAA,GAAS,oBAAA;AAAA,iBAqF5B,eAAA,CAAgB,GAAA;EAC9B,MAAA;EACA,IAAA;EACA,QAAA;EACA,IAAA;EACA,SAAA;EACA,aAAA;EACA,MAAA;AAAA;AAAA,iBAwDc,kBAAA,CACd,GAAA,UACA,OAAA;EACE,QAAA;EACA,SAAA;EACA,iBAAA;EACA,iBAAA,GAAoB,MAAA;EACpB,UAAA;AAAA;EAEC,KAAA;EAAgB,MAAA;AAAA;AAAA,iBA0FL,mBAAA,CAAoB,GAAA;AAAA,iBAwBpB,kBAAA,CAAmB,GAAA;AAAA,iBA8BnB,oBAAA,CAAqB,KAAA,UAAe,OAAA,GAAS,oBAAA;AAAA,iBA6B7C,YAAA,CAAa,GAAA,UAAa,OAAA,EAAS,UAAA"}
|
package/dist/keys.mjs
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
//#region keys.ts
|
|
2
|
+
/**
|
|
3
|
+
* @fileoverview Storage Key Generation and Management Utilities
|
|
4
|
+
* Storage Key Generation and Management Utilities
|
|
5
|
+
*
|
|
6
|
+
* Provides utilities for generating, parsing, and validating storage keys
|
|
7
|
+
* with support for various patterns and path normalization.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Generate a cryptographically secure alphanumeric string
|
|
11
|
+
*
|
|
12
|
+
* @param length - Length of the string to generate
|
|
13
|
+
* @returns Alphanumeric string (0-9a-zA-Z)
|
|
14
|
+
*/
|
|
15
|
+
function generateAlphanumeric(length) {
|
|
16
|
+
const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
17
|
+
const randomValues = new Uint8Array(length);
|
|
18
|
+
crypto.getRandomValues(randomValues);
|
|
19
|
+
return Array.from(randomValues, (byte) => chars[byte % 62]).join("");
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Generate a storage key using various patterns
|
|
23
|
+
*
|
|
24
|
+
* @param options - Key generation options
|
|
25
|
+
* @returns Generated storage key
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```typescript
|
|
29
|
+
* // Timestamped key
|
|
30
|
+
* generateStorageKey({ pattern: 'timestamped', prefix: 'uploads' })
|
|
31
|
+
* // → "uploads/2024/01/15/abc123.jpg"
|
|
32
|
+
*
|
|
33
|
+
* // UUID key
|
|
34
|
+
* generateStorageKey({ pattern: 'uuid', extension: 'pdf' })
|
|
35
|
+
* // → "550e8400-e29b-41d4-a716-446655440000.pdf"
|
|
36
|
+
*
|
|
37
|
+
* // Custom pattern
|
|
38
|
+
* generateStorageKey({
|
|
39
|
+
* pattern: 'custom',
|
|
40
|
+
* customFormat: (base) => `user-${base}-${Date.now()}`
|
|
41
|
+
* })
|
|
42
|
+
* // → "user-abc123-1705123456789"
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
function generateStorageKey(options = {}) {
|
|
46
|
+
const { pattern = "random", prefix = "", suffix = "", extension = "", includeTimestamp = false, customFormat } = options;
|
|
47
|
+
let baseKey;
|
|
48
|
+
switch (pattern) {
|
|
49
|
+
case "timestamped":
|
|
50
|
+
const now = /* @__PURE__ */ new Date();
|
|
51
|
+
baseKey = `${now.getFullYear()}/${(now.getMonth() + 1).toString().padStart(2, "0")}/${now.getDate().toString().padStart(2, "0")}/${generateAlphanumeric(6)}`;
|
|
52
|
+
break;
|
|
53
|
+
case "uuid":
|
|
54
|
+
baseKey = crypto.randomUUID();
|
|
55
|
+
break;
|
|
56
|
+
case "random":
|
|
57
|
+
baseKey = generateAlphanumeric(12);
|
|
58
|
+
break;
|
|
59
|
+
case "custom":
|
|
60
|
+
if (!customFormat) throw new Error("customFormat is required for custom pattern");
|
|
61
|
+
baseKey = customFormat(generateAlphanumeric(8));
|
|
62
|
+
break;
|
|
63
|
+
default: baseKey = generateAlphanumeric(12);
|
|
64
|
+
}
|
|
65
|
+
if (includeTimestamp && pattern !== "timestamped") baseKey = `${baseKey}-${Date.now()}`;
|
|
66
|
+
if (extension) {
|
|
67
|
+
const ext = extension.startsWith(".") ? extension : `.${extension}`;
|
|
68
|
+
baseKey = `${baseKey}${ext}`;
|
|
69
|
+
}
|
|
70
|
+
let finalKey = baseKey;
|
|
71
|
+
if (prefix) finalKey = `${prefix}/${finalKey}`;
|
|
72
|
+
if (suffix) finalKey = `${finalKey.replace(/\.[^/.]+$/, "")}-${suffix}${finalKey.match(/\.[^/.]+$/)?.[0] ?? ""}`;
|
|
73
|
+
return finalKey;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Parse a storage key to extract components
|
|
77
|
+
*
|
|
78
|
+
* @param key - Storage key to parse
|
|
79
|
+
* @returns Parsed key components
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```typescript
|
|
83
|
+
* parseStorageKey('uploads/2024/01/15/abc123.jpg')
|
|
84
|
+
* // → {
|
|
85
|
+
* // prefix: 'uploads',
|
|
86
|
+
* // path: '2024/01/15',
|
|
87
|
+
* // filename: 'abc123.jpg',
|
|
88
|
+
* // name: 'abc123',
|
|
89
|
+
* // extension: '.jpg',
|
|
90
|
+
* // isTimestamped: true
|
|
91
|
+
* // }
|
|
92
|
+
* ```
|
|
93
|
+
*/
|
|
94
|
+
function parseStorageKey(key) {
|
|
95
|
+
if (!key || typeof key !== "string") throw new Error("Invalid storage key: must be a non-empty string");
|
|
96
|
+
if (key.length > 1024) throw new Error("Storage key exceeds maximum length (1024 characters)");
|
|
97
|
+
const parts = key.split("/");
|
|
98
|
+
const filename = parts[parts.length - 1] ?? "";
|
|
99
|
+
const pathParts = parts.slice(0, -1);
|
|
100
|
+
const prefix = pathParts.length > 1 ? pathParts[0] : void 0;
|
|
101
|
+
const path = pathParts.length > 1 ? pathParts.slice(1).join("/") : pathParts.join("/");
|
|
102
|
+
const lastDotIndex = filename.lastIndexOf(".");
|
|
103
|
+
const name = lastDotIndex > 0 ? filename.substring(0, lastDotIndex) : filename;
|
|
104
|
+
return {
|
|
105
|
+
prefix,
|
|
106
|
+
path,
|
|
107
|
+
filename,
|
|
108
|
+
name,
|
|
109
|
+
extension: lastDotIndex > 0 ? filename.substring(lastDotIndex) : "",
|
|
110
|
+
isTimestamped: /^\d{4}\/\d{2}\/\d{2}\//.test(key),
|
|
111
|
+
isUuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(name)
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Validate a storage key
|
|
116
|
+
*
|
|
117
|
+
* @param key - Storage key to validate
|
|
118
|
+
* @param options - Validation options
|
|
119
|
+
* @returns Validation result
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* validateStorageKey('uploads/file.jpg', { maxLength: 100 })
|
|
124
|
+
* // → { valid: true, errors: [] }
|
|
125
|
+
*
|
|
126
|
+
* validateStorageKey('', { required: true })
|
|
127
|
+
* // → { valid: false, errors: ['Key cannot be empty'] }
|
|
128
|
+
* ```
|
|
129
|
+
*/
|
|
130
|
+
function validateStorageKey(key, options = {}) {
|
|
131
|
+
const { required = true, maxLength = 1024, allowedExtensions = [], forbiddenPatterns = [], allowEmpty = false } = options;
|
|
132
|
+
const errors = [];
|
|
133
|
+
if (allowEmpty && (!key || key.trim() === "")) return {
|
|
134
|
+
valid: true,
|
|
135
|
+
errors: []
|
|
136
|
+
};
|
|
137
|
+
if (required && (!key || key.trim() === "")) {
|
|
138
|
+
errors.push("Key cannot be empty");
|
|
139
|
+
return {
|
|
140
|
+
valid: false,
|
|
141
|
+
errors
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
if (!allowEmpty && (!key || key.trim() === "")) {
|
|
145
|
+
errors.push("Key cannot be empty");
|
|
146
|
+
return {
|
|
147
|
+
valid: false,
|
|
148
|
+
errors
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
if (key.length > maxLength) errors.push(`Key exceeds maximum length of ${maxLength} characters`);
|
|
152
|
+
for (const pattern of forbiddenPatterns) if (pattern.test(key)) errors.push(`Key matches forbidden pattern: ${pattern.source}`);
|
|
153
|
+
if (/[<>:"|?*]/.test(key)) errors.push("Key contains invalid characters: < > : \" | ? *");
|
|
154
|
+
if (key.includes("//")) errors.push("Key contains double slashes");
|
|
155
|
+
if (key.startsWith("/") || key.endsWith("/")) errors.push("Key should not start or end with slashes");
|
|
156
|
+
if (key.includes("../") || key.includes("./")) errors.push("Key contains relative path traversal");
|
|
157
|
+
if (allowedExtensions.length > 0) {
|
|
158
|
+
const extension = key.match(/\.[^/.]+$/)?.[0]?.toLowerCase();
|
|
159
|
+
if (extension && !allowedExtensions.includes(extension)) errors.push(`File extension ${extension} is not allowed. Allowed: ${allowedExtensions.join(", ")}`);
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
valid: errors.length === 0,
|
|
163
|
+
errors
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Normalize a storage key path
|
|
168
|
+
*
|
|
169
|
+
* @param key - Storage key to normalize
|
|
170
|
+
* @returns Normalized storage key
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```typescript
|
|
174
|
+
* normalizeStorageKey('uploads//folder///file.jpg')
|
|
175
|
+
* // → "uploads/folder/file.jpg"
|
|
176
|
+
*
|
|
177
|
+
* normalizeStorageKey('/uploads/file.jpg/')
|
|
178
|
+
* // → "uploads/file.jpg"
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
function normalizeStorageKey(key) {
|
|
182
|
+
if (!key || typeof key !== "string") return "";
|
|
183
|
+
return key.replace(/\/+/g, "/").replace(/^\/+/, "").replace(/\/+$/, "").trim();
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Sanitize a storage key by removing dangerous characters
|
|
187
|
+
*
|
|
188
|
+
* @param key - Storage key to sanitize
|
|
189
|
+
* @returns Sanitized storage key
|
|
190
|
+
*
|
|
191
|
+
* @example
|
|
192
|
+
* ```typescript
|
|
193
|
+
* sanitizeStorageKey('uploads/file<script>.jpg')
|
|
194
|
+
* // → "uploads/filescript.jpg"
|
|
195
|
+
* ```
|
|
196
|
+
*/
|
|
197
|
+
function sanitizeStorageKey(key) {
|
|
198
|
+
if (!key || typeof key !== "string") return "";
|
|
199
|
+
return key.replace(/[<>:"|?*]/g, "").replace(/[^\w\s.-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Generate multiple storage keys
|
|
203
|
+
*
|
|
204
|
+
* @param count - Number of keys to generate
|
|
205
|
+
* @param options - Key generation options
|
|
206
|
+
* @returns Array of generated storage keys
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* ```typescript
|
|
210
|
+
* generateMultipleKeys(3, { pattern: 'uuid', prefix: 'uploads' })
|
|
211
|
+
* // → [
|
|
212
|
+
* // "uploads/550e8400-e29b-41d4-a716-446655440000",
|
|
213
|
+
* // "uploads/6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
|
214
|
+
* // "uploads/6ba7b811-9dad-11d1-80b4-00c04fd430c8"
|
|
215
|
+
* // ]
|
|
216
|
+
* ```
|
|
217
|
+
*/
|
|
218
|
+
function generateMultipleKeys(count, options = {}) {
|
|
219
|
+
if (count <= 0) return [];
|
|
220
|
+
const keys = [];
|
|
221
|
+
for (let i = 0; i < count; i++) keys.push(generateStorageKey(options));
|
|
222
|
+
return keys;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Check if a storage key follows a specific pattern
|
|
226
|
+
*
|
|
227
|
+
* @param key - Storage key to check
|
|
228
|
+
* @param pattern - Pattern to match against
|
|
229
|
+
* @returns True if key matches pattern
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```typescript
|
|
233
|
+
* isKeyPattern('uploads/2024/01/15/file.jpg', 'timestamped')
|
|
234
|
+
* // → true
|
|
235
|
+
*
|
|
236
|
+
* isKeyPattern('550e8400-e29b-41d4-a716-446655440000', 'uuid')
|
|
237
|
+
* // → true
|
|
238
|
+
* ```
|
|
239
|
+
*/
|
|
240
|
+
function isKeyPattern(key, pattern) {
|
|
241
|
+
const parsed = parseStorageKey(key);
|
|
242
|
+
switch (pattern) {
|
|
243
|
+
case "timestamped": return parsed.isTimestamped;
|
|
244
|
+
case "uuid": return parsed.isUuid;
|
|
245
|
+
case "random": return !parsed.isTimestamped && !parsed.isUuid;
|
|
246
|
+
case "custom": return !parsed.isTimestamped && !parsed.isUuid;
|
|
247
|
+
default: return false;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
//#endregion
|
|
252
|
+
export { generateMultipleKeys, generateStorageKey, isKeyPattern, normalizeStorageKey, parseStorageKey, sanitizeStorageKey, validateStorageKey };
|
|
253
|
+
//# sourceMappingURL=keys.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keys.mjs","names":[],"sources":["../keys.ts"],"sourcesContent":["/**\n * @fileoverview Storage Key Generation and Management Utilities\n * Storage Key Generation and Management Utilities\n *\n * Provides utilities for generating, parsing, and validating storage keys\n * with support for various patterns and path normalization.\n */\n\n/**\n * Generate a cryptographically secure alphanumeric string\n *\n * @param length - Length of the string to generate\n * @returns Alphanumeric string (0-9a-zA-Z)\n */\nfunction generateAlphanumeric(length: number): string {\n const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n const randomValues = new Uint8Array(length);\n crypto.getRandomValues(randomValues);\n return Array.from(randomValues, (byte) => chars[byte % chars.length]).join('');\n}\n\n/**\n * Storage key generation patterns\n */\nexport type KeyPattern = 'timestamped' | 'uuid' | 'random' | 'custom';\n\n/**\n * Options for key generation\n */\nexport interface KeyGenerationOptions {\n pattern?: KeyPattern;\n prefix?: string;\n suffix?: string;\n extension?: string;\n includeTimestamp?: boolean;\n customFormat?: (base: string) => string;\n}\n\n/**\n * Generate a storage key using various patterns\n *\n * @param options - Key generation options\n * @returns Generated storage key\n *\n * @example\n * ```typescript\n * // Timestamped key\n * generateStorageKey({ pattern: 'timestamped', prefix: 'uploads' })\n * // → \"uploads/2024/01/15/abc123.jpg\"\n *\n * // UUID key\n * generateStorageKey({ pattern: 'uuid', extension: 'pdf' })\n * // → \"550e8400-e29b-41d4-a716-446655440000.pdf\"\n *\n * // Custom pattern\n * generateStorageKey({\n * pattern: 'custom',\n * customFormat: (base) => `user-${base}-${Date.now()}`\n * })\n * // → \"user-abc123-1705123456789\"\n * ```\n */\nexport function generateStorageKey(options: KeyGenerationOptions = {}): string {\n const {\n pattern = 'random',\n prefix = '',\n suffix = '',\n extension = '',\n includeTimestamp = false,\n customFormat,\n } = options;\n\n let baseKey: string;\n\n switch (pattern) {\n case 'timestamped':\n const now = new Date();\n const year = now.getFullYear();\n const month = (now.getMonth() + 1).toString().padStart(2, '0');\n const day = now.getDate().toString().padStart(2, '0');\n const randomId = generateAlphanumeric(6);\n baseKey = `${year}/${month}/${day}/${randomId}`;\n break;\n\n case 'uuid':\n baseKey = crypto.randomUUID();\n break;\n\n case 'random':\n baseKey = generateAlphanumeric(12);\n break;\n\n case 'custom':\n if (!customFormat) {\n throw new Error('customFormat is required for custom pattern');\n }\n baseKey = customFormat(generateAlphanumeric(8));\n break;\n\n default:\n baseKey = generateAlphanumeric(12);\n }\n\n // Add timestamp if requested\n if (includeTimestamp && pattern !== 'timestamped') {\n baseKey = `${baseKey}-${Date.now()}`;\n }\n\n // Add extension\n if (extension) {\n const ext = extension.startsWith('.') ? extension : `.${extension}`;\n baseKey = `${baseKey}${ext}`;\n }\n\n // Add prefix and suffix\n let finalKey = baseKey;\n if (prefix) {\n finalKey = `${prefix}/${finalKey}`;\n }\n if (suffix) {\n const nameWithoutExt = finalKey.replace(/\\.[^/.]+$/, '');\n const ext = finalKey.match(/\\.[^/.]+$/)?.[0] ?? '';\n finalKey = `${nameWithoutExt}-${suffix}${ext}`;\n }\n\n return finalKey;\n}\n\n/**\n * Parse a storage key to extract components\n *\n * @param key - Storage key to parse\n * @returns Parsed key components\n *\n * @example\n * ```typescript\n * parseStorageKey('uploads/2024/01/15/abc123.jpg')\n * // → {\n * // prefix: 'uploads',\n * // path: '2024/01/15',\n * // filename: 'abc123.jpg',\n * // name: 'abc123',\n * // extension: '.jpg',\n * // isTimestamped: true\n * // }\n * ```\n */\nexport function parseStorageKey(key: string): {\n prefix?: string;\n path: string;\n filename: string;\n name: string;\n extension: string;\n isTimestamped: boolean;\n isUuid: boolean;\n} {\n // Input validation\n if (!key || typeof key !== 'string') {\n throw new Error('Invalid storage key: must be a non-empty string');\n }\n\n // Prevent DoS via extremely long keys (max 1024 characters)\n if (key.length > 1024) {\n throw new Error('Storage key exceeds maximum length (1024 characters)');\n }\n\n const parts = key.split('/');\n const filename = parts[parts.length - 1] ?? '';\n const pathParts = parts.slice(0, -1);\n\n // Extract prefix (first part if multiple parts)\n const prefix = pathParts.length > 1 ? pathParts[0] : undefined;\n const path = pathParts.length > 1 ? pathParts.slice(1).join('/') : pathParts.join('/');\n\n // Extract filename components\n const lastDotIndex = filename.lastIndexOf('.');\n const name = lastDotIndex > 0 ? filename.substring(0, lastDotIndex) : filename;\n const extension = lastDotIndex > 0 ? filename.substring(lastDotIndex) : '';\n\n // Detect patterns\n const isTimestamped = /^\\d{4}\\/\\d{2}\\/\\d{2}\\//.test(key);\n const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(name);\n\n return {\n prefix,\n path,\n filename,\n name,\n extension,\n isTimestamped,\n isUuid,\n };\n}\n\n/**\n * Validate a storage key\n *\n * @param key - Storage key to validate\n * @param options - Validation options\n * @returns Validation result\n *\n * @example\n * ```typescript\n * validateStorageKey('uploads/file.jpg', { maxLength: 100 })\n * // → { valid: true, errors: [] }\n *\n * validateStorageKey('', { required: true })\n * // → { valid: false, errors: ['Key cannot be empty'] }\n * ```\n */\nexport function validateStorageKey(\n key: string,\n options: {\n required?: boolean;\n maxLength?: number;\n allowedExtensions?: string[];\n forbiddenPatterns?: RegExp[];\n allowEmpty?: boolean;\n } = {},\n): { valid: boolean; errors: string[] } {\n const {\n required = true,\n maxLength = 1024,\n allowedExtensions = [],\n forbiddenPatterns = [],\n allowEmpty = false,\n } = options;\n\n const errors: string[] = [];\n\n // If allowEmpty is explicitly set to true, empty keys are valid\n if (allowEmpty && (!key || key.trim() === '')) {\n return { valid: true, errors: [] };\n }\n\n // Check if key is provided\n if (required && (!key || key.trim() === '')) {\n errors.push('Key cannot be empty');\n return { valid: false, errors };\n }\n\n if (!allowEmpty && (!key || key.trim() === '')) {\n errors.push('Key cannot be empty');\n return { valid: false, errors };\n }\n\n // Check length\n if (key.length > maxLength) {\n errors.push(`Key exceeds maximum length of ${maxLength} characters`);\n }\n\n // Check for forbidden patterns\n for (const pattern of forbiddenPatterns) {\n if (pattern.test(key)) {\n errors.push(`Key matches forbidden pattern: ${pattern.source}`);\n }\n }\n\n // Check for invalid characters\n if (/[<>:\"|?*]/.test(key)) {\n errors.push('Key contains invalid characters: < > : \" | ? *');\n }\n\n // Check for double slashes\n if (key.includes('//')) {\n errors.push('Key contains double slashes');\n }\n\n // Check for leading/trailing slashes\n if (key.startsWith('/') || key.endsWith('/')) {\n errors.push('Key should not start or end with slashes');\n }\n\n // Check for relative path traversal\n if (key.includes('../') || key.includes('./')) {\n errors.push('Key contains relative path traversal');\n }\n\n // Check file extension if specified\n if (allowedExtensions.length > 0) {\n const extension = key.match(/\\.[^/.]+$/)?.[0]?.toLowerCase();\n if (extension && !allowedExtensions.includes(extension)) {\n errors.push(\n `File extension ${extension} is not allowed. Allowed: ${allowedExtensions.join(', ')}`,\n );\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n}\n\n/**\n * Normalize a storage key path\n *\n * @param key - Storage key to normalize\n * @returns Normalized storage key\n *\n * @example\n * ```typescript\n * normalizeStorageKey('uploads//folder///file.jpg')\n * // → \"uploads/folder/file.jpg\"\n *\n * normalizeStorageKey('/uploads/file.jpg/')\n * // → \"uploads/file.jpg\"\n * ```\n */\nexport function normalizeStorageKey(key: string): string {\n if (!key || typeof key !== 'string') {\n return '';\n }\n\n return key\n .replace(/\\/+/g, '/') // Replace multiple slashes with single slash\n .replace(/^\\/+/, '') // Remove leading slashes\n .replace(/\\/+$/, '') // Remove trailing slashes\n .trim();\n}\n\n/**\n * Sanitize a storage key by removing dangerous characters\n *\n * @param key - Storage key to sanitize\n * @returns Sanitized storage key\n *\n * @example\n * ```typescript\n * sanitizeStorageKey('uploads/file<script>.jpg')\n * // → \"uploads/filescript.jpg\"\n * ```\n */\nexport function sanitizeStorageKey(key: string): string {\n if (!key || typeof key !== 'string') {\n return '';\n }\n\n return key\n .replace(/[<>:\"|?*]/g, '') // Remove dangerous characters\n .replace(/[^\\w\\s.-]/g, '') // Keep only word chars, spaces, dots, hyphens\n .replace(/\\s+/g, '-') // Replace spaces with hyphens\n .replace(/-+/g, '-') // Replace multiple hyphens with single hyphen\n .replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens\n}\n\n/**\n * Generate multiple storage keys\n *\n * @param count - Number of keys to generate\n * @param options - Key generation options\n * @returns Array of generated storage keys\n *\n * @example\n * ```typescript\n * generateMultipleKeys(3, { pattern: 'uuid', prefix: 'uploads' })\n * // → [\n * // \"uploads/550e8400-e29b-41d4-a716-446655440000\",\n * // \"uploads/6ba7b810-9dad-11d1-80b4-00c04fd430c8\",\n * // \"uploads/6ba7b811-9dad-11d1-80b4-00c04fd430c8\"\n * // ]\n * ```\n */\nexport function generateMultipleKeys(count: number, options: KeyGenerationOptions = {}): string[] {\n if (count <= 0) {\n return [];\n }\n\n const keys: string[] = [];\n for (let i = 0; i < count; i++) {\n keys.push(generateStorageKey(options));\n }\n\n return keys;\n}\n\n/**\n * Check if a storage key follows a specific pattern\n *\n * @param key - Storage key to check\n * @param pattern - Pattern to match against\n * @returns True if key matches pattern\n *\n * @example\n * ```typescript\n * isKeyPattern('uploads/2024/01/15/file.jpg', 'timestamped')\n * // → true\n *\n * isKeyPattern('550e8400-e29b-41d4-a716-446655440000', 'uuid')\n * // → true\n * ```\n */\nexport function isKeyPattern(key: string, pattern: KeyPattern): boolean {\n const parsed = parseStorageKey(key);\n\n switch (pattern) {\n case 'timestamped':\n return parsed.isTimestamped;\n case 'uuid':\n return parsed.isUuid;\n case 'random':\n return !parsed.isTimestamped && !parsed.isUuid;\n case 'custom':\n return !parsed.isTimestamped && !parsed.isUuid;\n default:\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,SAAS,qBAAqB,QAAwB;CACpD,MAAM,QAAQ;CACd,MAAM,eAAe,IAAI,WAAW,OAAO;AAC3C,QAAO,gBAAgB,aAAa;AACpC,QAAO,MAAM,KAAK,eAAe,SAAS,MAAM,OAAO,IAAc,CAAC,KAAK,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;AA4ChF,SAAgB,mBAAmB,UAAgC,EAAE,EAAU;CAC7E,MAAM,EACJ,UAAU,UACV,SAAS,IACT,SAAS,IACT,YAAY,IACZ,mBAAmB,OACnB,iBACE;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