// SPDX-License-Identifier: AGPL-3.0-or-later import type { DocwellClient } from "@docwell/api-client"; import type { FileHost } from "@docwell/editor"; import { useApi } from "../api"; import { useRuntimeConfig } from "../platform"; // One file token for the whole app, renewed before it runs out. Documents // keep the API path of a file; the editor asks resolve() for a loadable URL. let token = ""; let expires = 0; let pending: Promise | null = null; const filePath = /^\/api\/v1\/files\/[A-Za-z0-9_-]+$/; function ensureToken(api: DocwellClient): Promise { // Renew when less than ten minutes are left, so links drawn now keep working a while. if (token && expires - Date.now() > 10 * 60_000) return Promise.resolve(); pending ??= api.files .token() .then((t) => { token = t.token; expires = Date.parse(t.expires); }) .finally(() => (pending = null)); return pending; } /** Forgets the token (on sign-out). */ export function clearFileToken() { token = ""; expires = 0; } /** * The editor's view of attachments for one page: uploads go to pageId. * Await ready before drawing a document, so its images get a token. */ export function useFileHost(pageId: () => string): { host: FileHost; ready: () => Promise } { const api = useApi(); const config = useRuntimeConfig(); const host: FileHost = { resolve(src) { if (!filePath.test(src)) return src; void ensureToken(api); return `${config.apiUrl}${src}?token=${encodeURIComponent(token)}`; }, async upload(file) { const a = await api.pages.upload(pageId(), file, file.name || "file"); return { url: a.url, name: a.name, mime: a.mime, size: a.size }; }, }; return { host, ready: () => ensureToken(api) }; }