@adonis-agora/media
Version:
Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a
177 lines • 9.44 kB
TypeScript
import type { MediaCollectionRegistry } from './media_collection.js';
import type { UploadSession, UploadSessionListFilter, UploadSessionStore } from './resumable_upload.js';
import type { StorageManager } from './storage_manager.js';
import type { MultipartPart } from './types.js';
/**
* Default part size: 20 MiB. Between S3's 5 MiB minimum and a reasonable payload per browser `PUT`;
* with S3's 10,000-part cap it covers files up to ~195 GiB. Larger than the proxy default (8 MiB)
* on purpose — direct parts don't occupy app memory, so the only cost of a bigger part is a bigger
* retry unit.
*/
export declare const DEFAULT_DIRECT_PART_SIZE: number;
/** S3's minimum part size (every part but the last). Enforced at `initiate` — see {@link UploadPartSizeError}. */
export declare const MIN_DIRECT_PART_SIZE: number;
/** S3's cap on parts per multipart upload. */
export declare const MAX_DIRECT_PARTS = 10000;
/** A part the client should `PUT`: its number and the presigned URL that authorizes exactly that. */
export interface DirectUploadPartUrl {
partNumber: number;
url: string;
}
export interface DirectUploadInitiateInput {
/** Disk name; defaults to the manager's default disk. Must be multipart-capable. */
disk?: string | undefined;
/** Final object key. Resolve it server-side (per user/tenant) — never trust a client-sent key. */
key: string;
/** Content-Type stamped on the final object, and checked against `collection`'s whitelist. */
contentType?: string | undefined;
/** Total file size in bytes. Required: it fixes the part count both sides slice by. */
size: number;
/**
* Collection this upload is destined for. When the manager holds a collection registry, the
* declared `contentType` is checked against that collection's `acceptsMimeTypes` HERE — before
* the multipart upload is opened, before a single byte moves. Mirrors the TUS `POST` gate: fast
* feedback and bandwidth economy, not the security boundary — `attachExisting` re-validates the
* real bytes at attach time.
*/
collection?: string | undefined;
/** Public/private visibility for the final object. */
visibility?: 'public' | 'private' | undefined;
/** Override the manager's part size for this upload. Same S3 bounds apply. */
partSize?: number | undefined;
/** Extra metadata persisted on the session (keys under `direct:` are reserved). */
metadata?: Record<string, string> | undefined;
}
/** What {@link DirectUploadManager.initiate} hands back — everything the client needs to start `PUT`ing. */
export interface DirectUploadCreatedSession {
/** Session id — the handle for `status`/`confirmPart`/`complete`/`abort`. */
id: string;
key: string;
disk: string;
/** The agreed slice size. The client MUST cut the file with exactly this. */
partSize: number;
size: number;
totalParts: number;
/** One presigned URL per part, 1-based, in order. */
parts: DirectUploadPartUrl[];
expiresAt?: Date | undefined;
}
/**
* The resume answer: what is already confirmed (ETags the server holds) and what is still pending
* (with FRESH presigned URLs). A client that lost its state — page reload, new tab, new device —
* asks this and continues from the parts that are missing, re-uploading nothing.
*/
export interface DirectUploadStatus {
id: string;
key: string;
disk: string;
partSize: number;
size: number;
totalParts: number;
contentType?: string | undefined;
/** Parts whose ETags the session holds — already uploaded and confirmed. */
completedParts: MultipartPart[];
/** Parts still missing, each with a freshly presigned URL (expiry never strands an upload). */
pendingParts: DirectUploadPartUrl[];
expiresAt?: Date | undefined;
}
export interface DirectUploadManagerOptions {
storage: StorageManager;
/**
* Session persistence — the SAME SPI (and, with the Lucid driver, the same tables) the resumable
* (TUS) subsystem uses. The store must implement `addPart`/`listParts`; both bundled drivers do.
*/
sessions: UploadSessionStore;
/** Collection registry (`media.collections`) for the `initiate` MIME gate. Omit ⇒ no gate here. */
collections?: MediaCollectionRegistry | undefined;
/** Default part size in bytes. Default 20 MiB ({@link DEFAULT_DIRECT_PART_SIZE}). */
partSize?: number | undefined;
/** Lifetime of presigned part URLs, in seconds. Default 3600. */
presignTtlSeconds?: number | undefined;
/** Session lifetime in seconds. Omit for sessions that never expire. */
sessionTtlSeconds?: number | undefined;
idGenerator?: (() => string) | undefined;
/** Injectable clock (tests drive expiry deterministically). Default `() => new Date()`. */
clock?: (() => Date) | undefined;
/** Emit `upload.*` diagnostics events (default true). */
emitDiagnostics?: boolean | undefined;
}
/**
* Session-backed direct-to-S3 multipart uploads: the browser `PUT`s every byte straight to storage
* through presigned part URLs, and the app only coordinates — open, presign, collect ETags, close.
* The app's bandwidth cost is a handful of JSON round-trips regardless of file size, which is the
* entire point for video-sized files: the TUS path streams every chunk THROUGH the app (2× the
* bytes: client→app, app→S3), where this path streams none.
*
* What this adds over the raw primitives on {@link UploadManager} (`initiateDirect` & friends) is
* the **persisted session**: `uploadId`, the agreed `partSize` and every confirmed part ETag live
* in an {@link UploadSessionStore} — the same SPI the TUS engine persists its offsets in — instead
* of in the client's memory. A page reload no longer orphans the upload: the client asks
* {@link status} and gets back the confirmed ETags plus fresh URLs for what is missing.
*
* Framework-free, like {@link ResumableUploadManager}: the `DirectUploadHandler` maps it onto HTTP
* and the AdonisJS provider mounts that. `MediaManager.completeDirectUploadToLibrary` bridges a
* finished session into the media library through `attachExisting` — where the collection's
* whitelist checks the REAL bytes, exactly like every other upload path.
*/
export declare class DirectUploadManager {
#private;
private readonly storage;
private readonly sessions;
private readonly collections;
private readonly partSize;
private readonly presignTtlSeconds;
private readonly ttlSeconds;
private readonly newId;
private readonly now;
private readonly emitDiagnostics;
constructor(options: DirectUploadManagerOptions);
/**
* Open a direct upload: validate everything that can be validated without bytes, start the native
* multipart upload, persist the session, and presign every part URL in one batch (presigning is
* local computation — see `sigv4.ts` — so a 10,000-part batch costs no S3 round-trips).
*/
initiate(input: DirectUploadInitiateInput): Promise<DirectUploadCreatedSession>;
/**
* Record one part the client finished `PUT`ing (its S3 `ETag` response header). This is what makes
* the session resumable: an ETag the server holds survives any client-side loss of state. Safe to
* retry — confirming the same part again overwrites its ETag.
*/
confirmPart(id: string, part: MultipartPart): Promise<{
offset: number;
completedParts: number;
}>;
/**
* Where the upload stands, framed for resumption: the ETags already confirmed and a FRESH
* presigned URL for every part still missing. After a page reload the client calls this, slices
* the file with the returned `partSize`, uploads only `pendingParts`, and completes.
*/
status(id: string): Promise<DirectUploadStatus>;
/**
* Assemble the parts into the final object and close the session. `parts` supplements what the
* session already holds (a client may hand over ETags it never got to confirm — e.g. it raced
* completion against its last confirms); on overlap the caller's ETag wins. Every part number in
* `1..totalParts` must be accounted for, or this throws {@link UploadPartsIncompleteError} naming
* the gaps — BEFORE the S3 round-trip that would report an opaque `InvalidPart`.
*
* This is the raw primitive (the object exists, no media record). To land in the library, use
* `MediaManager.completeDirectUploadToLibrary`, which chains `attachExisting` — collection
* whitelist against the real bytes included.
*/
complete(id: string, parts?: MultipartPart[]): Promise<{
key: string;
disk: string;
size: number;
}>;
/**
* Discard an in-flight upload: abort the native multipart upload (S3 frees the stored parts and
* stops charging for them) and drop the session. The S3 abort is best-effort — a bucket lifecycle
* rule may have already reaped the upload (`NoSuchUpload`), and a session that can no longer be
* aborted remotely must still be deletable locally.
*/
abort(id: string): Promise<void>;
/** In-progress direct sessions, optionally filtered. Empty when the store cannot enumerate. */
list(filter?: UploadSessionListFilter): Promise<UploadSession[]>;
private emit;
}
//# sourceMappingURL=direct_upload.d.ts.map