import { get, writable } from "svelte/store"; import { invoke, isTauri } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api"; import { ExternalSession, deadline } from "./externalSession"; import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView, PluginDocumentContext, PluginDocumentType } from "./sdk"; export const installedPlugins = writable({ root: "", plugins: [] }); export const externalErrors = writable>({}); export const pluginTools = writable<{ owner: string; id: string; title: string; kind: "command" | "view" }[]>([]); export interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor"; document?: PluginDocumentContext; icon?: "kanban" | "file" } export const pluginView = writable(null); export const pluginEditors = writable([]); export const pluginDocumentTypes = writable<{ owner: string; type: PluginDocumentType }[]>([]); export const pluginDocuments = writable>({}); export const pluginNavigation = writable<{ owner: string; id: string; title: string; icon?: PluginView["icon"] }[]>([]); export const pluginEditorActive = writable(false); export const pluginServiceError = writable(""); export const restartPlugins = writable([]); const sessions = new Map(); const failures = new Map(); const errors: Record = {}; const restarted = new Set(); let queue: Promise = Promise.resolve(); let started = false; let generation = 0; let documentOpenVersion = 0; export function cancelPluginDocumentOpen() { documentOpenVersion++; } const workspaceListeners = new Set<() => void>(); let renameDocument: ((path: string, name: string) => Promise) | undefined; export function handlePluginDocumentRename(handler: (path: string, name: string) => Promise): () => void { renameDocument = handler; return () => { if (renameDocument === handler) renameDocument = undefined; }; } let canWrite: (path: string) => void = () => {}; export function guardPluginWrites(guard: (path: string) => void): () => void { canWrite = guard; return () => { if (canWrite === guard) canWrite = () => {}; }; } export function notifyPluginWorkspace() { for (const listener of workspaceListeners) listener(); } export function selectPluginEditor(view: OpenPluginView) { cancelPluginDocumentOpen(); pluginView.set(view); pluginEditorActive.set(true); } export function closePluginEditor(key: string) { cancelPluginDocumentOpen(); const remaining = get(pluginEditors).filter(view => view.key !== key); pluginEditors.set(remaining); if (get(pluginView)?.key === key) { pluginView.set(remaining.at(-1) ?? null); pluginEditorActive.set(remaining.length > 0); } } export function renamePluginDocuments(from: string, to: string) { const editors = get(pluginEditors).map(view => { const path = view.document?.path; if (!path || (path !== from && !path.startsWith(from + "/"))) return view; view.document!.path = to + path.slice(from.length); return { ...view, title: documentTitle(view.document!.path) }; }); pluginEditors.set(editors); const selected = editors.find(view => view.key === get(pluginView)?.key); if (selected) pluginView.set(selected); pluginDocuments.set({}); notifyPluginWorkspace(); } export function removePluginDocuments(path: string) { for (const view of get(pluginEditors)) if (view.document && (view.document.path === path || view.document.path.startsWith(path + "/"))) closePluginEditor(view.key); pluginDocuments.set({}); notifyPluginWorkspace(); } const documentTitle = (path: string) => path.split("/").at(-1)!.replace(/\.[^.]+$/, ""); async function identifyDocument(path: string) { const types = get(pluginDocumentTypes).filter(({ type }) => type.extensions.includes(path.split(".").at(-1)!.toLowerCase())); if (!types.length) return null; let source: string | undefined; for (const { owner, type } of types) { if (!sessions.has(owner)) continue; try { if (type.content !== "binary" && source === undefined) source = await workspaceRead(path); const result = type.identify(path, type.content === "binary" ? "" : source!); if (result && typeof result.id === "string" && result.id.trim()) return { owner, type, document: { id: result.id, path } }; } catch { /* Invalid documents remain available in the text editor. */ } } return null; } export async function inspectPluginDocuments(entries: { rel_path: string; kind: string }[]) { const updates: Record = {}; await Promise.all(entries.filter(entry => entry.kind === "file").map(async entry => { try { const match = await identifyDocument(entry.rel_path); updates[entry.rel_path] = match ? { icon: match.type.icon ?? "file", title: match.type.title } : null; } catch { updates[entry.rel_path] = null; } })); pluginDocuments.update(current => { const next = { ...current }; for (const [path, value] of Object.entries(updates)) { if (value) next[path] = value; else delete next[path]; } return next; }); } export async function openPluginDocument(path: string, current: () => boolean = () => true): Promise { const request = ++documentOpenVersion; const match = await identifyDocument(path); if (request !== documentOpenVersion || !current()) return true; if (!match) return false; const { owner, type, document } = match; const existing = get(pluginEditors).find(view => view.owner === owner && view.id === type.id && view.document?.path === path && view.document.id === document.id); if (existing) { selectPluginEditor(existing); return true; } const view: OpenPluginView = { key: crypto.randomUUID(), owner, id: type.id, title: documentTitle(path), placement: "editor", document, icon: type.icon }; pluginEditors.update(views => [...views, view]); selectPluginEditor(view); return true; } export async function createPluginDocument(owner: string, id: string, path: string) { const session = sessions.get(owner)?.session; const create = session?.documentTypes.get(id)?.create; if (!create || session!.controller.signal.aborted) throw new Error("This document type is unavailable."); const contents = create.contents(); if (typeof contents !== "string") throw new Error("Document contents must be text."); await invoke("workspace_create", { rel: path, kind: "file", contents }); notifyPluginWorkspace(); } function publish() { pluginNavigation.set([...sessions].flatMap(([owner, { session }]) => [...session.views.values()].filter(view => view.navigation).map(view => ({ owner, id: view.id, title: view.title, icon: view.icon })))); pluginDocumentTypes.set([...sessions].flatMap(([owner, { session }]) => [...session.documentTypes.values()].map(type => ({ owner, type })))); pluginTools.set([...sessions].flatMap(([owner, { session }]) => [ ...[...session.commands.values()].map(({ id, title }) => ({ owner, id, title, kind: "command" as const })), ...[...session.views.values()].map(({ id, title }) => ({ owner, id, title, kind: "view" as const })), ])); externalErrors.set({ ...errors }); } function report(id: string, reason: unknown) { errors[id] = String(reason); publish(); } async function release(id: string, error?: string) { await invoke("plugins_release", { id, error: error ?? null }); } async function stop(id: string) { const loaded = sessions.get(id); if (!loaded) return; sessions.delete(id); for (const view of get(pluginEditors)) if (view.owner === id) closePluginEditor(view.key); pluginDocuments.set({}); pluginView.update(view => view?.owner === id ? null : view); restarted.add(id); restartPlugins.set([...restarted]); let error: string | undefined; try { await loaded.session.stop(); } catch (reason) { error = String(reason); report(id, reason); } await release(id, error); publish(); } function show(owner: string, id: string) { const view = sessions.get(owner)?.session.views.get(id); if (view) { const placement = view.placement ?? "dialog"; if (placement === "editor") { const existing = get(pluginEditors).find(item => item.owner === owner && item.id === id && !item.document); const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement }; if (!existing) pluginEditors.update(views => [...views, editor]); selectPluginEditor(editor); return; } const current = get(pluginView); if (current?.owner !== owner || current.id !== id) { pluginView.set({ key: crypto.randomUUID(), owner, id, title: view.title, placement }); } pluginEditorActive.set(false); } } async function activate(row: InstalledPlugin) { const id = row.manifest.id; let leased = false; const session = new ExternalSession(id, { workspace: { list: path => workspaceList(path ?? ""), read: workspaceRead, readBytes: workspaceReadBytes, write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); }, subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; }, readOptional: rel => invoke("workspace_read", { rel, missingOk: true }), create: async (rel, contents) => { await invoke("workspace_create", { rel, kind: "file", contents }); notifyPluginWorkspace(); }, }, settings: { read: async () => JSON.parse(await invoke("plugins_data", { id, value: null })), write: async value => { const json = JSON.stringify(value); if (json === undefined) throw new Error("Plugin settings must be JSON data."); await invoke("plugins_data", { id, value: json }); }, }, assets: { read: async path => Uint8Array.from(atob(await invoke("plugins_asset", { id, path })), char => char.charCodeAt(0)) }, }, publish, view => show(id, view), undefined, async path => { if (!await openPluginDocument(path)) throw new Error("No enabled plugin recognizes this document."); }, async (document, name) => { const match = await identifyDocument(document.path); if (session.controller.signal.aborted) throw new Error("This plugin is disabled."); if (!match || match.owner !== id || match.document.id !== document.id) throw new Error("The document changed. Refresh before renaming it."); if (!renameDocument) throw new Error("Document renaming is unavailable."); canWrite(document.path); return renameDocument(document.path, name); }); try { const code = await invoke("plugins_load", { id, hash: row.hash }); leased = true; const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" })); let module: PluginModule; try { module = await deadline(import(/* @vite-ignore */ url)); } catch (reason) { await release(id, String(reason)); leased = false; throw reason; } finally { URL.revokeObjectURL(url); } sessions.set(id, { hash: row.hash, session }); await session.start(module); delete errors[id]; publish(); } catch (reason) { failures.set(id, row.hash); report(id, reason); let cleanupError: string | undefined; try { await session.stop(); } catch (error) { cleanupError = String(error); } sessions.delete(id); if (leased) await release(id, cleanupError); publish(); } } export function refreshPlugins(): Promise { if (!isTauri()) return Promise.resolve(); const version = generation; const job = async () => { try { const snapshot = await invoke("plugins_snapshot"); if (!snapshot || version !== generation) return; installedPlugins.set(snapshot); pluginServiceError.set(""); for (const id of sessions.keys()) { const row = snapshot.plugins.find(row => row.manifest.id === id); if (!row?.enabled || row.hash !== sessions.get(id)?.hash) await stop(id); } for (const row of snapshot.plugins) { const id = row.manifest.id; if (!row.enabled) { failures.delete(id); continue; } if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row); } } catch (reason) { pluginServiceError.set(String(reason)); } }; queue = queue.then(job, job); return queue; } export async function setPluginEnabled(id: string, enabled: boolean, hash?: string) { await invoke("plugins_set_enabled", { id, enabled, hash: hash ?? null }); await refreshPlugins(); } export async function runPluginCommand(owner: string, id: string) { try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; } } export function openPluginView(owner: string, id: string) { show(owner, id); } export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext): Promise { const session = sessions.get(owner)?.session; if (!session) throw new Error("The plugin is disabled."); return session.mount(id, element, document); } export function startExternalPlugins(): () => void { if (!isTauri() || started) return () => {}; started = true; let disposed = false; let off: (() => void) | undefined; void listen("plugins-changed", () => { void refreshPlugins(); }).then(unlisten => { if (disposed) unlisten(); else off = unlisten; }).catch(reason => pluginServiceError.set(String(reason))); void refreshPlugins(); const focus = () => { void refreshPlugins(); }; window.addEventListener("focus", focus); // Also detects changes made in a file manager while this window stays open. const timer = setInterval(focus, 5000); return () => { disposed = true; started = false; generation++; off?.(); clearInterval(timer); window.removeEventListener("focus", focus); for (const id of [...sessions.keys()]) void stop(id).catch(reason => report(id, reason)); }; }