- Add the native feature runtime in src/lib/features/: the catalog, the switches, the first-start migration, the loader, and the feature sessions. - Add Settings → Features and the features settings section. - Add features_legacy. It reads the old plugin packages and changes nothing. - Move Git from the plugin into src/lib/features/git/, on host internals. - Remove api.git, the git contribution key, and the SDK Git types. - Add pnpm check:features. It fails when a feature module loads at start. - Update the tests, the menu inventory, the docs, and UI-055.
311 lines
22 KiB
TypeScript
311 lines
22 KiB
TypeScript
import { pluginHost, type ContributionRegistry } from "./registry.ts";
|
|
import { completionHub } from "../completion/hub.ts";
|
|
import { registerCompletionInput } from "../completion/input.ts";
|
|
import { showActionMenu } from "../ui/managedActionMenu.ts";
|
|
import { backgroundHub } from "./backgrounds.ts";
|
|
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts";
|
|
import type { BackgroundFiles } from "./backgroundContracts.ts";
|
|
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext, PtyApi, PtyOpenOptions, PtySession, PtyTransport } from "./sdk.ts";
|
|
|
|
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
|
|
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
|
|
openFile?: PluginApi["openFile"]; backgrounds?: BackgroundFiles;
|
|
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
|
|
pty?: PtyTransport; files?: FilesTransport; serviceHub?: ServiceHub;
|
|
};
|
|
|
|
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
|
|
let timer: ReturnType<typeof setTimeout>;
|
|
return Promise.race([work, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("Plugin cleanup or activation timed out. Restart RuneStone.")), milliseconds); })]).finally(() => clearTimeout(timer));
|
|
}
|
|
|
|
/** Revokes host access before cleanup, including when activation is still pending. */
|
|
export class ExternalSession {
|
|
readonly controller = new AbortController();
|
|
readonly commands = new Map<string, PluginCommand>();
|
|
readonly views = new Map<string, PluginView>();
|
|
readonly documentTypes = new Map<string, PluginDocumentType>();
|
|
private cleanups: Dispose[] = [];
|
|
private stopped = false;
|
|
private activation: Promise<void> = Promise.resolve();
|
|
private stopping?: Promise<void>;
|
|
private lateCleanup?: Promise<void>;
|
|
private mounted = new Set<Dispose>();
|
|
private contributions: Dispose[] = [];
|
|
private registry: ContributionRegistry;
|
|
private backgroundOwner = Symbol('plugin backgrounds');
|
|
private backgroundSubscriptions = new Set<() => void>();
|
|
private serviceOwner = Symbol('plugin services');
|
|
private serviceSubscriptions = new Set<() => void>();
|
|
private ptySessions = new Map<string, () => Promise<void>>();
|
|
readonly id: string;
|
|
private services: SessionServices;
|
|
private changed: () => void;
|
|
private show: PluginApi["openView"];
|
|
private close?: PluginApi["closeView"];
|
|
private replace?: PluginApi["replaceView"];
|
|
private replaceDocument?: PluginApi["replaceDocumentWithView"];
|
|
private receiveTab?: (data: string) => void | Promise<void>;
|
|
private openDocument: (path: string) => Promise<void>;
|
|
private renameDocument?: PluginApi["renameDocument"];
|
|
constructor(id: string, services: SessionServices, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
|
|
this.openDocument = openDocument;
|
|
this.renameDocument = renameDocument;
|
|
this.close = close;
|
|
this.replace = replace;
|
|
this.replaceDocument = replaceDocument;
|
|
this.registry = registry; this.id = id; this.services = services; this.changed = changed; this.show = show;
|
|
}
|
|
private check() { if (this.stopped) throw new Error("This plugin is disabled."); }
|
|
async start(module: PluginModule) {
|
|
const register = <T extends { id: string; title: string }>(map: Map<string, T>, item: T) => {
|
|
this.check();
|
|
if (!/^[a-z][a-z0-9.-]*$/.test(item.id) || !item.title?.trim() || map.has(item.id)) throw new Error("Invalid or duplicate plugin contribution.");
|
|
map.set(item.id, item); this.changed();
|
|
};
|
|
const api: PluginApi = {
|
|
id: this.id, signal: this.controller.signal,
|
|
...(this.services.pty ? { pty: this.ptyApi(this.services.pty) } : {}),
|
|
...(this.services.files ? { files: this.filesApi(this.services.files) } : {}),
|
|
services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub),
|
|
...(this.services.backgrounds ? { backgrounds: {
|
|
version: 1 as const,
|
|
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
|
|
...(this.services.backgrounds.defaultFolder ? { defaultFolder: () => this.backgroundRequest(() => this.services.backgrounds!.defaultFolder!()) } : {}),
|
|
list: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.list(folder)),
|
|
read: (folder: string, name: string) => this.backgroundRequest(() => this.services.backgrounds!.read(folder, name)),
|
|
...(this.services.backgrounds.readImageSettings ? { readImageSettings: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.readImageSettings!(folder)) } : {}),
|
|
...(this.services.backgrounds.writeImageSettings ? { writeImageSettings: (folder: string, contents: string, expected: string | null) => this.backgroundRequest(() => this.services.backgrounds!.writeImageSettings!(folder, contents, expected)) } : {}),
|
|
set: (target: string, frame: import('./backgroundContracts.ts').BackgroundFrame | null) => { this.check(); backgroundHub.set(this.backgroundOwner, target, frame); },
|
|
get: (target: string) => { this.check(); return backgroundHub.get(target); },
|
|
subscribe: (listener: (target: string) => void) => {
|
|
this.check();
|
|
if (typeof listener !== 'function') throw new Error('A background listener must be a function.');
|
|
const off = backgroundHub.subscribe(target => { if (!this.stopped) listener(target); });
|
|
const cleanup = () => { off(); this.backgroundSubscriptions.delete(cleanup); };
|
|
this.backgroundSubscriptions.add(cleanup);
|
|
return cleanup;
|
|
},
|
|
} } : {}),
|
|
ui: { showActionMenu: options => { this.check(); const menu = showActionMenu(options, this.controller.signal); return { close: () => menu.close() }; } },
|
|
completion: {
|
|
version: 1,
|
|
registerProvider: provider => { this.check(); const off = completionHub.registerProvider({ ...provider, id: this.id + ":" + provider.id }); this.contributions.push(off); return off; },
|
|
registerSurface: surface => { this.check(); const handle = completionHub.registerSurface({ ...surface, id: this.id + ":" + surface.id }); this.contributions.push(handle.dispose); return handle; },
|
|
registerInput: (element, options) => { this.check(); const handle = registerCompletionInput(element, { ...options, id: this.id + ":" + options.id }); this.contributions.push(handle.dispose); return handle; },
|
|
invalidate: () => { this.check(); completionHub.invalidate(); },
|
|
...(this.services.completionTransport ? { transport: (request, signal, onLine) => {
|
|
this.check(); return this.services.completionTransport!(request, AbortSignal.any([signal, this.controller.signal]), onLine);
|
|
} } : {}),
|
|
},
|
|
contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); },
|
|
registerCommand: item => { if (item.category !== undefined && !["open", "action"].includes(item.category)) throw new Error("Unknown plugin command category."); if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); },
|
|
registerView: item => { if ([item.settings, item.launcher, item.navigation, item.toolbar].some(value => value !== undefined && typeof value !== "boolean")) throw new Error("Plugin view access options must be boolean."); if (item.placement !== undefined && !["dialog", "editor", "sidebar"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (item.launch !== undefined && typeof item.launch !== "function") throw new Error("A view launch handler must be a function."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
|
|
registerTabDrop: receive => { this.check(); if (typeof receive !== "function" || this.receiveTab) throw new Error("Invalid or duplicate tab receiver."); this.receiveTab = receive; },
|
|
updateViewTitle: (id, title) => {
|
|
this.check(); const view = this.views.get(id);
|
|
if (!view || typeof title !== "string" || !title.trim() || title.length > 200) throw new Error("Invalid view title.");
|
|
if (view.title !== title) { view.title = title; this.changed(); }
|
|
},
|
|
updateViewIcon: (id, image) => {
|
|
this.check(); const view = this.views.get(id);
|
|
if (!view || (image !== null && (typeof image !== "string" || image.length > 90_000 || !/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/.test(image)))) throw new Error("Invalid view icon.");
|
|
if (view.iconImage !== image) { view.iconImage = image; this.changed(); }
|
|
},
|
|
registerDocumentType: item => {
|
|
if (item.content !== undefined && !["text", "binary"].includes(item.content)) throw new Error("Invalid document content type.");
|
|
if (typeof item.identify !== "function" || typeof item.mount !== "function" || !Array.isArray(item.extensions) || !item.extensions.length || item.extensions.some(ext => !/^[a-z0-9]+$/.test(ext)) || (item.icon && !["kanban", "file"].includes(item.icon))) throw new Error("Invalid document type.");
|
|
if (item.create && (!item.create.label?.trim() || !item.create.defaultName?.trim() || !item.extensions.includes(item.create.extension) || typeof item.create.contents !== "function")) throw new Error("Invalid document creation action.");
|
|
register(this.documentTypes, item);
|
|
},
|
|
openDocument: path => { this.check(); return this.openDocument(path); },
|
|
...(this.services.openFile ? { openFile: (path: string) => { this.check(); return this.services.openFile!(path); } } : {}),
|
|
...(this.renameDocument ? { renameDocument: (document: PluginDocumentContext, name: string) => { this.check(); return this.renameDocument!(document, name); } } : {}),
|
|
openView: (id, options) => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id, options); },
|
|
...(this.close ? { closeView: (id: string) => { this.check(); this.close!(id); } } : {}),
|
|
...(this.replace ? { replaceView: (currentId: string, nextId: string) => { this.check(); if (!this.views.has(currentId) || !this.views.has(nextId)) throw new Error("Unknown plugin view."); this.replace!(currentId, nextId); } } : {}),
|
|
...(this.replaceDocument ? { replaceDocumentWithView: (document: PluginDocumentContext, nextId: string) => { this.check(); if (!this.views.has(nextId)) throw new Error("Unknown plugin view."); this.replaceDocument!(document, nextId); } } : {}),
|
|
onDispose: cleanup => { this.check(); if (typeof cleanup !== "function") throw new Error("Cleanup must be a function."); this.cleanups.push(cleanup); },
|
|
workspace: {
|
|
...(this.services.workspace.subscribe ? { subscribe: (listener: () => void) => {
|
|
this.check(); const off = this.services.workspace.subscribe!(() => { if (!this.stopped) listener(); });
|
|
let active = true;
|
|
const cleanup: Dispose = () => {
|
|
if (!active) return;
|
|
active = false; this.cleanups = this.cleanups.filter(item => item !== cleanup);
|
|
return off();
|
|
};
|
|
this.cleanups.push(cleanup); return cleanup;
|
|
} } : {}),
|
|
list: path => { this.check(); return this.services.workspace.list(path); },
|
|
...(this.services.workspace.listMarkdown ? { listMarkdown: () => { this.check(); return this.services.workspace.listMarkdown!(); } } : {}),
|
|
read: path => { this.check(); return this.services.workspace.read(path); },
|
|
...(this.services.workspace.readMany ? { readMany: (paths: string[]) => { this.check(); return this.services.workspace.readMany!(paths); } } : {}),
|
|
...(this.services.workspace.readBytes ? { readBytes: (path: string) => { this.check(); return this.services.workspace.readBytes!(path); } } : {}),
|
|
...(this.services.workspace.readOptional ? { readOptional: (path: string) => { this.check(); return this.services.workspace.readOptional!(path); } } : {}),
|
|
...(this.services.workspace.create ? { create: (path: string, contents: string) => { this.check(); return this.services.workspace.create!(path, contents); } } : {}),
|
|
write: (path, value, expected) => { this.check(); if (typeof expected !== "string") throw new Error("Supply the original file text before writing."); return this.services.workspace.write(path, value, expected); },
|
|
},
|
|
settings: {
|
|
...(this.services.settings.subscribe ? { subscribe: (listener: () => void) => {
|
|
this.check();
|
|
const off = this.services.settings.subscribe!(() => { if (!this.stopped) listener(); });
|
|
let active = true;
|
|
const cleanup: Dispose = () => { if (!active) return; active = false; this.cleanups = this.cleanups.filter(item => item !== cleanup); return off(); };
|
|
this.cleanups.push(cleanup); return cleanup;
|
|
} } : {}),
|
|
read: () => { this.check(); return this.services.settings.read(); },
|
|
write: value => { this.check(); return this.services.settings.write(value); },
|
|
},
|
|
assets: { read: path => { this.check(); return this.services.assets.read(path); } },
|
|
};
|
|
this.activation = Promise.resolve().then(() => {
|
|
if (typeof module.activate !== "function") throw new Error("The plugin must export activate(api).");
|
|
this.check(); return module.activate(api);
|
|
}).then(async cleanup => {
|
|
if (typeof cleanup === "function") {
|
|
if (this.stopped) { this.lateCleanup = Promise.resolve().then(cleanup); await this.lateCleanup; } else this.cleanups.push(cleanup);
|
|
}
|
|
});
|
|
await deadline(this.activation);
|
|
}
|
|
async run(id: string) { this.check(); const command = this.commands.get(id); if (!command) throw new Error("Unknown plugin command."); await command.run(); }
|
|
async launch(id: string) {
|
|
this.check();
|
|
const view = this.views.get(id);
|
|
if (!view) throw new Error("Unknown plugin view.");
|
|
if (view.launch) await view.launch();
|
|
else this.show(id);
|
|
}
|
|
private backgroundRequest<T>(request: () => Promise<T>): Promise<T> {
|
|
this.check();
|
|
return request().then(value => { this.check(); return value; });
|
|
}
|
|
private ptyApi(pty: PtyTransport): PtyApi {
|
|
const size = (cols: unknown, rows: unknown) => {
|
|
if (![cols, rows].every(value => Number.isInteger(value) && (value as number) > 0 && (value as number) <= 10_000)) throw new Error("Terminal columns and rows must be positive integers.");
|
|
};
|
|
const validate = (options: PtyOpenOptions) => {
|
|
this.check();
|
|
if (!options || typeof options.onData !== "function" || (options.onExit !== undefined && typeof options.onExit !== "function")) throw new Error("A terminal session needs an onData function.");
|
|
if (typeof options.cwd !== "string") throw new Error("Supply the workspace folder as cwd.");
|
|
size(options.cols, options.rows);
|
|
};
|
|
const open = async (options: PtyOpenOptions): Promise<PtySession> => {
|
|
const id = crypto.randomUUID();
|
|
let closed = false, exited = false, closing: Promise<void> | undefined;
|
|
const exit = (code: number | null) => {
|
|
if (exited) return;
|
|
exited = true; this.ptySessions.delete(id);
|
|
if (!closed && !this.stopped) options.onExit?.(code);
|
|
};
|
|
const opening = pty.open({ id, cwd: options.cwd, cols: options.cols, rows: options.rows, ...(options.profile === undefined ? {} : { profile: options.profile }), ...(options.directory === undefined ? {} : { directory: options.directory }) },
|
|
data => { if (!closed && !this.stopped) options.onData(data); }, exit);
|
|
// Wait for the start, so that a close cannot leave a late shell running.
|
|
const close = () => closing ??= (async () => {
|
|
closed = true;
|
|
try { await opening; } catch { this.ptySessions.delete(id); return; }
|
|
this.ptySessions.delete(id);
|
|
await pty.close(id);
|
|
})();
|
|
this.ptySessions.set(id, close);
|
|
try { await opening; } catch (error) { this.ptySessions.delete(id); closed = true; throw error; }
|
|
if (this.stopped) { await close(); this.check(); }
|
|
const live = () => { this.check(); if (closed) throw new Error("This terminal is closed."); };
|
|
return {
|
|
id,
|
|
write: data => { live(); if (typeof data !== "string") throw new Error("Terminal input must be text."); return pty.write(id, data); },
|
|
resize: (cols, rows) => { live(); size(cols, rows); return pty.resize(id, cols, rows); },
|
|
close,
|
|
};
|
|
};
|
|
return {
|
|
version: 1,
|
|
profiles: () => this.backgroundRequest(() => pty.profiles()),
|
|
open: options => { validate(options); return open(options); },
|
|
openWindow: () => { this.check(); return pty.openWindow(); },
|
|
dictation: () => { this.check(); return pty.dictation(); },
|
|
};
|
|
}
|
|
private filesApi(files: FilesTransport): FilesApi {
|
|
const text = (value: unknown, label: string) => { if (typeof value !== "string" || !value) throw new Error(`Supply the ${label} as text.`); };
|
|
return {
|
|
version: 1,
|
|
chooseFolder: options => this.backgroundRequest(() => files.chooseFolder(options?.title === undefined ? undefined : { title: String(options.title) })),
|
|
pictureFolder: name => { text(name, "folder name"); return this.backgroundRequest(() => files.pictureFolder(name)); },
|
|
grants: () => this.backgroundRequest(() => files.grants()),
|
|
revoke: grant => { text(grant, "grant ID"); return this.backgroundRequest(() => files.revoke(grant)); },
|
|
list: grant => { text(grant, "grant ID"); return this.backgroundRequest(() => files.list(grant)); },
|
|
readBytes: (grant, name) => { text(grant, "grant ID"); text(name, "file name"); return this.backgroundRequest(() => files.readBytes(grant, name)); },
|
|
readSidecar: (grant, name) => { text(grant, "grant ID"); text(name, "file name"); return this.backgroundRequest(() => files.readSidecar(grant, name)); },
|
|
writeSidecar: (grant, name, contents, expected) => {
|
|
text(grant, "grant ID"); text(name, "file name");
|
|
if (typeof contents !== "string" || (expected !== null && typeof expected !== "string")) throw new Error("Supply the sidecar text and the expected text or null.");
|
|
return this.backgroundRequest(() => files.writeSidecar(grant, name, contents, expected));
|
|
},
|
|
};
|
|
}
|
|
private servicesApi(hub: ServiceHub): NonNullable<PluginApi["services"]> {
|
|
return {
|
|
version: 1,
|
|
provide: (name, methods) => { this.check(); return hub.provide(this.serviceOwner, this.id, name, methods); },
|
|
get: (plugin, name) => { this.check(); return hub.get(plugin, name, () => !this.stopped); },
|
|
subscribe: listener => {
|
|
this.check();
|
|
if (typeof listener !== "function") throw new Error("A service listener must be a function.");
|
|
const off = hub.subscribe((plugin, name) => { if (!this.stopped) listener(plugin, name); });
|
|
const cleanup = () => { off(); this.serviceSubscriptions.delete(cleanup); };
|
|
this.serviceSubscriptions.add(cleanup);
|
|
return cleanup;
|
|
},
|
|
};
|
|
}
|
|
async dropTab(data: string) {
|
|
this.check();
|
|
if (!this.receiveTab) throw new Error("This plugin cannot receive tabs.");
|
|
await this.receiveTab(data);
|
|
}
|
|
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext, surface: "settings" | "view" = "view"): Promise<Dispose> {
|
|
this.check(); const view = document ? this.documentTypes.get(id) : this.views.get(id); if (!view) throw new Error("Unknown plugin view.");
|
|
let cleaning: Promise<void> | undefined;
|
|
const pending = Promise.resolve().then(() => { this.check(); return document ? (view as PluginDocumentType).mount(element, document) : (view as PluginView).mount(element, { surface }); });
|
|
const cleanup = () => {
|
|
cleaning ??= (async () => {
|
|
const dispose = await pending;
|
|
if (typeof dispose === "function") await dispose();
|
|
element.replaceChildren(); this.mounted.delete(cleanup);
|
|
})();
|
|
return cleaning;
|
|
};
|
|
this.mounted.add(cleanup);
|
|
try { await deadline(pending); } catch (error) { await deadline(cleanup()).catch(() => {}); throw error; }
|
|
if (this.stopped) await cleanup();
|
|
return cleanup;
|
|
}
|
|
stop(): Promise<void> {
|
|
if (this.stopping) return this.stopping;
|
|
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed();
|
|
for (const off of this.backgroundSubscriptions) off();
|
|
backgroundHub.removeOwner(this.backgroundOwner);
|
|
for (const off of this.serviceSubscriptions) off();
|
|
(this.services.serviceHub ?? defaultServiceHub).removeOwner(this.serviceOwner);
|
|
for (const remove of this.contributions.splice(0)) remove();
|
|
this.stopping = (async () => {
|
|
const errors: unknown[] = [];
|
|
// Activation rejection is reported by start. A timeout still blocks removal.
|
|
try { await deadline(this.activation.catch(() => {})); } catch (error) { errors.push(error); }
|
|
if (this.lateCleanup) { try { await deadline(this.lateCleanup); } catch (error) { errors.push(error); } }
|
|
for (const cleanup of [...this.mounted, ...this.cleanups.reverse()]) {
|
|
try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); }
|
|
}
|
|
this.cleanups = [];
|
|
// Stop the terminal sessions that the plugin cleanup left open.
|
|
for (const close of [...this.ptySessions.values()]) {
|
|
try { await deadline(close()); } catch (error) { errors.push(error); }
|
|
}
|
|
if (errors.length) throw new Error(errors.map(String).join("\n"));
|
|
})();
|
|
return this.stopping;
|
|
}
|
|
}
|