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

218 lines • 9.04 kB
/* * The console switcher registry, version 1, declared here STRUCTURALLY: every `@adonis-agora` * console declares the same shapes and binds the same plain value at `'agora.consoles'` when it is * the first to boot. No lib imports another; whichever copy creates the registry, the others append * to it. */ /** The container binding the registry lives at. */ export const AGORA_CONSOLES_BINDING = 'agora.consoles'; const ID = /^[a-z][a-z0-9-]*$/; const ICONS = new Set([ 'workflow', 'telescope', 'media', 'payments', 'agent', 'identity', 'generic', ]); /** How long another console's `authorize` (or `search`) may take before it is left out. */ export const PROBE_TIMEOUT_MS = 300; /** Hits per console in a global search. */ export const SEARCH_HITS_PER_CONSOLE = 5; /** Whether `path` is a same-origin absolute path (`/x`, never `//host` or a URL). */ export function isSameOriginPath(path) { return typeof path === 'string' && path.startsWith('/') && !path.startsWith('//'); } /** * Add a console to the app's switcher registry, creating the registry when this is the first * console to boot. Consoles call it from their provider's `boot()`; an app can call it too, for a * console it mounts itself. A registry of another version is left alone; a duplicate id is skipped * with a warning. Returns whether the entry was added. */ export async function registerAgoraConsole(container, entry, logger) { if (!ID.test(entry.id)) { throw new Error(`[@adonis-agora/media] console id ${JSON.stringify(entry.id)} is invalid`); } if (!isSameOriginPath(entry.path)) { throw new Error(`[@adonis-agora/media] console path ${JSON.stringify(entry.path)} must start with a single "/"`); } if (typeof container.hasBinding !== 'function') return false; if (!container.hasBinding(AGORA_CONSOLES_BINDING)) { const fresh = { version: 1, entries: [] }; container.bindValue(AGORA_CONSOLES_BINDING, fresh); } const registry = (await container.make(AGORA_CONSOLES_BINDING)); if (registry?.version !== 1 || !Array.isArray(registry.entries)) return false; if (registry.entries.some((existing) => existing.id === entry.id)) { logger?.warn(`[@adonis-agora/media] console id "${entry.id}" already registered`); return false; } registry.entries.push(entry); return true; } /** The registry, when one is bound with a version this copy reads. */ export async function readAgoraConsoles(container) { if (typeof container.hasBinding !== 'function') return undefined; if (!container.hasBinding(AGORA_CONSOLES_BINDING)) return undefined; const registry = (await container.make(AGORA_CONSOLES_BINDING)); if (registry?.version !== 1 || !Array.isArray(registry.entries)) return undefined; return registry; } /** How many consoles other than `selfId` are registered (no `authorize` runs). */ export function otherConsoles(registry, selfId) { return registry ? registry.entries.filter((entry) => entry.id !== selfId).length : 0; } /** `work`, or `fallback` when it rejects or takes longer than `ms`. */ async function within(work, ms, fallback) { let timer; const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(fallback), ms); }); try { return await Promise.race([ Promise.resolve() .then(work) .catch(() => fallback), timeout, ]); } finally { if (timer !== undefined) clearTimeout(timer); } } /** * Run `fn` with the probe marker on `ctx`: an `authorize` that writes an audit trail can read * `ctx.agoraProbe === true` and skip it, since the switcher only asks, it does not open anything. */ async function probing(ctx, fn) { const marked = ctx; const previous = marked.agoraProbe; marked.agoraProbe = true; try { return await fn(); } finally { if (previous === undefined) delete marked.agoraProbe; else marked.agoraProbe = previous; } } function sorted(entries) { return [...entries].sort((a, b) => a.order - b.order || a.id.localeCompare(b.id)); } async function allowedEntries(entries, ctx, timeoutMs) { const verdicts = await probing(ctx, () => Promise.all(entries.map((entry) => within(async () => (await entry.authorize(ctx)).allowed === true, timeoutMs, false)))); return entries.filter((_, index) => verdicts[index]); } function iconOf(icon) { return ICONS.has(icon) ? icon : 'generic'; } /** * The consoles other than `selfId` the viewer may open: every other entry's `authorize` runs in * parallel, each given {@link PROBE_TIMEOUT_MS}; a timeout, a rejection or any denial hides it. No * reason is ever returned. */ export async function listVisibleConsoles(registry, selfId, ctx, timeoutMs = PROBE_TIMEOUT_MS) { const others = registry ? sorted(registry.entries.filter((entry) => entry.id !== selfId && isSameOriginPath(entry.path))) : []; const allowed = await allowedEntries(others, ctx, timeoutMs); return { version: 1, current: selfId, consoles: allowed.map((entry) => ({ id: entry.id, title: entry.title, ...(entry.package !== undefined ? { package: entry.package } : {}), icon: iconOf(entry.icon), href: entry.path, })), }; } /** * Global search: `q` goes to every console the viewer may open that has a `search` (this one * included, the viewer is already in it), in parallel, {@link PROBE_TIMEOUT_MS} each, at most * {@link SEARCH_HITS_PER_CONSOLE} same-origin hits per console. Consoles with no hit are left out. */ export async function searchConsoles(registry, selfId, ctx, q, timeoutMs = PROBE_TIMEOUT_MS) { const query = q.trim().slice(0, 200); if (!registry || query === '') return { version: 1, q: query, results: [] }; const searchable = sorted(registry.entries.filter((entry) => typeof entry.search === 'function' && isSameOriginPath(entry.path))); const self = searchable.filter((entry) => entry.id === selfId); const others = await allowedEntries(searchable.filter((entry) => entry.id !== selfId), ctx, timeoutMs); const targets = sorted([...self, ...others]); const hits = await probing(ctx, () => Promise.all(targets.map((entry) => within(async () => (await entry.search?.(ctx, query, SEARCH_HITS_PER_CONSOLE)) ?? [], timeoutMs, [])))); const results = []; targets.forEach((entry, index) => { const safe = (hits[index] ?? []) .filter((hit) => typeof hit === 'object' && hit !== null && typeof hit.title === 'string' && isSameOriginPath(hit.href)) .slice(0, SEARCH_HITS_PER_CONSOLE) .map((hit) => ({ title: hit.title, ...(typeof hit.subtitle === 'string' ? { subtitle: hit.subtitle } : {}), href: hit.href, })); if (safe.length > 0) { results.push({ id: entry.id, title: entry.title, icon: iconOf(entry.icon), hits: safe }); } }); return { version: 1, q: query, results }; } /** * The media console's global search: an exact media record id opens the record, and collection and * disk names that contain `q` open the collection's records or the disk's library. `base` is the * console's mount path. */ export function mediaConsoleSearch(source, base) { const shell = base === '/' ? '/' : base; return async (ctx, q, limit) => { const reader = await source(ctx); const hits = []; const needle = q.toLowerCase(); const record = await reader.find(q).catch(() => null); if (record) { hits.push({ title: record.fileName, subtitle: `media · ${record.collection} · ${record.id}`, href: `${shell}#/collections/${encodeURIComponent(record.id)}`, }); } const collections = await reader.collections().catch(() => []); for (const row of collections) { if (hits.length >= limit) break; if (!row.key.toLowerCase().includes(needle)) continue; hits.push({ title: row.key, subtitle: `collection · ${row.count} ${row.count === 1 ? 'file' : 'files'}`, href: `${shell}#/collections?collection=${encodeURIComponent(row.key)}`, }); } for (const disk of reader.disks()) { if (hits.length >= limit) break; if (!disk.toLowerCase().includes(needle)) continue; hits.push({ title: disk, subtitle: 'disk', href: `${shell}#/browse/${encodeURIComponent(disk)}`, }); } return hits.slice(0, limit); }; } //# sourceMappingURL=console_switcher.js.map