@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
275 lines • 11.2 kB
JavaScript
import { MediaControlPlaneError, MediaNotFoundError, MediaTenantUnsupportedError, } from '../errors.js';
import { deliverRecord, imageOfRecord } from '../internal_symbols.js';
import { MediaLibrary, } from '../media_library.js';
import { fromWireRecord, IMAGE_URL_TOKEN } from './protocol.js';
import { nodeStreamOf } from './tenant_client.js';
const enc = encodeURIComponent;
function isNotFound(error) {
return error instanceof MediaControlPlaneError && error.status === 404;
}
/** `30`, `'30'`, `'30s'`, `'5m'`, `'2h'`, `'1d'` → seconds. */
export function seconds(value) {
if (typeof value === 'number')
return value;
const match = /^(\d+)\s*(s|m|h|d)?$/i.exec(value.trim());
if (!match)
throw new TypeError(`media: "${value}" is not a duration (30, '30s', '5m', '1h', '1d')`);
const unit = { s: 1, m: 60, h: 3600, d: 86400 }[(match[2] ?? 's').toLowerCase()];
return Number(match[1]) * unit;
}
/**
* The records of a tenant, read from the control plane. Only the reads the library makes go
* through it; every write is a call of its own on {@link TenantMediaLibrary}.
*/
export class RemoteMediaStore {
client;
constructor(client) {
this.client = client;
}
async find(id) {
try {
const body = await this.client.json(`/records/${enc(id)}`);
return fromWireRecord(body.data);
}
catch (error) {
if (isNotFound(error))
return null;
throw error;
}
}
async listByOwner(ownerType, ownerId, collection) {
const body = await this.client.json(`/owners/${enc(ownerType)}/${enc(ownerId)}/records`, { query: { collection } });
return body.data.map(fromWireRecord);
}
async list(options = {}) {
const body = await this.client.json('/records', {
query: {
collection: options.collection,
ownerType: options.ownerType,
ownerId: options.ownerId,
cursor: options.cursor,
limit: options.limit,
},
});
return { items: body.data.map(fromWireRecord), nextCursor: body.nextCursor };
}
save() {
return Promise.reject(new MediaTenantUnsupportedError('Writing a record to the store'));
}
delete() {
return Promise.reject(new MediaTenantUnsupportedError('Deleting from the store'));
}
nextOrder() {
return Promise.reject(new MediaTenantUnsupportedError('nextOrder'));
}
}
/**
* `media.library` on a tenant: the same API, run on the control plane. Records, files and
* conversions live there; this app keeps its collection `access` rules, its delivery route and its
* signing secret.
*/
export class TenantMediaLibrary extends MediaLibrary {
#client;
#urls;
constructor(options, tenant) {
super(options);
this.#client = tenant.client;
this.#urls = tenant.urls ?? 'app';
}
/** Upload the file to the control plane, which stores it and runs the collection's conversions. */
async attach(input) {
const meta = {
ownerType: input.ownerType,
ownerId: String(input.ownerId),
collection: input.collection,
fileName: input.fileName,
mimeType: input.mimeType,
...(input.name !== undefined ? { name: input.name } : {}),
...(input.id !== undefined ? { id: input.id } : {}),
...(input.customProperties !== undefined ? { customProperties: input.customProperties } : {}),
};
const contents = input.contents;
const size = Buffer.isBuffer(contents) ? contents.byteLength : input.size;
const body = await this.#client.json('/records', {
method: 'POST',
upload: true,
headers: {
'content-type': 'application/octet-stream',
'x-media-attach': Buffer.from(JSON.stringify(meta), 'utf8').toString('base64url'),
...(size !== undefined ? { 'x-media-size': String(size) } : {}),
},
body: Buffer.isBuffer(contents) ? new Uint8Array(contents) : contents,
});
return fromWireRecord(body.data);
}
attachExisting(_input) {
return Promise.reject(new MediaTenantUnsupportedError('attachExisting (an object already on a disk)'));
}
async rename(id, name) {
try {
const body = await this.#client.json(`/records/${enc(id)}`, {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name }),
});
return fromWireRecord(body.data);
}
catch (error) {
if (isNotFound(error))
throw new MediaNotFoundError(id);
throw error;
}
}
async delete(id) {
await this.#client.request(`/records/${enc(id)}`, { method: 'DELETE' }).then((response) => response.body?.cancel(), (error) => {
if (!isNotFound(error))
throw error;
});
}
async ensureConversion(id, conversionName) {
try {
const body = await this.#client.json(`/records/${enc(id)}/conversions/${enc(conversionName)}`, { method: 'POST' });
return fromWireRecord(body.data);
}
catch (error) {
if (isNotFound(error))
throw new MediaNotFoundError(`${id}#${conversionName}`);
throw error;
}
}
/**
* The URL of a file: this app's delivery route (`urls: 'app'`, signed when `delivery.signing` is
* set), or the control plane's storage URL (`urls: 'control-plane'`).
*/
async url(id, conversion) {
if (this.#urls === 'app')
return this.deliveryUrl(id, conversion ? { conversion } : {});
return this.#remoteUrl(id, conversion);
}
/** A time-limited storage URL, signed by the control plane (not by proxy). */
async signedUrl(id, expiresIn, options = {}) {
return this.#remoteUrl(id, options.conversion, seconds(expiresIn));
}
async #remoteUrl(id, conversion, expiresIn) {
try {
const body = await this.#client.json(`/records/${enc(id)}/url`, {
query: { conversion, expiresIn },
});
return body.url;
}
catch (error) {
if (isNotFound(error))
throw new MediaNotFoundError(conversion ? `${id}#${conversion}` : id);
throw error;
}
}
async deliver(id, options = {}) {
return this.#deliver(id, options);
}
/** @internal */
async [deliverRecord](record, options = {}) {
return this.#deliver(record.id, options);
}
async #deliver(id, options) {
const resize = options.width !== undefined && options.width !== '';
if (this.#urls === 'control-plane' && options.mode !== 'proxy' && !resize) {
try {
return { kind: 'redirect', url: await this.#remoteUrl(id, options.conversion) };
}
catch (error) {
// A control plane that delivers by proxy only: read the bytes instead.
if (!(error instanceof MediaControlPlaneError && error.status === 409))
throw error;
}
}
let response;
try {
response = await this.#client.request(`/records/${enc(id)}/file`, {
query: {
conversion: options.conversion,
...(resize ? { w: String(options.width), q: options.quality } : {}),
},
...(options.accept ? { headers: { accept: options.accept } } : {}),
});
}
catch (error) {
if (isNotFound(error)) {
throw new MediaNotFoundError(options.conversion ? `${id}#${options.conversion}` : id);
}
throw error;
}
const length = Number(response.headers.get('content-length'));
const fileName = response.headers.get('x-media-file-name');
const vary = response.headers.get('vary');
return {
kind: 'stream',
stream: nodeStreamOf(response),
mimeType: response.headers.get('content-type') ?? 'application/octet-stream',
...(Number.isFinite(length) && length > 0 ? { size: length } : {}),
...(fileName ? { fileName: decodeURIComponent(fileName) } : {}),
...(vary === 'Accept' ? { vary: 'Accept' } : {}),
};
}
/**
* The responsive-image props, computed by the control plane from its collection presets; each
* URL is this app's (`urls: 'app'`) or the control plane's.
* @internal
*/
async [imageOfRecord](record, options = {}) {
if (options.onDemand)
return super[imageOfRecord](record, options);
let image;
try {
const body = await this.#client.json(`/records/${enc(record.id)}/image`, {
query: {
conversions: options.conversions?.join(','),
generate: options.generate ? '1' : undefined,
},
});
image = body.data;
}
catch (error) {
if (isNotFound(error))
throw new MediaNotFoundError(record.id);
throw error;
}
const urls = new Map();
const urlOf = (conversion) => {
let url = urls.get(conversion);
if (!url) {
const name = conversion === '' ? undefined : conversion;
url = Promise.resolve(options.url
? options.url(name)
: options.expiresIn !== undefined
? this.signedUrl(record.id, options.expiresIn, name ? { conversion: name } : {})
: this.url(record.id, name));
urls.set(conversion, url);
}
return url;
};
const swap = async (value) => value.startsWith(IMAGE_URL_TOKEN) ? urlOf(value.slice(IMAGE_URL_TOKEN.length)) : value;
const src = await swap(image.src);
let srcSet;
if (image.srcSet) {
const parts = await Promise.all(image.srcSet.split(', ').map(async (candidate) => {
const space = candidate.lastIndexOf(' ');
return `${await swap(candidate.slice(0, space))}${candidate.slice(space)}`;
}));
srcSet = parts.join(', ');
}
return { ...image, src, ...(srcSet !== undefined ? { srcSet } : {}) };
}
transform(_id, transformerName) {
return Promise.reject(new MediaTenantUnsupportedError(`transform("${transformerName}") (the control plane runs it)`));
}
setFocalPoint(_id, _point) {
return Promise.reject(new MediaTenantUnsupportedError('setFocalPoint'));
}
stream() {
return Promise.reject(new MediaTenantUnsupportedError('stream (HLS/DASH packages)'));
}
streamFile() {
return Promise.reject(new MediaTenantUnsupportedError('streamFile (HLS/DASH packages)'));
}
}
//# sourceMappingURL=tenant_library.js.map