Give plugins SDK APIs for terminals, granted folders, and plugin services
Plugins can now do through the SDK what they did with direct native calls. The SDK checks plugin shutdown, so these APIs can move to an isolated plugin context later. - api.pty opens shell sessions. pty_open accepts an optional channel. A channel session sends its output as raw bytes to its own webview and sends no pty-data or pty-exit events. Without a channel, the events stay, so the released Terminal plugin keeps working. The host closes the open sessions of a plugin when the plugin stops. - api.files gives folder grants. The user selects the folder, the host keeps the grants of each plugin in its retained data, and the plugin uses an opaque grant ID. The host rejects names with folder parts, links, and files over the size limit. Sidecar JSON files replace the per-image settings commands. - api.services lets one plugin offer data to another plugin in the same window. The host copies arguments and results. - The folder methods of api.backgrounds are deprecated. They stay for released Background Slideshow versions. - The plugin reference lists the native calls of each plugin and the SDK member that replaces each call.
This commit is contained in:
@@ -3,8 +3,16 @@ 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, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.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"]; git?: PluginApi["git"]; 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>;
|
||||
@@ -27,8 +35,11 @@ export class ExternalSession {
|
||||
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: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
|
||||
private services: SessionServices;
|
||||
private changed: () => void;
|
||||
private show: PluginApi["openView"];
|
||||
private close?: PluginApi["closeView"];
|
||||
@@ -37,7 +48,7 @@ export class ExternalSession {
|
||||
private receiveTab?: (data: string) => void | Promise<void>;
|
||||
private openDocument: (path: string) => Promise<void>;
|
||||
private renameDocument?: PluginApi["renameDocument"];
|
||||
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, 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"]) {
|
||||
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;
|
||||
@@ -54,6 +65,9 @@ export class ExternalSession {
|
||||
};
|
||||
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()),
|
||||
@@ -180,6 +194,85 @@ export class ExternalSession {
|
||||
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.");
|
||||
@@ -207,6 +300,8 @@ export class ExternalSession {
|
||||
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[] = [];
|
||||
@@ -217,6 +312,10 @@ export class ExternalSession {
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user