Move the tests from scripts/ to tests/ by feature
Unit tests go to tests/unit/<area>/, browser smoke tests to tests/smoke/<area>/, and tests against a running desktop app to tests/native/. Files named after dates, work passes, or Kanban cards get feature names, for example editorOctober12 -> editor/footnotes. scripts/ keeps the build, release, and package tools. Plugin repositories import scripts/packagePlugin.mjs, and the Terminal smoke test imports scripts/pluginMocks.mjs, which now re-exports the harness copy. The unit tests get their own type check (tests/tsconfig.json) with Node types. pnpm check runs it after the app check. Add @types/node and fix the three test mocks that it reported.
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { CompletionHub, eligible } from '../../../src/lib/completion/hub.ts';
|
||||
import type { CompletionSnapshot } from '../../../src/lib/completion/contracts.ts';
|
||||
const snapshot = (): CompletionSnapshot => ({ documentId: 'doc', revision: 1, text: 'The ', caret: 4, selectionEnd: 4, focused: true, kind: 'prose' });
|
||||
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
|
||||
test('sensitive fields, composition, selections, code blocks and link targets are excluded', () => {
|
||||
assert(eligible(snapshot()));
|
||||
for (const change of [{ sensitive: true }, { composing: true }, { readOnly: true }, { selectionEnd: 0 }, { focused: false }]) assert(!eligible({ ...snapshot(), ...change }));
|
||||
for (const text of ['```js\nlet ', '[name](http', '| cell ', '`source', '---\nname: ']) assert(!eligible({ ...snapshot(), text, caret: text.length, selectionEnd: text.length }));
|
||||
assert(eligible({ ...snapshot(), kind: 'code', text: 'let ', caret: 4 }));
|
||||
});
|
||||
test('a new revision blocks stale insertion even when the provider ignores cancellation', async () => {
|
||||
const hub = new CompletionHub(); let state = snapshot(), emit!: (text: string) => void, finish!: (text: string) => void, visible = '', edits = 0;
|
||||
hub.registerProvider({ id: 'model', complete: (_request, publish) => { emit = publish; return new Promise(resolve => finish = resolve); } });
|
||||
const field = hub.registerSurface({ id: 'field', snapshot: () => state, preview: text => visible = text || '', insert: () => { edits++; return true; } });
|
||||
field.request(); emit('harbor'); assert.equal(visible, 'harbor');
|
||||
state = { ...state, revision: 2, text: 'The old ', caret: 8, selectionEnd: 8 };
|
||||
assert.equal(field.accept(), false); finish('late'); await tick(); assert.equal(visible, ''); assert.equal(edits, 0); field.dispose();
|
||||
});
|
||||
test('acceptance is explicit and provider removal clears all surfaces', async () => {
|
||||
const hub = new CompletionHub(); let visible = '', inserted = '';
|
||||
const remove = hub.registerProvider({ id: 'model', complete: async () => 'quiet harbor' });
|
||||
const field = hub.registerSurface({ id: 'field', snapshot, preview: text => visible = text || '', insert: text => { inserted = text; return true; } });
|
||||
field.request(); await tick(); assert.equal(inserted, ''); assert.equal(visible, 'quiet harbor');
|
||||
assert(field.accept(true)); assert.equal(inserted, 'quiet '); assert.equal(visible, '');
|
||||
field.request(); await tick(); remove(); assert.equal(visible, ''); assert.equal(field.accept(), false); field.dispose();
|
||||
});
|
||||
test('moving between fields cancels the previous request', async () => {
|
||||
const hub = new CompletionHub(); const signals: AbortSignal[] = [];
|
||||
hub.registerProvider({ id: 'model', complete: request => { signals.push(request.signal); return new Promise(() => {}); } });
|
||||
const a = hub.registerSurface({ id: 'a', snapshot, preview() {}, insert: () => true });
|
||||
const b = hub.registerSurface({ id: 'b', snapshot, preview() {}, insert: () => true });
|
||||
a.request(); b.request(); assert(signals[0].aborted); assert(!signals[1].aborted); a.dispose(); b.dispose();
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
|
||||
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
|
||||
function fixture() {
|
||||
let writes = 0;
|
||||
const session = new ExternalSession("org.test.demo", {
|
||||
workspace: { list: async () => [], read: async () => "original", write: async () => { writes++; } },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, () => {});
|
||||
return { session, writes: () => writes };
|
||||
}
|
||||
|
||||
test("native Markdown discovery remains optional and is revoked on disable", async () => {
|
||||
let api!: PluginApi;
|
||||
let scans = 0;
|
||||
const session = new ExternalSession("org.test.scan", {
|
||||
workspace: { list: async () => [], listMarkdown: async () => { scans++; return ["Notes/task.md"]; }, read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
assert.deepEqual(await api.workspace.listMarkdown!(), ["Notes/task.md"]);
|
||||
await session.stop();
|
||||
assert.throws(() => api.workspace.listMarkdown!(), /disabled/);
|
||||
assert.equal(scans, 1);
|
||||
const old = fixture().session;
|
||||
await old.start({ activate(value) { assert.equal(value.workspace.listMarkdown, undefined); } });
|
||||
await old.stop();
|
||||
});
|
||||
test("external commands run and all host access stops before cleanup", async () => {
|
||||
const { session, writes } = fixture(); let api!: PluginApi; let ran = 0;
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
api.registerCommand({ id: "run", title: "Run", run: () => { ran++; } });
|
||||
api.registerView({ id: "view", title: "View", mount: () => {} });
|
||||
api.onDispose(() => { assert(api.signal.aborted); assert.throws(() => api.workspace.read("x"), /disabled/); });
|
||||
} });
|
||||
await session.run("run"); assert.equal(ran, 1);
|
||||
assert.throws(() => api.workspace.write("x", "new", undefined!), /original/);
|
||||
await api.workspace.write("x", "new", "original"); assert.equal(writes(), 1);
|
||||
await session.stop(); assert.equal(session.commands.size, 0); assert.equal(session.views.size, 0);
|
||||
await assert.rejects(session.run("run"), /disabled/);
|
||||
assert.throws(() => api.settings.read(), /disabled/);
|
||||
});
|
||||
test("async activation cleanup runs once even when disabled before activation finishes", async () => {
|
||||
const { session } = fixture(); let resolve!: () => void; let cleaned = 0;
|
||||
const gate = new Promise<void>(done => resolve = done);
|
||||
const start = session.start({ async activate() { await gate; return () => { cleaned++; }; } });
|
||||
await Promise.resolve();
|
||||
const stopped = session.stop(); resolve();
|
||||
await Promise.all([start, stopped]); await session.stop(); assert.equal(cleaned, 1);
|
||||
});
|
||||
test("failed cleanup does not skip other callbacks and blocks successful shutdown", async () => {
|
||||
const { session } = fixture(); const calls: number[] = [];
|
||||
await session.start({ activate(api) {
|
||||
api.onDispose(() => { calls.push(1); });
|
||||
api.onDispose(() => { calls.push(2); throw new Error("Cleanup failed"); });
|
||||
api.onDispose(() => { calls.push(3); });
|
||||
} });
|
||||
await assert.rejects(session.stop(), /Cleanup failed/); assert.deepEqual(calls, [3, 2, 1]);
|
||||
});
|
||||
test("duplicate contribution IDs fail and partial activation can be cleaned", async () => {
|
||||
const { session } = fixture(); let cleaned = false;
|
||||
await assert.rejects(session.start({ activate(api) {
|
||||
api.onDispose(() => { cleaned = true; });
|
||||
api.registerCommand({ id: "run", title: "Run", run() {} });
|
||||
api.registerCommand({ id: "run", title: "Again", run() {} });
|
||||
} }), /duplicate/);
|
||||
await session.stop(); assert(cleaned); assert.equal(session.commands.size, 0);
|
||||
});
|
||||
test("view disposal is idempotent and participates in plugin shutdown", async () => {
|
||||
const { session } = fixture(); let cleaned = 0; let cleared = 0;
|
||||
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => () => { cleaned++; } }); } });
|
||||
const cleanup = await session.mount("view", { replaceChildren() { cleared++; } } as unknown as HTMLElement);
|
||||
await session.stop(); await cleanup(); assert.equal(cleaned, 1); assert.equal(cleared, 1);
|
||||
});
|
||||
test("shutdown waits for view cleanup that already started when the view closed", async () => {
|
||||
const { session } = fixture(); let done!: () => void; let cleaned = false;
|
||||
const gate = new Promise<void>(resolve => done = resolve);
|
||||
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => async () => { await gate; cleaned = true; } }); } });
|
||||
const cleanup = await session.mount("view", { replaceChildren() {} } as unknown as HTMLElement);
|
||||
const closing = cleanup(); await Promise.resolve();
|
||||
let stopped = false; const stopping = session.stop().then(() => { stopped = true; });
|
||||
await Promise.resolve(); await Promise.resolve(); assert.equal(stopped, false);
|
||||
done(); await Promise.all([closing, stopping]); assert(cleaned);
|
||||
});
|
||||
test("cleanup returned by late activation still blocks shutdown when it fails", async () => {
|
||||
const { session } = fixture(); let done!: () => void;
|
||||
const gate = new Promise<void>(resolve => done = resolve);
|
||||
const starting = session.start({ async activate() { await gate; return () => { throw new Error("Late cleanup failed"); }; } });
|
||||
await Promise.resolve(); const stopping = session.stop(); done();
|
||||
await assert.rejects(starting, /Late cleanup failed/); await assert.rejects(stopping, /Late cleanup failed/);
|
||||
});
|
||||
|
||||
test("batch workspace reads remain optional and stop when the plugin is disabled", async () => {
|
||||
let api!: PluginApi;
|
||||
let calls = 0;
|
||||
const rows = [{ path: "Card.md", source: "Card source" }, { path: "Missing.md", error: "File not found" }];
|
||||
const session = new ExternalSession("org.test.batch", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {},
|
||||
readMany: async paths => { calls++; assert.deepEqual(paths, ["Card.md", "Missing.md"]); return rows; } },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
assert.deepEqual(await api.workspace.readMany!(["Card.md", "Missing.md"]), rows);
|
||||
await session.stop();
|
||||
assert.throws(() => api.workspace.readMany!(["Card.md"]), /disabled/);
|
||||
assert.equal(calls, 1);
|
||||
const old = fixture().session;
|
||||
await old.start({ activate(value) { assert.equal(value.workspace.readMany, undefined); } });
|
||||
await old.stop();
|
||||
});
|
||||
|
||||
test("view launch selects a default while explicit opens preserve their target", async () => {
|
||||
const opened: string[] = [];
|
||||
let api!: PluginApi;
|
||||
const session = new ExternalSession("org.test.launch", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, id => { opened.push(id); });
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
api.registerView({ id: "all", title: "All", launch: async () => { api.openView("board"); }, mount() {} });
|
||||
api.registerView({ id: "board", title: "Board", mount() {} });
|
||||
assert.throws(() => api.registerView({ id: "invalid", title: "Invalid", launch: true as never, mount() {} }), /launch handler/);
|
||||
} });
|
||||
await session.launch("all");
|
||||
api.openView("all");
|
||||
await session.launch("board");
|
||||
assert.deepEqual(opened, ["board", "all", "board"]);
|
||||
await assert.rejects(session.launch("missing"), /Unknown plugin view/);
|
||||
await session.stop();
|
||||
await assert.rejects(session.launch("all"), /disabled/);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { pluginAccess } from "../../../src/lib/plugins/access.ts";
|
||||
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
|
||||
import type { PluginApi, PluginCommand, PluginView } from "../../../src/lib/plugins/sdk.ts";
|
||||
|
||||
const view = (id: string, extra: Partial<PluginView> = {}): PluginView => ({ id, title: id, mount() {}, ...extra });
|
||||
const command = (id: string, extra: Partial<PluginCommand> = {}): PluginCommand => ({ id, title: id, run() {}, ...extra });
|
||||
|
||||
test("plugin access separates settings, launchers, and commands without reading titles", () => {
|
||||
const tools = pluginAccess("org.example.test", [command("open", { category: "open" }), command("configure")], [view("preferences", { settings: true }), view("tasks"), view("instance", { launcher: false })]);
|
||||
assert.deepEqual(tools.map(({ id, surface }) => [id, surface]), [["open", "open"], ["configure", "commands"], ["preferences", "settings"], ["tasks", "open"]]);
|
||||
});
|
||||
|
||||
test("installed RuneStone packages retain access before their next package update", () => {
|
||||
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings")])[0].surface, "settings");
|
||||
assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab")], [view("tab-123")]).map(({ id, surface }) => [id, surface]), [["new-tab", "open"]]);
|
||||
assert.equal(pluginAccess("org.example.test", [], [view("settings")])[0].surface, "open");
|
||||
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings", { settings: false })])[0].surface, "open");
|
||||
assert.equal(pluginAccess("runestone.browser", [command("new-tab", { category: "action" })], [])[0].surface, "commands");
|
||||
});
|
||||
|
||||
test("command launchers retain the plugin action icon", () => {
|
||||
const tools = pluginAccess("runestone.git", [command("graph", { category: "open", icon: "git" })], []);
|
||||
assert.equal(tools[0].icon, "git");
|
||||
assert.equal(tools[0].surface, "open");
|
||||
});
|
||||
|
||||
test("settings listeners are removable and revoked before plugin cleanup", async () => {
|
||||
let api!: PluginApi, notify!: () => void;
|
||||
let received = 0, disposed = 0;
|
||||
const session = new ExternalSession("org.example.settings", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
settings: { read: async () => null, write: async () => {}, subscribe(listener) { notify = listener; return () => { disposed++; }; } },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
const off = api.settings.subscribe!(() => { received++; });
|
||||
notify(); assert.equal(received, 1);
|
||||
await off(); await off(); assert.equal(disposed, 1);
|
||||
api.settings.subscribe!(() => { received++; });
|
||||
await session.stop(); notify();
|
||||
assert.equal(received, 1); assert.equal(disposed, 2);
|
||||
assert.throws(() => api.settings.subscribe!(() => {}), /disabled/);
|
||||
});
|
||||
|
||||
test("invalid access metadata fails registration", async () => {
|
||||
for (const activate of [
|
||||
(api: PluginApi) => api.registerCommand(command("invalid", { category: "unknown" as "open" })),
|
||||
(api: PluginApi) => api.registerView(view("invalid", { settings: "yes" as unknown as boolean })),
|
||||
(api: PluginApi) => api.registerView(view("invalid", { launcher: "yes" as unknown as boolean })),
|
||||
]) {
|
||||
const session = new ExternalSession("org.example.invalid", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
|
||||
}, () => {}, () => {});
|
||||
await assert.rejects(session.start({ activate }), /category|boolean/);
|
||||
await session.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("settings windows permit model checks and cancellation", () => {
|
||||
const capability = JSON.parse(readFileSync(new URL("../../../src-tauri/capabilities/settings.json", import.meta.url), "utf8"));
|
||||
for (const permission of ["allow-completion-request", "allow-completion-cancel", "allow-plugins-data"]) assert(capability.permissions.includes(permission));
|
||||
});
|
||||
|
||||
test("view mount context distinguishes Settings from editor and dialog views", async () => {
|
||||
const surfaces: string[] = [];
|
||||
const session = new ExternalSession("org.example.context", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(api) { api.registerView(view("settings", { mount(_element, context) { surfaces.push(context!.surface); } })); } });
|
||||
const target = { replaceChildren() {} } as unknown as HTMLElement;
|
||||
const disposeView = await session.mount("settings", target);
|
||||
await disposeView();
|
||||
const disposeSettings = await session.mount("settings", target, undefined, "settings");
|
||||
await disposeSettings(); await session.stop();
|
||||
assert.deepEqual(surfaces, ["view", "settings"]);
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
|
||||
import type { PluginApi, PluginDocumentType } from "../../../src/lib/plugins/sdk.ts";
|
||||
|
||||
const services = {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
};
|
||||
const type: PluginDocumentType = {
|
||||
id: "board", title: "Board", icon: "kanban", extensions: ["md"],
|
||||
identify: (_path, source) => source === "board" ? { id: "stable" } : null,
|
||||
create: { label: "New board", defaultName: "Untitled board", extension: "md", contents: () => "board" },
|
||||
mount: () => {},
|
||||
};
|
||||
|
||||
test("document renames pass the stable identity and stop after shutdown", async () => {
|
||||
let api!: PluginApi;
|
||||
const calls: unknown[] = [];
|
||||
const session = new ExternalSession("fixture", services, () => {}, () => {}, undefined, undefined,
|
||||
async (document, name) => { calls.push({ document, name }); return "Renamed.md"; });
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
assert.equal(await api.renameDocument!({ id: "stable", path: "Board.md" }, "Renamed"), "Renamed.md");
|
||||
assert.deepEqual(calls, [{ document: { id: "stable", path: "Board.md" }, name: "Renamed" }]);
|
||||
await session.stop();
|
||||
assert.throws(() => api.renameDocument!({ id: "stable", path: "Board.md" }, "Other"), /disabled/);
|
||||
assert.equal(calls.length, 1);
|
||||
});
|
||||
|
||||
test("binary document registration preserves bytes and revokes reads on shutdown", async () => {
|
||||
let api!: PluginApi;
|
||||
const bytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0xff, 0x00]);
|
||||
const paths: string[] = [];
|
||||
const session = new ExternalSession("fixture", {
|
||||
...services, workspace: { ...services.workspace, readBytes: async path => { paths.push(path); return bytes; } },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
api.registerDocumentType({ ...type, id: "pdf", extensions: ["pdf"], content: "binary", create: undefined });
|
||||
} });
|
||||
assert.equal(session.documentTypes.get("pdf")?.content, "binary");
|
||||
assert.deepEqual(await api.workspace.readBytes!("report.pdf"), bytes);
|
||||
assert.deepEqual(paths, ["report.pdf"]);
|
||||
assert.throws(() => api.registerDocumentType({ ...type, content: "invalid" as "binary" }), /content type/);
|
||||
await session.stop();
|
||||
assert.throws(() => api.workspace.readBytes!("report.pdf"), /disabled/);
|
||||
});
|
||||
|
||||
test("document types have independent registrations and reject invalid creation actions", async () => {
|
||||
let api!: PluginApi;
|
||||
const session = new ExternalSession("fixture", services, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; api.registerDocumentType(type); } });
|
||||
assert.equal(session.documentTypes.get("board")?.identify("Board.md", "board")?.id, "stable");
|
||||
assert.equal(session.documentTypes.get("board")?.identify("Note.md", "plain"), null);
|
||||
assert.throws(() => api.registerDocumentType(type), /duplicate/);
|
||||
assert.throws(() => api.registerDocumentType({ ...type, id: "other", create: { ...type.create!, extension: "exe" } }), /Invalid document creation/);
|
||||
await session.stop();
|
||||
assert.equal(session.documentTypes.size, 0);
|
||||
assert.throws(() => api.registerDocumentType(type), /disabled/);
|
||||
});
|
||||
|
||||
test("two document mounts retain independent context and clean up once", async () => {
|
||||
const mounted: string[] = [], cleaned: string[] = [];
|
||||
const session = new ExternalSession("fixture", services, () => {}, () => {});
|
||||
await session.start({ activate(api) {
|
||||
api.registerDocumentType({ ...type, mount(_node, context) { mounted.push(context.path); return () => { cleaned.push(context.id); }; } });
|
||||
} });
|
||||
const element = () => ({ replaceChildren() {} }) as unknown as HTMLElement;
|
||||
const first = await session.mount("board", element(), { id: "first", path: "One.md" });
|
||||
await session.mount("board", element(), { id: "second", path: "Two.md" });
|
||||
assert.deepEqual(mounted, ["One.md", "Two.md"]);
|
||||
await first(); await first();
|
||||
assert.deepEqual(cleaned, ["first"]);
|
||||
await session.stop();
|
||||
assert.deepEqual(cleaned, ["first", "second"]);
|
||||
});
|
||||
|
||||
test("document opening and workspace subscriptions stop with their plugin", async () => {
|
||||
let api!: PluginApi;
|
||||
let listener: (() => void) | undefined;
|
||||
let notifications = 0, removed = 0;
|
||||
const opened: string[] = [];
|
||||
const session = new ExternalSession("fixture", {
|
||||
...services,
|
||||
workspace: { ...services.workspace, subscribe(callback) { listener = callback; return () => { removed++; }; } },
|
||||
}, () => {}, () => {}, undefined, async path => { opened.push(path); });
|
||||
await session.start({ activate(value) { api = value; api.workspace.subscribe!(() => { notifications++; }); } });
|
||||
await api.openDocument("Board.md"); listener!();
|
||||
assert.deepEqual(opened, ["Board.md"]);
|
||||
assert.equal(notifications, 1);
|
||||
await session.stop(); listener!();
|
||||
assert.equal(notifications, 1);
|
||||
assert.equal(removed, 1);
|
||||
assert.throws(() => api.openDocument("Board.md"), /disabled/);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
|
||||
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
|
||||
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
|
||||
|
||||
test("Git and file access stop before plugin cleanup", async () => {
|
||||
const calls: unknown[] = [];
|
||||
let api!: PluginApi;
|
||||
const registry = new ContributionRegistry();
|
||||
const session = new ExternalSession("test.git", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
|
||||
openFile: async path => { calls.push(path); },
|
||||
git: {
|
||||
status: async () => ({ available: true, repository: true, branch: "main", changes: [] }),
|
||||
diff: async (path, staged) => { calls.push([path, staged]); return "diff"; },
|
||||
stage: async paths => { calls.push(paths); }, unstage: async paths => { calls.push(paths); },
|
||||
commit: async message => { calls.push(message); }, blame: async () => null,
|
||||
push: async () => { calls.push('push'); }, pull: async () => { calls.push('pull'); }, graph: async () => ({ commits: [] }),
|
||||
commitDetails: async () => { throw new Error("not used"); }, commitDiff: async () => "",
|
||||
},
|
||||
}, () => {}, () => {}, registry);
|
||||
await session.start({ activate(value) { api = value; api.contribute("git", { blame: (path, line) => api.git!.blame(path, line) }); } });
|
||||
await api.openFile!("notes.md");
|
||||
assert.equal(await api.git!.diff("notes.md", true), "diff");
|
||||
await api.git!.stage(["notes.md"]);
|
||||
assert.deepEqual(calls, ["notes.md", ["notes.md", true], ["notes.md"]]);
|
||||
await api.git!.push();
|
||||
await api.git!.pull();
|
||||
assert.deepEqual(await api.git!.graph(), { commits: [] });
|
||||
assert.deepEqual(calls.slice(-2), ['push', 'pull']);
|
||||
await session.stop();
|
||||
assert.equal(registry.get("git"), undefined);
|
||||
assert.throws(() => api.openFile!("notes.md"), /disabled/);
|
||||
for (const action of [() => api.git!.push(), () => api.git!.pull(), () => api.git!.graph()]) assert.throws(action, /disabled/);
|
||||
for (const action of [() => api.git!.status(), () => api.git!.diff("a", false), () => api.git!.stage(["a"]), () => api.git!.unstage(["a"]), () => api.git!.commit("a"), () => api.git!.blame("a", 1)]) assert.throws(action, /disabled/);
|
||||
});
|
||||
|
||||
test("view replacement rejects unknown destinations and stops after disposal", async () => {
|
||||
let api!: PluginApi;
|
||||
const calls: unknown[] = [];
|
||||
const session = new ExternalSession("test.boards", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, () => {}, new ContributionRegistry(), undefined, undefined, undefined,
|
||||
(current, next) => calls.push([current, next]), (document, next) => calls.push([document, next]));
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
for (const id of ["a", "b"]) api.registerView({ id, title: id, placement: "editor", mount() {} });
|
||||
api.registerView({ id: "sidebar", title: "Sidebar", placement: "sidebar", navigation: true, icon: "git", mount() {} });
|
||||
} });
|
||||
api.replaceView!("a", "b");
|
||||
api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "b");
|
||||
assert.deepEqual(calls, [["a", "b"], [{ id: "legacy", path: "Board.md" }, "b"]]);
|
||||
assert.throws(() => api.replaceView!("missing", "b"), /Unknown/);
|
||||
assert.throws(() => api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "missing"), /Unknown/);
|
||||
await session.stop();
|
||||
assert.throws(() => api.replaceView!("a", "b"), /disabled/);
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, mkdir, readFile, writeFile, rm, realpath } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
// @ts-ignore The build tool is a JavaScript module.
|
||||
import { packagePlugin } from "../../../scripts/packagePlugin.mjs";
|
||||
|
||||
test("plugin packaging rejects invalid release inputs before writing an archive", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "runestone-packaging-"));
|
||||
const source = join(root, "plugin"), output = join(root, "releases");
|
||||
await mkdir(source);
|
||||
const manifest = {
|
||||
schemaVersion: 1, apiVersion: 1, id: "org.test.demo", name: "Demo", author: "Test",
|
||||
description: "Test plugin", version: "1.0.0", entry: "main.js", access: "full-app",
|
||||
};
|
||||
const save = async (changes = {}) => writeFile(join(source, "plugin.json"), JSON.stringify({ ...manifest, ...changes }));
|
||||
try {
|
||||
await assert.rejects(packagePlugin(source, output), /plugin.json at its root/);
|
||||
await save();
|
||||
await assert.rejects(packagePlugin(source, output), /entry module is missing/);
|
||||
await writeFile(join(source, "main.js"), "export function activate() {}");
|
||||
for (const [changes, message] of [
|
||||
[{ id: "../escape" }, /ID is invalid/],
|
||||
[{ version: "1.0" }, /version such as/],
|
||||
[{ version: "1.0.0A" }, /version such as/],
|
||||
[{ version: "1.0.0a1" }, /version such as/],
|
||||
[{ version: "1.0.0-beta" }, /version such as/],
|
||||
[{ version: "1.0.0+build" }, /version such as/],
|
||||
[{ entry: "../main.js" }, /compiled JavaScript/],
|
||||
[{ apiVersion: 99 }, /Unsupported/],
|
||||
[{ author: "" }, /valid author/],
|
||||
] as const) {
|
||||
await save(changes);
|
||||
await assert.rejects(packagePlugin(source, output), message);
|
||||
}
|
||||
await save();
|
||||
await assert.rejects(packagePlugin(source, source), /outside the plugin folder/);
|
||||
await writeFile(join(source, "invalid file.txt"), "test");
|
||||
await assert.rejects(packagePlugin(source, output), /Invalid package path/);
|
||||
await rm(join(source, "invalid file.txt"));
|
||||
await writeFile(join(root, "package.json"), JSON.stringify({ name: "test-plugin" }));
|
||||
const path = await packagePlugin(source);
|
||||
assert.equal(path, join(await realpath(output), "org.test.demo-1.0.0.zip"));
|
||||
const first = await readFile(path);
|
||||
await packagePlugin(source, output);
|
||||
assert.deepEqual(await readFile(path), first);
|
||||
await writeFile(join(source, "main.js"), "export function activate() { return 1; }");
|
||||
await assert.rejects(packagePlugin(source), /different contents/);
|
||||
assert.deepEqual(await readFile(path), first);
|
||||
await writeFile(join(source, "main.js"), "export function activate() {}");
|
||||
for (const version of ["0.2.28a", "0.2.28b", "0.2.28aa"]) {
|
||||
await save({ version });
|
||||
const hotfix = await packagePlugin(source, output);
|
||||
assert.equal(hotfix, join(await realpath(output), `org.test.demo-${version}.zip`));
|
||||
assert.ok((await readFile(hotfix)).length > 0);
|
||||
assert.deepEqual(await readFile(path), first);
|
||||
}
|
||||
} finally {
|
||||
// mkdtemp returns this test's unique directory under the operating system temp folder.
|
||||
assert.equal(root.startsWith(join(tmpdir(), "runestone-packaging-")), true);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ContributionRegistry, pluginHost } from "../../../src/lib/plugins/registry.ts";
|
||||
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
|
||||
import { existsSync } from "node:fs";
|
||||
// The Table Formulas package comes from a sibling repository. Run `pnpm build:plugins` to build it.
|
||||
const tableFormulasEntry = new URL("../../../plugin-packages/table-formulas/main.js", import.meta.url);
|
||||
const tableFormulas = existsSync(tableFormulasEntry) ? await import(tableFormulasEntry.href) : undefined;
|
||||
const activate = tableFormulas?.activate;
|
||||
const needsTableFormulas = { skip: tableFormulas ? false : "the Table Formulas package is not built; run pnpm build:plugins" };
|
||||
import { renderMarkdownHtml, renderMarkdownSections } from "../../../src/lib/workspace/noteHtml.ts";
|
||||
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
|
||||
|
||||
const services = {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
};
|
||||
|
||||
test("optional workspace creation and reads stop when the plugin is disabled", async () => {
|
||||
const files = new Map<string, string>();
|
||||
let api!: PluginApi;
|
||||
const session = new ExternalSession("workspace-test", {
|
||||
...services,
|
||||
workspace: {
|
||||
...services.workspace,
|
||||
readOptional: async path => files.get(path) ?? null,
|
||||
create: async (path, contents) => { if (files.has(path)) throw new Error("exists"); files.set(path, contents); },
|
||||
},
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
assert.equal(await api.workspace.readOptional!("board.json"), null);
|
||||
await api.workspace.create!("board.json", "{}");
|
||||
assert.equal(await api.workspace.readOptional!("board.json"), "{}");
|
||||
await assert.rejects(api.workspace.create!("board.json", "replacement"), /exists/);
|
||||
await session.stop();
|
||||
assert.throws(() => api.workspace.create!("other.json", "{}"), /disabled/);
|
||||
assert.throws(() => api.workspace.readOptional!("board.json"), /disabled/);
|
||||
assert.equal(files.size, 1);
|
||||
});
|
||||
test("core starts without optional features and formula packages preserve source when stopped", needsTableFormulas, async () => {
|
||||
assert.equal(pluginHost.get("terminal"), undefined);
|
||||
assert.equal(pluginHost.get("tableFormulas"), undefined);
|
||||
const source = "| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n";
|
||||
assert.doesNotMatch(renderMarkdownHtml(source, new Map()), /md-table-formula/);
|
||||
const session = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
|
||||
await session.start({ activate });
|
||||
const enabled = renderMarkdownHtml(source, new Map());
|
||||
assert.match(enabled, />6<\/span>/);
|
||||
await session.stop();
|
||||
for (const html of [renderMarkdownHtml(source, new Map()), ...renderMarkdownSections(source, new Map()).map(section => section.html)]) {
|
||||
assert.doesNotMatch(html, /md-table-formula/);
|
||||
assert.match(html, /=A2\*3/);
|
||||
assert.match(html, /<table>/);
|
||||
}
|
||||
const next = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
|
||||
await next.start({ activate });
|
||||
assert.equal(renderMarkdownHtml(source, new Map()), enabled);
|
||||
await next.stop();
|
||||
});
|
||||
|
||||
test("package contribution conflicts preserve the first owner and revoke access before cleanup", needsTableFormulas, async () => {
|
||||
const registry = new ContributionRegistry();
|
||||
const first = new ExternalSession("first", services, () => {}, () => {}, registry);
|
||||
const second = new ExternalSession("second", services, () => {}, () => {}, registry);
|
||||
let api!: PluginApi;
|
||||
await first.start({ activate(value) { api = value; activate(api); } });
|
||||
const contribution = registry.get("tableFormulas");
|
||||
await assert.rejects(second.start({ activate }), /already registered/);
|
||||
await second.stop();
|
||||
assert.equal(registry.get("tableFormulas"), contribution);
|
||||
api.onDispose(() => {
|
||||
assert.equal(registry.get("tableFormulas"), undefined);
|
||||
assert.throws(() => api.contribute("tableFormulas", contribution!), /disabled/);
|
||||
});
|
||||
await first.stop();
|
||||
});
|
||||
|
||||
test("partial activation and failed cleanup cannot retain feature contributions", needsTableFormulas, async () => {
|
||||
const registry = new ContributionRegistry();
|
||||
const session = new ExternalSession("failed", services, () => {}, () => {}, registry);
|
||||
await assert.rejects(session.start({ activate(api) {
|
||||
activate(api);
|
||||
api.onDispose(() => { throw new Error("Cleanup failed"); });
|
||||
throw new Error("Activation failed");
|
||||
} }), /Activation failed/);
|
||||
await assert.rejects(session.stop(), /Cleanup failed/);
|
||||
assert.equal(registry.get("tableFormulas"), undefined);
|
||||
});
|
||||
Reference in New Issue
Block a user