uploadthing
Version:
Learn more: [docs.uploadthing.com](https://docs.uploadthing.com)
284 lines (276 loc) • 10.4 kB
TypeScript
import * as __internal_types from '../internal/types.js';
export { UTFiles } from '../internal/types.js';
import * as _uploadthing_shared from '@uploadthing/shared';
import { Json, UploadThingError, FetchEsque, MaybeUrl, ContentDisposition, ACL, Either, SerializedUploadThingError, Time } from '@uploadthing/shared';
export { UploadThingError } from '@uploadthing/shared';
import { UploadedFileData, FileRouter, RouteHandlerOptions } from '../types/index.js';
export { FileRouter } from '../types/index.js';
import { Blob as Blob$1 } from 'buffer';
import * as Config from 'effect/Config';
import * as LogLevel from 'effect/LogLevel';
type CreateBuilderOptions<TErrorShape extends Json> = {
errorFormatter: (err: UploadThingError) => TErrorShape;
};
declare const LogFormat: Config.Config<"json" | "logFmt" | "structured" | "pretty">;
type LogFormat = Config.Config.Success<typeof LogFormat>;
interface UTApiOptions {
/**
* Provide a custom fetch function.
* @default globalThis.fetch
*/
fetch?: FetchEsque;
/**
* Provide a custom UploadThing token
* @default process.env.UPLOADTHING_TOKEN
*/
token?: string;
/**
* @default "info"
*/
logLevel?: LogLevel.Literal;
/**
* What format log entries should be in
* @default "pretty" in development, else "json"
* @see https://effect.website/docs/guides/observability/logging#built-in-loggers
*/
logFormat?: Config.Config.Success<typeof LogFormat>;
/**
* Set the default key type for file operations. Allows you to set your preferred filter
* for file keys or custom identifiers without needing to specify it on every call.
* @default "fileKey"
*/
defaultKeyType?: "fileKey" | "customId";
/**
* URL override for the API server
*/
apiUrl?: string;
/**
* URL override for the ingest server
*/
ingestUrl?: string;
}
type UrlWithOverrides = {
url: MaybeUrl;
name?: string;
customId?: string;
};
type BlobEsque = Blob$1 | Blob;
type FileEsque = BlobEsque & {
name: string;
lastModified?: number;
customId?: string | null | undefined;
};
interface UploadFilesOptions {
contentDisposition?: ContentDisposition;
acl?: ACL;
/**
* AbortSignal that can be used to cancel the upload
*/
signal?: AbortSignal;
}
type UploadFileResult = Either<UploadedFileData, SerializedUploadThingError>;
interface KeyTypeOptionsBase {
/**
* Whether the provided key is a fileKey or a custom identifier. fileKey is the
* identifier you get from UploadThing after uploading a file, customId is a
* custom identifier you provided when uploading a file.
* @default fileKey
*/
keyType?: "fileKey" | "customId";
}
interface DeleteFilesOptions extends KeyTypeOptionsBase {
}
interface GetFileUrlsOptions extends KeyTypeOptionsBase {
}
interface ListFilesOptions {
limit?: number;
offset?: number;
}
type KeyRename = {
fileKey: string;
newName: string;
};
type CustomIdRename = {
customId: string;
newName: string;
};
type RenameFileUpdate = KeyRename | CustomIdRename;
interface GetSignedURLOptions extends KeyTypeOptionsBase {
/**
* How long the URL will be valid for.
* - Must be positive and less than 7 days (604800 seconds).
* - You must accept overrides on the UploadThing dashboard for this option to be accepted.
* @default app default on UploadThing dashboard
*/
expiresIn?: Time;
}
interface ACLUpdateOptions extends KeyTypeOptionsBase {
}
interface UTFilePropertyBag extends BlobPropertyBag {
lastModified?: number | undefined;
customId?: string | undefined;
}
/**
* Extension of the Blob class that simplifies setting the `name` and `customId` properties,
* similar to the built-in File class from Node > 20.
*/
declare class UTFile extends Blob {
name: string;
lastModified: number;
customId: string | undefined;
constructor(parts: BlobPart[], name: string, options?: UTFilePropertyBag);
}
declare class UTApi {
private opts?;
private fetch;
private defaultKeyType;
private runtime;
constructor(opts?: UTApiOptions | undefined);
private requestUploadThing;
private executeAsync;
/**
* Upload files to UploadThing storage.
*
* @example
* await uploadFiles(new File(["foo"], "foo.txt"));
*
* @example
* await uploadFiles([
* new File(["foo"], "foo.txt"),
* new File(["bar"], "bar.txt"),
* ]);
*/
uploadFiles(files: FileEsque, opts?: UploadFilesOptions): Promise<UploadFileResult>;
uploadFiles(files: FileEsque[], opts?: UploadFilesOptions): Promise<UploadFileResult[]>;
/**
* @param {string} url The URL of the file to upload
* @param {Json} metadata JSON-parseable metadata to attach to the uploaded file(s)
*
* @example
* await uploadFileFromUrl("https://uploadthing.com/f/2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg");
*
* @example
* await uploadFileFromUrl([
* "https://uploadthing.com/f/2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg",
* "https://uploadthing.com/f/1649353b-04ea-48a2-9db7-31de7f562c8d_image2.jpg"
* ])
*/
uploadFilesFromUrl(urls: MaybeUrl | UrlWithOverrides, opts?: UploadFilesOptions): Promise<UploadFileResult>;
uploadFilesFromUrl(urls: (MaybeUrl | UrlWithOverrides)[], opts?: UploadFilesOptions): Promise<UploadFileResult[]>;
/**
* Request to delete files from UploadThing storage.
* @param {string | string[]} fileKeys
*
* @example
* await deleteFiles("2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg");
*
* @example
* await deleteFiles(["2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg","1649353b-04ea-48a2-9db7-31de7f562c8d_image2.jpg"])
*
* @example
* await deleteFiles("myCustomIdentifier", { keyType: "customId" })
*/
deleteFiles: (keys: string[] | string, opts?: DeleteFilesOptions) => Promise<{
readonly success: boolean;
readonly deletedCount: number;
}>;
/**
* Request file URLs from UploadThing storage.
* @param {string | string[]} fileKeys
*
* @example
* const data = await getFileUrls("2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg");
* console.log(data); // [{key: "2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg", url: "https://uploadthing.com/f/2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg"}]
*
* @example
* const data = await getFileUrls(["2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg","1649353b-04ea-48a2-9db7-31de7f562c8d_image2.jpg"])
* console.log(data) // [{key: "2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg", url: "https://uploadthing.com/f/2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg" },{key: "1649353b-04ea-48a2-9db7-31de7f562c8d_image2.jpg", url: "https://uploadthing.com/f/1649353b-04ea-48a2-9db7-31de7f562c8d_image2.jpg"}]
*
* @deprecated - See https://docs.uploadthing.com/working-with-files#accessing-files for info how to access files
*/
getFileUrls: (keys: string[] | string, opts?: GetFileUrlsOptions) => Promise<{
readonly data: readonly {
readonly key: string;
readonly url: string;
}[];
}>;
/**
* Request file list from UploadThing storage.
* @param {object} opts
* @param {number} opts.limit The maximum number of files to return
* @param {number} opts.offset The number of files to skip
*
* @example
* const data = await listFiles({ limit: 1 });
* console.log(data); // { key: "2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg", id: "2e0fdb64-9957-4262-8e45-f372ba903ac8" }
*/
listFiles: (opts?: ListFilesOptions) => Promise<{
readonly files: readonly {
readonly name: string;
readonly size: number;
readonly customId: string | null;
readonly key: string;
readonly status: "Deletion Pending" | "Failed" | "Uploaded" | "Uploading";
readonly id: string;
readonly uploadedAt: number;
}[];
readonly hasMore: boolean;
}>;
renameFiles: (updates: RenameFileUpdate | RenameFileUpdate[]) => Promise<{
readonly success: boolean;
}>;
getUsageInfo: () => Promise<{
readonly totalBytes: number;
readonly appTotalBytes: number;
readonly filesUploaded: number;
readonly limitBytes: number;
}>;
/** Request a presigned url for a private file(s) */
getSignedURL: (key: string, opts?: GetSignedURLOptions) => Promise<{
readonly url: string;
}>;
/**
* Update the ACL of a file or set of files.
*
* @example
* // Make a single file public
* await utapi.updateACL("2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg", "public-read");
*
* // Make multiple files private
* await utapi.updateACL(
* [
* "2e0fdb64-9957-4262-8e45-f372ba903ac8_image.jpg",
* "1649353b-04ea-48a2-9db7-31de7f562c8d_image2.jpg",
* ],
* "private",
* );
*/
updateACL: (keys: string | string[], acl: ACL, opts?: ACLUpdateOptions) => Promise<{
readonly success: boolean;
}>;
}
type AdapterArgs = {
req: Request;
res: undefined;
event: undefined;
};
declare const createUploadthing: <TErrorShape extends Json>(opts?: CreateBuilderOptions<TErrorShape>) => <TRouteOptions extends _uploadthing_shared.RouteOptions>(input: _uploadthing_shared.FileRouterInputConfig, config?: TRouteOptions | undefined) => __internal_types.UploadBuilder<{
_routeOptions: TRouteOptions;
_input: {
in: __internal_types.UnsetMarker;
out: __internal_types.UnsetMarker;
};
_metadata: __internal_types.UnsetMarker;
_adapterFnArgs: AdapterArgs;
_errorShape: TErrorShape;
_errorFn: __internal_types.UnsetMarker;
_output: __internal_types.UnsetMarker;
}>;
declare const createRouteHandler: <TRouter extends FileRouter>(opts: RouteHandlerOptions<TRouter>) => (args_0: Request | {
request: Request;
}) => Promise<Response>;
declare const extractRouterConfig: (router: FileRouter) => {
slug: string;
config: _uploadthing_shared.ExpandedRouteConfig;
}[];
export { UTApi, UTFile, createRouteHandler, createUploadthing, extractRouterConfig };