/** * Media Storage Types * * Defines interfaces and types for the unified media storage system. * Supports cloud storage adapters via plugins. * * Storage Backends: * - AWS S3 / Cloudflare R2 / MinIO (via @nextlyhq/storage-s3) * - Vercel Blob (via @nextlyhq/storage-vercel-blob) */ interface UploadOptions { /** Original filename from user */ filename: string; /** MIME type (e.g., 'image/png', 'video/mp4') */ mimeType: string; /** Optional content type override */ contentType?: string; /** Optional folder/prefix for organizing uploads */ folder?: string; /** Collection slug this upload belongs to (for collection-specific storage) */ collection?: string; /** Optional Content-Disposition header value (e.g., 'attachment' for SVG security) */ contentDisposition?: "inline" | "attachment"; } interface UploadResult { /** Public URL to access the file */ url: string; /** Storage path/key (for deletion and metadata retrieval) */ path: string; } /** * Extended file metadata returned by getMetadata() * * Contains comprehensive information about an uploaded file, * including dimensions for images and creation timestamps. */ interface FileMetadata { /** Unique identifier (typically the storage path/key) */ id: string; /** Storage filename (may differ from original) */ filename: string; /** Original filename as uploaded by user */ originalFilename: string; /** MIME type (e.g., 'image/jpeg', 'application/pdf') */ mimeType: string; /** File size in bytes */ size: number; /** Public URL to access the file */ url: string; /** Thumbnail URL for images (if generated) */ thumbnailUrl?: string; /** Image width in pixels (for images only) */ width?: number; /** Image height in pixels (for images only) */ height?: number; /** ISO timestamp when file was uploaded */ createdAt: string; /** ISO timestamp when file was last modified */ updatedAt?: string; } /** * Storage type identifier. * - "s3": AWS S3 or S3-compatible services (R2, MinIO, DigitalOcean Spaces) * - "vercel-blob": Vercel Blob Storage * - "local": Local disk storage (default for development) * - "uploadthing": Uploadthing cloud storage */ type StorageType = "s3" | "vercel-blob" | "local" | "uploadthing"; /** * Information about a storage adapter's capabilities. * Returned by adapter.getInfo() method. */ /** * Bounds for a read that pulls an object into memory. * * Reading a stored object means BUFFERING it, so its size is the caller's * problem whether or not the caller says so. Left unbounded, a large object * consumes as much process memory as it happens to occupy, and a stalled * backend holds the request until something further out gives up. * * OPTIONAL, with the defaults living in the fetch layer rather than being * restated per adapter — a second set of numbers agrees today and drifts. What * this type exists for is the caller that already knows its own limit: the * email attachment path caps a read at the configured attachment size, so an * oversized object fails as a size error rather than after it has been read. */ interface StorageReadOptions { /** Refuse once this many bytes have arrived. Defaults to the fetch cap. */ maxBytes?: number; /** Give up after this long. Defaults to the fetch deadline. */ timeoutMs?: number; } interface StorageAdapterInfo { /** Storage type identifier */ type: StorageType; /** Human-readable adapter name */ name: string; /** Whether this adapter supports signed URLs for private access */ supportsSignedUrls: boolean; /** Whether this adapter supports client-side (direct) uploads */ supportsClientUploads: boolean; /** * Whether files written through the private calls (`putPrivate`, * `getPrivateUploadUrl`) can be reached only through Nextly: no public * address serves them. An adapter says so only when it is configured that * way, for example with no public URL in front of its bucket. Absent means * no, so a collection of private files is never stored where it may be * public. * * @experimental */ supportsPrivateFiles?: boolean; } /** * What a storage says about an object it holds, read without its bytes. * * @experimental */ interface StoredObjectHead { /** The object's size in bytes, as stored. */ size: number; /** The type it was stored with, where the storage keeps one. */ contentType?: string; /** When it was last written, where the storage says. */ lastModified?: Date; } /** * Bounds for a read handed back as a stream. * * @experimental */ interface StorageStreamOptions { /** * Give up when the storage has not started answering after this long. The * transfer itself is not bounded: its reader decides how long it takes. */ timeoutMs?: number; } /** * A short-lived link to a private file, as the private download call takes it. * * @experimental */ interface PrivateDownloadUrlOptions { /** How long the link lasts, in seconds, within the adapter's own cap. */ expiresIn: number; /** The Content-Disposition the storage answers the link with. */ contentDisposition: string; /** The Content-Type the storage answers the link with. */ contentType?: string; } /** * A direct upload of a private file, as the private upload call takes it. * * @experimental */ interface PrivateUploadUrlOptions { /** The file's exact size in bytes; storage refuses a body of another length. */ contentLength: number; /** How long the URL lasts, in seconds, within the adapter's own cap. */ expiresIn: number; } /** * Per-collection storage configuration. * Allows customizing storage behavior for specific upload collections. */ interface CollectionStorageConfig { /** Prefix/folder for this collection's uploads */ prefix?: string; /** Enable client-side uploads (for serverless platforms with body size limits) */ clientUploads?: boolean; /** Generate signed URLs for downloads (for private buckets) */ signedDownloads?: boolean; /** Signed URL expiry time in seconds (default: 3600) */ signedUrlExpiresIn?: number; } /** * Collection storage map - maps collection slugs to their config. * Used in storage plugin configuration. * * @example * ```typescript * { * media: true, // Use default config * 'private-docs': { * prefix: 'private/', * signedDownloads: true, * signedUrlExpiresIn: 900 * } * } * ``` */ type CollectionStorageMap = Record; /** * Base configuration for storage plugins. * Extended by specific adapter configs (S3StorageConfig, etc.) */ interface StoragePluginConfig { /** Enable/disable the plugin (default: true) */ enabled?: boolean; /** Collections to apply this storage adapter to */ collections: CollectionStorageMap; } /** * Storage plugin returned by adapter plugin functions. * These are processed during Nextly initialization. * * @example * ```typescript * // From @nextlyhq/storage-s3 * const plugin = s3Storage({ * bucket: 'my-bucket', * region: 'us-east-1', * collections: { media: true } * }); * // plugin implements StoragePlugin * ``` */ interface StoragePlugin { /** Plugin name for identification */ name: string; /** Storage type */ type: StorageType; /** Collections this plugin handles */ collections: CollectionStorageMap; /** The storage adapter instance */ adapter: IStorageAdapter; /** * Handler for generating client-side upload URLs. * Called when clientUploads is enabled for a collection, for a file whose * name, type and size the upload checks have already allowed. The URL must * bind the type and `options.size`, so storage refuses a different file: * its bytes never pass Nextly's checks. */ getClientUploadUrl?: (filename: string, mimeType: string, collection: string, options: ClientUploadOptions) => Promise; /** * Handler for generating signed download URLs. * Called when signedDownloads is enabled for a collection. */ getSignedDownloadUrl?: (path: string, expiresIn?: number) => Promise; } /** What a signed client upload is bound to, besides its key and type. */ interface ClientUploadOptions { /** The file's exact size in bytes; storage refuses a body of another length. */ size: number; /** How long the URL lasts, in seconds, within the adapter's own cap. */ expiresIn?: number; } /** * Data returned for client-side (direct) uploads. * Contains pre-signed URL and headers for direct-to-storage uploads. * * @example * ```typescript * // Usage in frontend * const uploadData = await fetch('/api/nextly/storage/upload-url', { * method: 'POST', * body: JSON.stringify({ filename: 'photo.jpg', mimeType: 'image/jpeg', collection: 'media' }) * }).then(r => r.json()); * * // Direct upload to storage * await fetch(uploadData.uploadUrl, { * method: uploadData.method, * headers: uploadData.headers, * body: file * }); * ``` */ interface ClientUploadData { /** Pre-signed URL for direct upload */ uploadUrl: string; /** Storage path/key that will be used */ path: string; /** HTTP method to use (usually PUT for S3, POST for some services) */ method: "PUT" | "POST"; /** Headers to include in upload request */ headers?: Record; /** Form fields for multipart uploads (some services require this) */ fields?: Record; /** URL expiry timestamp */ expiresAt: Date; } /** * Base storage adapter interface. * All storage adapters must implement this interface. * * Core methods (required): * - upload: Store file buffer * - delete: Remove file from storage * - exists: Check if file exists * - getPublicUrl: Get public URL for file access * - getType: Get storage type identifier * * Optional methods: * - getInfo: Get adapter capabilities (recommended) * - getMetadata: Retrieve file metadata * - getSignedUrl: Generate temporary signed URLs for private access * - getPresignedUploadUrl: Generate pre-signed URL for client uploads */ /** A file a storage holds, as {@link IStorageAdapter.list} names it. */ interface StoredFileEntry { /** The stored path, as `upload` returned it and `delete` takes it. */ path: string; /** When it was stored, where the storage says. */ lastModified?: Date; /** * The name it was uploaded under, where the storage keeps that apart from * its path: UploadThing's keys carry no name. Elsewhere the name is the * path's last segment. */ name?: string; } interface BulkDeleteResult { successful: string[]; failed: Array<{ filePath: string; error: string; }>; } interface IStorageAdapter { /** Upload file buffer to storage */ upload(buffer: Buffer, options: UploadOptions): Promise; /** * Store bytes at exactly `filePath`, replacing anything there (optional). * * Core calls it only with a key it derived from a file this storage already * holds, to keep a file made from that one, such as a resized copy of an * image, beside it. A storage without it cannot keep such files, and core * serves the original instead. `upload` stays the way new files are * stored, since it is the storage that chooses their keys. * * @experimental */ uploadAt?(filePath: string, buffer: Buffer, options: { mimeType: string; }): Promise; /** Delete file from storage */ delete(filePath: string): Promise; /** Bulk delete files from storage. Optional — adapters that support batch operations should implement this. */ bulkDelete?(filePaths: string[]): Promise; /** Check if file exists in storage */ exists(filePath: string): Promise; /** Get public URL for file */ getPublicUrl(filePath: string): string; /** Get storage type identifier */ getType(): string; /** Read file contents from storage (optional - not all adapters support this) */ read?(filePath: string, options?: StorageReadOptions): Promise; /** Get adapter info including capabilities (optional but recommended) */ getInfo?(): StorageAdapterInfo; /** Get file metadata (optional - not all adapters support this) */ getMetadata?(filePath: string): Promise; /** Generate signed URL for temporary private access (optional) */ getSignedUrl?(filePath: string, expiresIn?: number): Promise; /** * Generate pre-signed upload URL for client-side uploads (optional). With * `options.contentLength`, the signature binds the body's exact length. */ getPresignedUploadUrl?(key: string, mimeType: string, expiresIn?: number, options?: { contentLength?: number; }): Promise; /** * Every file the storage holds, a page at a time (optional). Used to find * files no record refers to; a storage without it cannot be searched for * them, which is said rather than taken as "none". */ list?(): AsyncIterable; /** * What the storage holds at `filePath`, its size and type, without reading * it (optional); `null` when nothing is there. * * @experimental */ head?(filePath: string): Promise; /** * The file's bytes as a stream, for a response that should not hold the * whole file in memory (optional); `null` when nothing is there. * * @experimental */ readStream?(filePath: string, options?: StorageStreamOptions): Promise | null>; /** * Store a private file at exactly `key` (optional). Unlike `upload`, the key * is core's (it names no file and no person), no public address is formed, * the original file name is kept nowhere in the storage, and the object is * marked never to be cached. Required, with the two calls below, for a * collection of private files. * * @experimental */ putPrivate?(key: string, buffer: Buffer, options: { mimeType: string; }): Promise; /** * A pre-signed URL a browser sends one private file to, at exactly `key` * (optional). Like `getPresignedUploadUrl`, it binds the type and exact * length; unlike it, the object it writes is private and never cached. * * @experimental */ getPrivateUploadUrl?(key: string, mimeType: string, options: PrivateUploadUrlOptions): Promise; /** * A link to a private file that lasts `options.expiresIn` seconds and is * answered as an attachment that is never cached (optional). Only Nextly's * checked download hands one out, after the caller's access was checked. * * @experimental */ getPrivateDownloadUrl?(key: string, options: PrivateDownloadUrlOptions): Promise; } /** * Vercel Blob storage adapter configuration. * * Extends the base storage plugin config with Vercel Blob-specific options. * Designed for seamless integration with Vercel's serverless platform. * * @example Basic usage * ```typescript * vercelBlobStorage({ * token: process.env.BLOB_READ_WRITE_TOKEN, * collections: { * media: true * } * }) * ``` * * @example With client uploads (recommended for large files) * ```typescript * vercelBlobStorage({ * collections: { * media: { * clientUploads: true // Bypass 4.5MB serverless limit * } * } * }) * ``` * * @example With folder prefix * ```typescript * vercelBlobStorage({ * collections: { * media: { * prefix: 'uploads/', * }, * 'private-docs': { * prefix: 'documents/', * clientUploads: true * } * } * }) * ``` */ interface VercelBlobStorageConfig extends StoragePluginConfig { /** Enable/disable this storage plugin (default: true). */ enabled?: boolean; /** Collections this plugin handles. */ collections: Record; /** * Vercel Blob read/write token. * * If not provided, falls back to `BLOB_READ_WRITE_TOKEN` environment variable. * Get your token from: Vercel Dashboard > Storage > Blob > Tokens * * @example * ```typescript * token: process.env.BLOB_READ_WRITE_TOKEN * ``` */ token?: string; /** * Add a random suffix to uploaded filenames. * Prevents filename collisions when uploading files with the same name. * * When true, `photo.jpg` becomes `photo-abc123.jpg` * * @default true */ addRandomSuffix?: boolean; /** * Cache-Control max-age in seconds. * Controls how long browsers and CDNs cache the files. * * Note: Vercel Blob has a minimum cache time of 1 minute. * * @default 31536000 (1 year) */ cacheControlMaxAge?: number; /** * Access level for uploaded blobs. * Vercel Blob only supports 'public' access. * * @default 'public' */ access?: "public"; /** * Store ID for multi-store setups. * Required if you have multiple blob stores in your Vercel project. * * Get the store ID from: Vercel Dashboard > Storage > Blob > Settings */ storeId?: string; /** * Whether to allow overwriting existing blobs. * When false, uploading a file with the same path will throw an error. * * Note: Only relevant when `addRandomSuffix` is false. * * @default false */ allowOverwrite?: boolean; /** * Multipart upload threshold in bytes. * Files larger than this will be uploaded using multipart upload. * * @default 5242880 (5MB) */ multipartThreshold?: number; } /** * Vercel Blob-specific collection storage configuration. * Extends base collection config with Vercel Blob-specific options. * * @example * ```typescript * vercelBlobStorage({ * collections: { * // Simple enable with defaults * media: true, * * // Full configuration * documents: { * prefix: 'docs/', * addRandomSuffix: false, * allowOverwrite: true, * clientUploads: true * } * } * }) * ``` */ interface VercelBlobCollectionConfig extends CollectionStorageConfig { /** * Override addRandomSuffix for this collection. * If not set, uses the adapter-level setting. */ addRandomSuffix?: boolean; /** * Override allowOverwrite for this collection. * If not set, uses the adapter-level setting. */ allowOverwrite?: boolean; } /** * Type-safe collection storage map for Vercel Blob. * Maps collection slugs to Vercel Blob-specific configurations. */ type VercelBlobCollectionStorageMap = Record; /** * Resolved Vercel Blob configuration after applying defaults. * Used internally by the adapter. * * @internal */ interface ResolvedVercelBlobConfig { token: string; addRandomSuffix: boolean; cacheControlMaxAge: number; access: "public"; storeId?: string; allowOverwrite: boolean; multipartThreshold: number; } /** * Create a Vercel Blob storage plugin for Nextly. * * This factory function creates a StoragePlugin that can be added to * the `storage` array in `nextly.config.ts`. Vercel Blob is optimized * for Vercel deployments with: * * - Global CDN distribution * - Simple token-based authentication * - Client-side upload support (via handleUpload API) * - Automatic file management * * @param config - Vercel Blob storage configuration * @returns A StoragePlugin that MediaStorage can register * * Constructing the plugin never requires the token: a missing credential is * refused when storage is first used, not while the config loads. */ export declare function vercelBlobStorage(config: VercelBlobStorageConfig): StoragePlugin; /** * Vercel Blob Storage Adapter * * Implements the IStorageAdapter interface for Vercel Blob Storage. * Provides file upload, deletion, existence checks, and metadata retrieval. */ export declare class VercelBlobStorageAdapter implements IStorageAdapter { private config; private resolvedConfig; /** * Create a new Vercel Blob storage adapter. * * The token is deliberately NOT checked here. This constructor runs while * the host's config file is evaluated, so a throw would stop every command * — including the schema-only ones that never touch storage. The check * moves to the first storage operation ({@link ensureToken}), which refuses * with the same message a missing token has always produced. * * @param config - Vercel Blob storage configuration */ constructor(config: VercelBlobStorageConfig); /** * Resolve the storage token, refusing at the first use that needs it. * * A token already resolved — from the config at construction, or from the * environment on an earlier call — is returned as is. An unresolved one is * read from the config and then the environment, and a refusal here is the * same one the constructor used to throw: the operator is told which * variable to set, at the moment the credential was actually needed. * * @throws Error if token is not provided */ private ensureToken; /** * Upload file to Vercel Blob. * * Files are stored with globally distributed CDN backing. * By default, a random suffix is added to prevent filename collisions. * * @param buffer - File content as Buffer * @param options - Upload options (filename, mimeType, folder, collection) * @returns Upload result with URL and storage path */ upload(buffer: Buffer, options: UploadOptions): Promise; /** * Write bytes at exactly the blob `filePath` names, beside one already in * the store. * * A stored path here is the blob's full URL, so `filePath` is one too: a * stored blob's URL with a suffix core derived from it, for a file made from * that blob, such as a resized copy of an image. Written under that URL's * pathname with no random suffix, so the blob's URL is the key it was asked * for and the next read finds it; overwriting is allowed, since two requests * may make the same copy at once and write the same bytes. * * A key on any host but this store's is refused before anything is * written, so core keeps no copy of it and serves the original. Writes go * to the token's store whatever host the key names, so a key on another * store's host, as an item moved from another store has, would otherwise * be written where its next read never looks. * * @experimental */ uploadAt(filePath: string, buffer: Buffer, options: { mimeType: string; }): Promise; /** * Delete file from Vercel Blob. * * @param filePath - Full blob URL to delete */ delete(filePath: string): Promise; /** * Delete multiple files from Vercel Blob in chunked batches. * * Processes deletions in chunks of 10 concurrent calls using Promise.allSettled, * collecting successes and failures without short-circuiting. * * @param filePaths - Array of full blob URLs to delete * @returns BulkDeleteResult with successful and failed arrays */ bulkDelete(filePaths: string[]): Promise; /** * Check if file exists in Vercel Blob. * * Uses the head() function which is efficient for existence checks. * * @param filePath - Full blob URL to check * @returns true if file exists, false otherwise */ exists(filePath: string): Promise; /** * Read a stored blob back as bytes, or `null` when it is not there. * * A NETWORK round trip, unlike the local adapter's disk read, because the * bytes live on Vercel's CDN and there is no other way to reach them. That * cost is the reason a caller serving these from its own origin has to cache: * the privacy rule that forces same-origin serving does not also make the * fetch free, and an uncached proxy pays it on every request. * * The URL is taken from `head` rather than assembled from `filePath`, * because a blob's address is issued by the service — it carries a random * suffix this adapter never chose — so deriving one here would be guessing at * a string another system owns. * * `null` for a missing blob rather than a throw, matching {@link exists}. * * @param filePath - Blob path/key * @returns The blob's bytes, or `null` when it does not exist */ read(filePath: string, options?: StorageReadOptions): Promise; /** * Get public URL for Vercel Blob file. * * Vercel Blob paths ARE the public URLs - they're already full HTTPS URLs * with CDN distribution. * * @param filePath - Full blob URL * @returns The same URL (Vercel Blob paths are already public URLs) */ /** * Every blob in the store, by its URL (which is its stored path here), with * when it was uploaded, a page at a time. */ list(): AsyncIterable; getPublicUrl(filePath: string): string; /** * Get storage type identifier. */ getType(): "vercel-blob"; /** * Get adapter info including capabilities. * * @returns Adapter info with type, name, and capability flags */ getInfo(): StorageAdapterInfo; /** * Get file metadata from Vercel Blob. * * Retrieves file information including size, content type, and upload date. * * @param filePath - Full blob URL * @returns File metadata or null if file not found */ getMetadata(filePath: string): Promise; /** * Generate pre-signed URL for client-side uploads. * * Vercel Blob uses a different pattern for client uploads - they require * the handleUpload API which handles token generation server-side. * * This method is not implemented because Vercel Blob's client upload flow * requires server-side route handlers with handleUpload(). * * @see https://vercel.com/docs/storage/vercel-blob/client-upload * @throws Error always - client uploads require handleUpload API */ getPresignedUploadUrl(_key: string, _mimeType: string, _expiresIn?: number): Promise; /** * List blobs with optional prefix filter. * * Useful for browsing or batch operations on stored files. * * @param prefix - Optional prefix to filter results * @param options - List options (limit, cursor) * @returns List of blob metadata */ listBlobs(prefix?: string, options?: { limit?: number; cursor?: string; }): Promise<{ blobs: Array<{ url: string; pathname: string; size: number; uploadedAt: Date; }>; hasMore: boolean; cursor?: string; }>; /** * Build pathname for Vercel Blob upload. * * Creates pathname in format: {folder}/{filename} * If no folder is provided, uses the filename directly. * * @param filename - Original filename (will be sanitized) * @param folder - Optional folder/prefix for organizing uploads * @returns Generated pathname * @throws Error if folder fails sanitization */ private buildPathname; /** * Sanitize filename to prevent path traversal issues. * * @param filename - Original filename * @returns Sanitized filename */ private sanitizeFilename; /** * Reject folder values that would let a caller * escape the configured prefix via path traversal or weird * separators. Vercel Blob is flat-keyed so `/` is just part of the * pathname, but an attacker who controls `folder` could still: * * - Use `..` to chain a relative-traversal-style key. * - Use `\` (Windows separator) to confuse downstream tooling. * - Use control chars / null bytes to truncate the key. * - Use a leading `/` to look like an absolute path. * * Internal `/` segments stay allowed because callers legitimately * use nested folders (`docs/2026/...`); a leading `/`, empty * segments (`docs//x`), or `..` segments are rejected. * * @throws Error with a stable message so the storage facade can * surface a 400 instead of a 500. */ private sanitizeFolder; /** * Get the configured token (masked for logging). Never resolves or * refuses: an adapter whose credentials have not arrived yet masks to * `****`, since this answers for logs, not for storage. */ getTokenMasked(): string; /** * Check if random suffix is enabled. */ hasRandomSuffix(): boolean; /** * Get configured cache control max age. */ getCacheControlMaxAge(): number; } export declare const PACKAGE_NAME = "@nextly/storage-vercel-blob"; export declare const PACKAGE_VERSION = "0.1.0"; export type { ResolvedVercelBlobConfig, VercelBlobCollectionConfig, VercelBlobCollectionStorageMap, VercelBlobStorageConfig }; //# sourceMappingURL=index.d.ts.map