UNPKG

@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

262 lines • 14.3 kB
import type { Readable } from 'node:stream'; import type { MediaRecord } from '../media_record.js'; import type { MediaCollectionTotals, MediaListOptions, MediaListPage } from '../media_store.js'; import type { UploadSession } from '../resumable_upload.js'; import type { Disk, MultipartPart } from '../types.js'; import type { ObjectInsightProvider } from './object_insights.js'; import type { ObjectUrlConfig } from './object_urls.js'; import type { CollectionFilter, CollectionListResponse, CollectionsSummaryResponse, CursorParams, DiskListResponse, MediaDetailResponse, MediaEntry, ObjectDetailResponse, ObjectInsightsResponse, ObjectListResponse, Topology, UploadDetailResponse, UploadListResponse } from './types.js'; /** TTL of the signed URLs handed to the browser for object preview/download. */ export declare const URL_TTL_SECONDS = 300; /** Cap on the get→put streaming path used for cross-disk copy/move (drivers can't copy across disks). */ export declare const MAX_TRANSFER_BYTES: number; /** Page size for the flat sweep that recursive folder delete/copy/move paginates over. */ export declare const FOLDER_SWEEP_LIMIT = 1000; /** Page size for the client-side scan behind {@link DashboardService.collectionsSummary}. */ export declare const COLLECTIONS_SUMMARY_PAGE_SIZE = 200; /** Hard cap on records scanned by {@link DashboardService.collectionsSummary} — beyond this the * rollup is partial rather than unbounded. */ export declare const COLLECTIONS_SUMMARY_SCAN_LIMIT = 5000; /** Ceiling for a console (direct) upload — buffered in memory, so bounded to protect the process * heap. Larger files belong on the resumable (TUS) upload path, not this convenience upload. */ export declare const MAX_UPLOAD_BYTES: number; /** The slice of `MediaManager` the dashboard depends on — kept structural so it's trivial to fake in tests. */ export interface MediaManagerLike { readonly storage: { readonly defaultDisk: string; disk(name?: string): Disk; }; readonly hasResumable: boolean; readonly resumable: { list(filter?: { disk?: string; keyPrefix?: string; tenantIds?: ReadonlyArray<string | null>; }): Promise<UploadSession[]>; /** Discard an in-flight session (native multipart + buffered parts), then drop its record. */ abort(id: string): Promise<void>; /** All recorded parts for a session (multipart-capable disks); empty for a buffered session. */ listParts(id: string): Promise<MultipartPart[]>; }; /** The persistence SPI — the console reads stored records via the cross-owner `list`, and a single * record (+ delete) for the record-detail drill-in. */ readonly store: { list(options?: MediaListOptions): Promise<MediaListPage>; find(id: string): Promise<MediaRecord | null>; delete(id: string): Promise<void>; collectionTotals?(): Promise<MediaCollectionTotals[]>; }; } export interface DashboardServiceOptions { /** Disk names the console may browse/act on. The first entry (or the manager default) is the default. */ diskNames: string[]; /** Whether mutating actions (copy/move/delete) are permitted. */ actions: boolean; /** * How to build the `url` reported for an object's bytes — see {@link ObjectUrlConfig}. Omit (or * `undefined`) for `auto`: a signed URL straight to the store, which is what this service always * did before the option existed. */ objectUrls?: ObjectUrlConfig; /** * With tenancy on, the storage prefixes a confined viewer may touch on the disks (`t/<tenant>/` * per organization in scope). Keys outside them read as missing. Omit for no confinement. */ keyPrefixes?: string[]; } /** An error carrying an HTTP status for the provider to surface verbatim. */ export declare class DashboardError extends Error { readonly status: number; constructor(message: string, status: number); } /** Shown by the console when the Lucid upload-session store's tables do not exist yet. */ export declare const UPLOAD_SESSIONS_TABLE_MISSING = "upload sessions table missing \u2014 run the media migration (node ace migration:run)"; /** * Whether `error` is the database saying a table does not exist: Postgres `42P01`, MySQL/MariaDB * `ER_NO_SUCH_TABLE` (1146), SQLite `no such table`, SQL Server 208 (`Invalid object name`). */ export declare function isMissingTableError(error: unknown): boolean; /** * All dashboard read/action logic, expressed over a structural {@link MediaManagerLike}. It reads the * *real* `@adonis-agora/media` surface — disk `list`/`stat`/`getSignedUrl`/`copy`/`move`/`deleteMany` * and the resumable `UploadSessionStore.list()` — and never invents its own persistence. The provider * is a thin HTTP shell around this; the logic is pure and unit-tested without booting AdonisJS. */ export declare class DashboardService { private readonly manager; private readonly options; /** Host-registered {@link ObjectInsightProvider}s, from `config/media_dashboard.ts`'s `objectInsights`. */ private readonly insightProviders; constructor(manager: MediaManagerLike, options: DashboardServiceOptions, /** Host-registered {@link ObjectInsightProvider}s, from `config/media_dashboard.ts`'s `objectInsights`. */ insightProviders?: ObjectInsightProvider[]); /** Coarse capability topology for the SPA to enable/disable affordances. */ topology(): Topology; /** Enumerate the exposed disks with their capabilities (non-extended disks report `list:false`). */ disks(): DiskListResponse; /** * List one page of a bucket under `prefix` (folders rolled up on the `/` delimiter), paginated * through the ecosystem's cursor interface ({@link CursorParams} → the `CursorPageInfo` envelope): * `after` is the previous page's `nextCursor`, `first` its size. * * `after`/`first` map onto the driver's own `cursor`/`limit` — S3's `ListObjectsV2` continuation * token — which is why the response's `prevCursor`/`hasPrev` are pinned to `null`/`false`: there is * no backwards token to hand out. */ objects(diskName: string, params?: CursorParams & { prefix?: string; }): Promise<ObjectListResponse>; /** * The URL to report for an object's bytes, under the host's {@link ObjectUrlStrategy}. `auto` * signs a short-lived URL straight to the store; `proxy` routes through this server, for a host * whose browser cannot reach the store at all. */ private objectUrl; /** Object metadata + a URL for preview/download (signed, or this console's proxy — see `objectUrls`). */ object(diskName: string, key: string): Promise<ObjectDetailResponse>; /** {@link object} without the URL: size, content type and last modified only. */ objectMeta(diskName: string, key: string): Promise<Omit<ObjectDetailResponse, 'url'>>; /** * The object's raw byte stream plus the metadata the provider needs to serve it inline. Backs the * console's same-origin preview proxy so text/PDF render in the browser instead of downloading * (and so a CORS-locked bucket is still previewable). */ objectStream(diskName: string, key: string): Promise<{ stream: Readable; contentType: string; size: number; }>; /** * What the HOST knows about this object, from every registered `objectInsights` provider (see * `config/media_dashboard.ts`). `{ insights: [] }` when none are registered. A provider that * throws is skipped and logged — annotation must never be able to stop an admin opening a file, and * providers run concurrently so one host lookup being slow doesn't serialize the others. */ objectInsights(diskName: string, key: string): Promise<ObjectInsightsResponse>; /** In-progress resumable uploads, projected from the session store (empty when unconfigured). */ uploads(filter?: { disk?: string; prefix?: string; }): Promise<UploadListResponse>; /** Full detail (+ recorded parts) of one resumable upload session. */ uploadDetail(id: string): Promise<UploadDetailResponse>; /** * Cancels a resumable session: discards its native multipart upload (or buffered parts) and drops * its record, so it stops appearing as in-progress. Actions-gated. */ abortUpload(id: string): Promise<void>; /** * One cursor-paginated page of stored media-library records across owners/collections, projected to * the SPA's {@link MediaEntry}. Delegates to the real {@link MediaStore.list} — no bespoke query. * * Paginated through the ecosystem's cursor interface ({@link CursorParams} → `CursorPage`): * `after`/`first` map onto the store's `cursor`/`limit` keyset page, which — like the disk listing — * only walks forward, hence the pinned `prevCursor: null` / `hasPrev: false`. */ collections(params?: CollectionFilter & CursorParams): Promise<CollectionListResponse>; /** * Per-collection rollup (record count + total bytes) for the console's collection chips. One * aggregate query when the store implements {@link MediaStore.collectionTotals} (both bundled * stores do). A store without it is walked through `list()` in batches and summed client-side — * bounded at {@link COLLECTIONS_SUMMARY_SCAN_LIMIT} records so a very large library degrades to a * partial (still useful) summary instead of an unbounded scan. */ collectionsSummary(): Promise<CollectionsSummaryResponse>; /** * Full detail of one stored `MediaRecord`, plus a URL per generated conversion (signed, or this * console's proxy — same `objectUrls` strategy as {@link object}). Only conversions carrying a * concrete `{disk, path}` artifact get a link — a metadata-only conversion (probe results with no * output file) has nothing to preview. */ mediaRecord(id: string): Promise<MediaDetailResponse>; /** One stored `MediaRecord` as the console lists it, without signing any URL. */ mediaEntry(id: string): Promise<MediaEntry>; /** Deletes a stored `MediaRecord`. Actions-gated (does not touch its underlying disk object). */ deleteMediaRecord(id: string): Promise<void>; /** Server-side copy (same disk) or streamed cross-disk copy. Original is kept. */ copy(body: { disk: string; from: string; to: string; toDisk?: string; }): Promise<void>; /** Server-side move (same disk) or streamed cross-disk move. Source is deleted after transfer. */ move(body: { disk: string; from: string; to: string; toDisk?: string; }): Promise<void>; /** Batched delete of many keys on one disk. */ remove(body: { disk: string; keys: string[]; }): Promise<void>; /** * Writes an object from a byte stream (a browser upload) — the console's convenience upload, * distinct from the resumable TUS path. The caller supplies the full key (prefix + filename). * Bounded at {@link MAX_UPLOAD_BYTES} so a runaway upload can't exhaust the process heap. Actions-gated. */ putObject(diskName: string, key: string, body: AsyncIterable<Uint8Array>, contentType?: string): Promise<void>; /** * Create a "folder" — a zero-byte marker object at `<prefix>/`, which S3-style delimiter listing * surfaces as a navigable folder. Normalizes to exactly one trailing slash (so the key never * double-slashes); rejects an empty prefix. Actions-gated. */ createFolder(body: { disk: string; prefix: string; }): Promise<void>; /** * Recursively delete a "folder": every object under `<prefix>/` (nested included) plus the * zero-byte marker itself. Sweeps with an EMPTY delimiter so the driver lists keys FLAT — the * default `/` delimiter would roll nested keys up into folder prefixes and the sweep would miss * them, deleting only direct children. Paginates until the disk reports no more, then deletes the * marker explicitly (its key equals the sweep prefix, which `list` filters out). Actions-gated. */ deleteFolder(body: { disk: string; prefix: string; }): Promise<void>; /** Copy a whole "folder" (every object under `<from>/`, nested included) to `<to>/`, same or cross disk. */ copyFolder(body: { disk: string; from: string; to: string; toDisk?: string; }): Promise<void>; /** Move a whole "folder" (every object under `<from>/`, nested included) to `<to>/`, same or cross disk. */ moveFolder(body: { disk: string; from: string; to: string; toDisk?: string; }): Promise<void>; private transfer; /** * Relocate a single object, same disk or across disks. Same-disk uses the driver's native * `copy`/`move` (server-side, no bytes through the app). Cross-disk has no driver primitive, so the * object is streamed through the app (get→put, capped at {@link MAX_TRANSFER_BYTES}); a `move` then * deletes the source. Callers gate actions. */ private transferKey; /** * Shared engine for {@link copyFolder}/{@link moveFolder}. Same flat-listing sweep as * {@link deleteFolder}; each key is relocated via {@link transferKey} (so cross-disk works * transparently), preserving its path relative to the source. On the SAME disk, rejects a * destination inside the source (which would recurse forever); across disks that can't happen. The * destination folder marker is written, and for a move the source marker removed, so both listings * stay consistent. Actions-gated. */ private transferFolder; private extended; /** A key outside the viewer's tenant prefixes reads as missing (tenancy, confined viewer). */ private assertKey; /** * For a confined viewer, a listing ABOVE their tenant prefixes (the root, `t/`) shows just the * folders that lead to them; `undefined` when the prefix needs a real listing. */ private syntheticFolders; private assertActions; } //# sourceMappingURL=service.d.ts.map