@vercel/blob
Version:
The Vercel Blob JavaScript API client
410 lines (407 loc) • 21.6 kB
text/typescript
import { B as BlobAccessType, W as WithUploadProgress, a as BlobCommandOptions, P as PutBlobResult, b as Part, C as CommonCompleteMultipartUploadOptions, c as PutBody, d as CommonMultipartUploadOptions } from './create-folder-D-Qslm5_.cjs';
export { e as createFolder } from './create-folder-D-Qslm5_.cjs';
import { IncomingMessage } from 'node:http';
import 'stream';
import 'undici';
/**
* Interface for put, upload and multipart upload operations.
* This type omits all options that are encoded in the client token.
*/
interface ClientCommonCreateBlobOptions {
/**
* Whether the blob should be publicly accessible.
* - 'public': The blob will be publicly accessible via its URL.
* - 'private': The blob will require authentication to access.
*/
access: BlobAccessType;
/**
* Defines the content type of the blob. By default, this value is inferred from the pathname.
* Sent as the 'content-type' header when downloading a blob.
*/
contentType?: string;
/**
* `AbortSignal` to cancel the running request. See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
*/
abortSignal?: AbortSignal;
}
/**
* Shared interface for put and multipart operations that use client tokens.
*/
interface ClientTokenOptions {
/**
* A client token that was generated by your server using the `generateClientToken` method.
*/
token: string;
}
/**
* Shared interface for put and upload operations.
* @internal This is an internal interface not intended for direct use by consumers.
*/
interface ClientCommonPutOptions extends ClientCommonCreateBlobOptions, WithUploadProgress {
/**
* Whether to use multipart upload. Use this when uploading large files.
* It will split the file into multiple parts, upload them in parallel and retry failed parts.
*/
multipart?: boolean;
}
/**
* Options for the client-side put operation.
*/
type ClientPutCommandOptions = ClientCommonPutOptions & ClientTokenOptions;
/**
* Uploads a file to the blob store using a client token.
*
* @param pathname - The pathname to upload the blob to, including the extension. This will influence the URL of your blob.
* @param body - The content of your blob. Can be a string, File, Blob, Buffer or ReadableStream.
* @param options - Configuration options including:
* - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.
* - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.
* - contentType - (Optional) The media type for the blob. By default, it's derived from the pathname.
* - multipart - (Optional) Whether to use multipart upload for large files. It will split the file into multiple parts, upload them in parallel and retry failed parts.
* - abortSignal - (Optional) AbortSignal to cancel the operation.
* - onUploadProgress - (Optional) Callback to track upload progress: onUploadProgress(\{loaded: number, total: number, percentage: number\})
* @returns A promise that resolves to the blob information, including pathname, contentType, contentDisposition, url, and downloadUrl.
*/
declare const put: (pathname: string, body: PutBody, optionsInput: ClientPutCommandOptions) => Promise<PutBlobResult>;
/**
* Options for creating a multipart upload from the client side.
*/
type ClientCreateMultipartUploadCommandOptions = ClientCommonCreateBlobOptions & ClientTokenOptions;
/**
* Creates a multipart upload. This is the first step in the manual multipart upload process.
*
* @param pathname - A string specifying the path inside the blob store. This will be the base value of the return URL and includes the filename and extension.
* @param options - Configuration options including:
* - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.
* - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.
* - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension.
* - abortSignal - (Optional) AbortSignal to cancel the operation.
* @returns A promise that resolves to an object containing:
* - key: A string that identifies the blob object.
* - uploadId: A string that identifies the multipart upload. Both are needed for subsequent uploadPart calls.
*/
declare const createMultipartUpload: (pathname: string, optionsInput: ClientCreateMultipartUploadCommandOptions) => Promise<{
key: string;
uploadId: string;
}>;
/**
* Creates a multipart uploader that simplifies the multipart upload process.
* This is a wrapper around the manual multipart upload process that provides a more convenient API.
*
* @param pathname - A string specifying the path inside the blob store. This will be the base value of the return URL and includes the filename and extension.
* @param options - Configuration options including:
* - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.
* - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.
* - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension.
* - abortSignal - (Optional) AbortSignal to cancel the operation.
* @returns A promise that resolves to an uploader object with the following properties and methods:
* - key: A string that identifies the blob object.
* - uploadId: A string that identifies the multipart upload.
* - uploadPart: A method to upload a part of the file.
* - complete: A method to complete the multipart upload process.
*/
declare const createMultipartUploader: (pathname: string, optionsInput: ClientCreateMultipartUploadCommandOptions) => Promise<{
key: string;
uploadId: string;
uploadPart(partNumber: number, body: PutBody): Promise<{
etag: string;
partNumber: number;
}>;
complete(parts: Part[]): Promise<PutBlobResult>;
}>;
/**
* @internal Internal type for multipart upload options.
*/
type ClientMultipartUploadCommandOptions = ClientCommonCreateBlobOptions & ClientTokenOptions & CommonMultipartUploadOptions & WithUploadProgress;
/**
* Uploads a part of a multipart upload.
* Used as part of the manual multipart upload process.
*
* @param pathname - Same value as the pathname parameter passed to createMultipartUpload. This will influence the final URL of your blob.
* @param body - A blob object as ReadableStream, String, ArrayBuffer or Blob based on these supported body types. Each part must be a minimum of 5MB, except the last one which can be smaller.
* @param options - Configuration options including:
* - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.
* - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.
* - uploadId - (Required) A string returned from createMultipartUpload which identifies the multipart upload.
* - key - (Required) A string returned from createMultipartUpload which identifies the blob object.
* - partNumber - (Required) A number identifying which part is uploaded (1-based index).
* - contentType - (Optional) The media type for the blob. By default, it's derived from the pathname.
* - abortSignal - (Optional) AbortSignal to cancel the running request.
* - onUploadProgress - (Optional) Callback to track upload progress: onUploadProgress(\{loaded: number, total: number, percentage: number\})
* @returns A promise that resolves to the uploaded part information containing etag and partNumber, which will be needed for the completeMultipartUpload call.
*/
declare const uploadPart: (pathname: string, body: PutBody, optionsInput: ClientMultipartUploadCommandOptions) => Promise<Part>;
/**
* @internal Internal type for completing multipart uploads.
*/
type ClientCompleteMultipartUploadCommandOptions = ClientCommonCreateBlobOptions & ClientTokenOptions & CommonCompleteMultipartUploadOptions;
/**
* Completes a multipart upload by combining all uploaded parts.
* This is the final step in the manual multipart upload process.
*
* @param pathname - Same value as the pathname parameter passed to createMultipartUpload.
* @param parts - An array containing all the uploaded parts information from previous uploadPart calls. Each part must have properties etag and partNumber.
* @param options - Configuration options including:
* - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.
* - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.
* - uploadId - (Required) A string returned from createMultipartUpload which identifies the multipart upload.
* - key - (Required) A string returned from createMultipartUpload which identifies the blob object.
* - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension.
* - abortSignal - (Optional) AbortSignal to cancel the operation.
* @returns A promise that resolves to the finalized blob information, including pathname, contentType, contentDisposition, url, and downloadUrl.
*/
declare const completeMultipartUpload: (pathname: string, parts: Part[], optionsInput: ClientCompleteMultipartUploadCommandOptions) => Promise<PutBlobResult>;
/**
* Options for client-side upload operations.
*/
interface CommonUploadOptions {
/**
* A route that implements the `handleUpload` function for generating a client token.
*/
handleUploadUrl: string;
/**
* Additional data which will be sent to your `handleUpload` route.
*/
clientPayload?: string;
/**
* Additional headers to be sent when making the request to your `handleUpload` route.
* This is useful for sending authorization headers or any other custom headers.
*/
headers?: Record<string, string>;
}
/**
* Options for the upload method, which handles client-side uploads.
*/
type UploadOptions = ClientCommonPutOptions & CommonUploadOptions;
/**
* Uploads a blob into your store from the client.
* Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#client-uploads
*
* If you want to upload from your server instead, check out the documentation for the put operation: https://vercel.com/docs/vercel-blob/using-blob-sdk#upload-a-blob
*
* Unlike the put method, this method does not require a client token as it will fetch one from your server.
*
* @param pathname - The pathname to upload the blob to. This includes the filename and extension.
* @param body - The contents of your blob. This has to be a supported fetch body type (string, Blob, File, ArrayBuffer, etc).
* @param options - Configuration options including:
* - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.
* - handleUploadUrl - (Required) A string specifying the route to call for generating client tokens for client uploads.
* - clientPayload - (Optional) A string to be sent to your handleUpload server code. Example use-case: attaching the post id an image relates to.
* - headers - (Optional) An object containing custom headers to be sent with the request to your handleUpload route. Example use-case: sending Authorization headers.
* - contentType - (Optional) A string indicating the media type. By default, it's extracted from the pathname's extension.
* - multipart - (Optional) Whether to use multipart upload for large files. It will split the file into multiple parts, upload them in parallel and retry failed parts.
* - abortSignal - (Optional) AbortSignal to cancel the operation.
* - onUploadProgress - (Optional) Callback to track upload progress: onUploadProgress(\{loaded: number, total: number, percentage: number\})
* @returns A promise that resolves to the blob information, including pathname, contentType, contentDisposition, url, and downloadUrl.
*/
declare const upload: (pathname: string, body: PutBody, optionsInput: UploadOptions) => Promise<PutBlobResult>;
/**
* Decoded payload from a client token.
*/
type DecodedClientTokenPayload = Omit<GenerateClientTokenOptions, 'token'> & {
/**
* Timestamp in milliseconds when the token will expire.
*/
validUntil: number;
};
/**
* Extracts and decodes the payload from a client token.
*
* @param clientToken - The client token string to decode
* @returns The decoded payload containing token options
*/
declare function getPayloadFromClientToken(clientToken: string): DecodedClientTokenPayload;
/**
* @internal Event type constants for internal use.
*/
declare const EventTypes: {
readonly generateClientToken: "blob.generate-client-token";
readonly uploadCompleted: "blob.upload-completed";
};
/**
* Event for generating a client token for blob uploads.
* @internal This is an internal interface used by the SDK.
*/
interface GenerateClientTokenEvent {
/**
* Type identifier for the generate client token event.
*/
type: (typeof EventTypes)['generateClientToken'];
/**
* Payload containing information needed to generate a client token.
*/
payload: {
/**
* The destination path for the blob.
*/
pathname: string;
/**
* Whether the upload will use multipart uploading.
*/
multipart: boolean;
/**
* Additional data from the client which will be available in onBeforeGenerateToken.
*/
clientPayload: string | null;
};
}
/**
* Event that occurs when a client upload has completed.
* @internal This is an internal interface used by the SDK.
*/
interface UploadCompletedEvent {
/**
* Type identifier for the upload completed event.
*/
type: (typeof EventTypes)['uploadCompleted'];
/**
* Payload containing information about the uploaded blob.
*/
payload: {
/**
* Details about the blob that was uploaded.
*/
blob: PutBlobResult;
/**
* Optional payload that was defined during token generation.
*/
tokenPayload?: string | null;
};
}
/**
* Union type representing either a request to generate a client token or a notification that an upload completed.
*/
type HandleUploadBody = GenerateClientTokenEvent | UploadCompletedEvent;
/**
* Type representing either a Node.js IncomingMessage or a web standard Request object.
* @internal This is an internal type used by the SDK.
*/
type RequestType = IncomingMessage | Request;
/**
* Options for the handleUpload function.
*/
interface HandleUploadOptions {
/**
* The request body containing upload information.
*/
body: HandleUploadBody;
/**
* Function called before generating the client token for uploads.
*
* @param pathname - The destination path for the blob
* @param clientPayload - A string payload specified on the client when calling upload()
* @param multipart - A boolean specifying whether the file is a multipart upload
*
* @returns An object with configuration options for the client token including the optional callbackUrl
*/
onBeforeGenerateToken: (pathname: string, clientPayload: string | null, multipart: boolean) => Promise<Pick<GenerateClientTokenOptions, 'allowedContentTypes' | 'maximumSizeInBytes' | 'validUntil' | 'addRandomSuffix' | 'allowOverwrite' | 'cacheControlMaxAge' | 'ifMatch'> & {
tokenPayload?: string | null;
callbackUrl?: string;
}>;
/**
* Function called by Vercel Blob when the client upload finishes.
* This is useful to update your database with the blob URL that was uploaded.
*
* @param body - Contains information about the completed upload including the blob details
*/
onUploadCompleted?: (body: UploadCompletedEvent['payload']) => Promise<void>;
/**
* A string specifying the read-write token to use when making requests.
* It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.
*/
token?: string;
/**
* An IncomingMessage or Request object to be used to determine the action to take.
*/
request: RequestType;
}
/**
* A server-side route helper to manage client uploads. It has two responsibilities:
* 1. Generate tokens for client uploads
* 2. Listen for completed client uploads, so you can update your database with the URL of the uploaded file
*
* @param options - Configuration options for handling uploads
* - request - (Required) An IncomingMessage or Request object to be used to determine the action to take.
* - body - (Required) The request body containing upload information.
* - onBeforeGenerateToken - (Required) Function called before generating the client token for uploads.
* - onUploadCompleted - (Optional) Function called by Vercel Blob when the client upload finishes.
* - token - (Optional) A string specifying the read-write token to use when making requests. Defaults to process.env.BLOB_READ_WRITE_TOKEN.
* @returns A promise that resolves to either a client token generation result or an upload completion result
*/
declare function handleUpload({ token, request, body, onBeforeGenerateToken, onUploadCompleted, }: HandleUploadOptions): Promise<{
type: 'blob.generate-client-token';
clientToken: string;
} | {
type: 'blob.upload-completed';
response: 'ok';
}>;
/**
* Generates a client token from a read-write token. This function must be called from a server environment.
* The client token contains permissions and constraints that limit what the client can do.
*
* @param options - Options for generating the client token
* - pathname - (Required) The destination path for the blob.
* - token - (Optional) A string specifying the read-write token to use. Defaults to process.env.BLOB_READ_WRITE_TOKEN.
* - onUploadCompleted - (Optional) Configuration for upload completion callback.
* - maximumSizeInBytes - (Optional) A number specifying the maximum size in bytes that can be uploaded (max 5TB).
* - allowedContentTypes - (Optional) An array of media types that are allowed to be uploaded. Wildcards are supported (text/*).
* - validUntil - (Optional) A timestamp in ms when the token will expire. Defaults to one hour from generation.
* - addRandomSuffix - (Optional) Whether to add a random suffix to the filename. Defaults to false.
* - allowOverwrite - (Optional) Whether to allow overwriting existing blobs. Defaults to false.
* - cacheControlMaxAge - (Optional) Number of seconds to configure cache duration. Defaults to one month.
* - ifMatch - (Optional) Only write if the ETag matches (optimistic concurrency control).
* @returns A promise that resolves to the generated client token string which can be used in client-side upload operations.
*/
declare function generateClientTokenFromReadWriteToken({ token, ...argsWithoutToken }: GenerateClientTokenOptions): Promise<string>;
/**
* Options for generating a client token.
*/
interface GenerateClientTokenOptions extends BlobCommandOptions {
/**
* The destination path for the blob
*/
pathname: string;
/**
* Configuration for upload completion callback
*/
onUploadCompleted?: {
callbackUrl: string;
tokenPayload?: string | null;
};
/**
* A number specifying the maximum size in bytes that can be uploaded. The maximum is 5TB.
*/
maximumSizeInBytes?: number;
/**
* An array of strings specifying the media type that are allowed to be uploaded.
* By default, it's all content types. Wildcards are supported (text/*)
*/
allowedContentTypes?: string[];
/**
* A number specifying the timestamp in ms when the token will expire.
* By default, it's now + 1 hour.
*/
validUntil?: number;
/**
* Adds a random suffix to the filename.
* @defaultvalue false
*/
addRandomSuffix?: boolean;
/**
* Allow overwriting an existing blob. By default this is set to false and will throw an error if the blob already exists.
* @defaultvalue false
*/
allowOverwrite?: boolean;
/**
* Number in seconds to configure how long Blobs are cached. Defaults to one month. Cannot be set to a value lower than 1 minute.
* @defaultvalue 30 * 24 * 60 * 60 (1 Month)
*/
cacheControlMaxAge?: number;
/**
* Only write if the ETag matches (optimistic concurrency control).
* Use this for conditional writes to prevent overwriting changes made by others.
* If the ETag doesn't match, a `BlobPreconditionFailedError` will be thrown.
*/
ifMatch?: string;
}
export { type ClientCommonCreateBlobOptions, type ClientCreateMultipartUploadCommandOptions, type ClientPutCommandOptions, type ClientTokenOptions, type CommonUploadOptions, type DecodedClientTokenPayload, type GenerateClientTokenOptions, type HandleUploadBody, type HandleUploadOptions, type UploadOptions, completeMultipartUpload, createMultipartUpload, createMultipartUploader, generateClientTokenFromReadWriteToken, getPayloadFromClientToken, handleUpload, put, upload, uploadPart };