RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
// Node module hooks for the unit tests. A `.svelte.ts` module uses Svelte runes, so the
// Svelte compiler compiles it after Node strips its types. The server output keeps the
// logic of `$state` fields as plain values, which is enough for tests without a DOM.
import { readFile } from "node:fs/promises";
import { stripTypeScriptTypes } from "node:module";
import { fileURLToPath } from "node:url";
import { compileModule } from "svelte/compiler";
export async function load(url, context, nextLoad) {
if (!url.startsWith("file:") || !url.endsWith(".svelte.ts")) return nextLoad(url, context);
const filename = fileURLToPath(url);
const source = stripTypeScriptTypes(await readFile(filename, "utf8"), { mode: "strip" });
const { js } = compileModule(source, { filename, generate: "server" });
return { format: "module", source: js.code, shortCircuit: true };
}
+4
View File
@@ -0,0 +1,4 @@
// Load with `node --import`, so the unit tests can import `.svelte.ts` modules.
import { register } from "node:module";
register("./hooks.mjs", import.meta.url);
+44
View File
@@ -0,0 +1,44 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
test("browser contributions and view updates are revoked when the plugin stops", async () => {
const registry = new ContributionRegistry();
let api!: PluginApi;
let disposed = false;
const received: string[] = [];
const session = new ExternalSession("runestone.browser", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
}, () => {}, () => {}, registry);
await session.start({ activate(value) {
api = value;
api.registerView({ id: "tab-test", title: "Browser", placement: "editor", icon: "globe", mount: () => {} });
api.registerTabDrop!(data => { received.push(data); });
api.contribute("browser", { mountSettings: () => () => {}, mountBookmarks: () => () => {}, open: async () => true });
api.onDispose(() => { disposed = true; });
} });
assert.ok(registry.get("browser"));
await session.dropTab("live-tab");
assert.deepEqual(received, ["live-tab"]);
api.updateViewTitle!("tab-test", "Example · User");
assert.equal(session.views.get("tab-test")?.title, "Example · User");
const icon = "data:image/png;base64,aW1hZ2U=";
api.updateViewIcon!("tab-test", icon);
assert.equal(session.views.get("tab-test")?.iconImage, icon);
assert.throws(() => api.updateViewIcon!("tab-test", "https://example.com/icon.png"), /Invalid/);
assert.throws(() => api.updateViewIcon!("tab-test", "data:text/html;base64,aW1hZ2U="), /Invalid/);
assert.throws(() => api.updateViewIcon!("tab-test", "data:image/png;base64," + "a".repeat(90_000)), /Invalid/);
api.updateViewIcon!("tab-test", null);
assert.equal(session.views.get("tab-test")?.iconImage, null);
await session.stop();
assert.equal(registry.get("browser"), undefined);
assert.equal(disposed, true);
assert.throws(() => api.updateViewTitle!("tab-test", "Other"), /disabled/);
assert.throws(() => api.updateViewIcon!("tab-test", icon), /disabled/);
await assert.rejects(session.dropTab("closed-tab"), /disabled/);
assert.throws(() => api.registerTabDrop!(() => {}), /disabled/);
assert.deepEqual(received, ["live-tab"]);
});
+17
View File
@@ -0,0 +1,17 @@
import test from "node:test";
import assert from "node:assert/strict";
import { SearchQuery } from "@codemirror/search";
import { documentMatches } from "../../../src/lib/editor/findTarget.ts";
test("document search uses Writer word matching and normalized CRLF positions", () => {
const query = new SearchQuery({ search: "Alpha", wholeWord: true, caseSensitive: true });
const { state, matches } = documentMatches("Alpha alphabet\r\nalpha Alpha", query);
assert.deepEqual(matches.map(({ from, to }) => ({ from, to })), [{ from: 0, to: 5 }, { from: 21, to: 26 }]);
assert.equal(state.doc.lineAt(matches[1].from).number, 2);
assert.equal(state.doc.lineAt(matches[1].from).from, 15);
});
test("empty and invalid queries do not produce matches", () => {
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "" })).matches, []);
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "[", regexp: true })).matches, []);
});
+33
View File
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import test from "node:test";
import MarkdownIt from "markdown-it";
import { footnotes, renderFootnotes } from "../../../src/lib/editor/footnotes.ts";
function render(source: string) {
const markdown = new MarkdownIt({ html: false }).use(footnotes);
const env = {};
return markdown.render(source, env) + renderFootnotes(markdown, env);
}
test("footnotes use first-reference order, repeated backlinks, and rich multiline definitions", () => {
const html = render("First[^b], then[^a], again[^b].\n\n[^a]: Second definition\n[^b]: **Bold** text\n continued\n\n Second paragraph.\n");
assert.match(html, /id="rs-fnref-1-1"/);
assert.match(html, /id="rs-fnref-1-2"/);
assert.match(html, /<strong>Bold<\/strong> text\ncontinued/);
assert.match(html, /<p>Second paragraph\.<\/p>/);
assert.ok(html.indexOf('<li id="rs-fn-1"') < html.indexOf('<li id="rs-fn-2"'));
assert.match(html, /href="#rs-fnref-1-2"/);
});
test("undefined, escaped, inline-code, fenced-code, and indented-code references stay literal", () => {
const html = render("Missing[^missing]. Escaped\\[^n]. `[^n]`\n\n```md\n[^n]\n```\n\n [^n]\n\n[^n]: Unused\n");
assert.doesNotMatch(html, /md-footnotes|md-footnote-ref/);
assert.match(html, /Missing\[\^missing\]/);
});
test("footnotes keep HTML escaped and support CRLF", () => {
const html = render("Body[^x]\r\n\r\n[^x]: <script>alert(1)</script>\r\n");
assert.match(html, /&lt;script&gt;/);
assert.doesNotMatch(html, /<script>/);
assert.match(html, /Footnote 1/);
});
+17
View File
@@ -0,0 +1,17 @@
import assert from "node:assert/strict";
import test from "node:test";
import { htmlToMarkdown } from "../../../src/lib/workspace/htmlToMarkdown.ts";
test("Windows HTML clipboard fragment comments do not become table content", () => {
const html = '<html><body><!--StartFragment--><table><tr><th>Ticker</th><th>Name</th></tr><tr><td>ADBE.US</td><td>Adobe</td></tr><tr><td>ADSK.US</td><td>Autodesk</td></tr></table><!--EndFragment--></body></html>';
assert.equal(htmlToMarkdown(html), '| Ticker | Name |\n| --- | --- |\n| ADBE.US | Adobe |\n| ADSK.US | Autodesk |');
});
test("comments inside cells preserve adjacent text and formatting", () => {
const html = '<table><tr><th>Notes</th></tr><tr><td>First<!-- multi-line\n <b>comment</b> --> part<br><strong>Second</strong></td></tr></table>';
assert.equal(htmlToMarkdown(html), '| Notes |\n| --- |\n| First part<br>**Second** |');
});
test("escaped comment text remains user content", () => {
assert.equal(htmlToMarkdown('<p>&lt;!--Example--&gt;</p>'), '<!--Example-->');
});
+32
View File
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import test from "node:test";
import { estimatedImageHeight, imageSize, rememberImageSize } from "../../../src/lib/workspace/imageSizes.ts";
import { renderMarkdownHtml } from "../../../src/lib/workspace/noteHtml.ts";
test("a rendered image has size attributes only when its size is known", () => {
const unknown = "data:image/png;base64,AAAA";
const known = "data:image/png;base64,BBBB";
rememberImageSize(known, 1400, 700);
const urls = new Map([["a.png", unknown], ["b.png", known]]);
assert.doesNotMatch(renderMarkdownHtml("![a](a.png)", urls), /width=/);
assert.match(renderMarkdownHtml("![b](b.png)", urls), /width="1400" height="700"/);
});
test("a large data URL keeps its size without the image data as the key", () => {
const url = `data:image/png;base64,${"A".repeat(5000)}${"B".repeat(100)}${"C".repeat(5000)}`;
const other = `data:image/png;base64,${"A".repeat(5000)}${"D".repeat(100)}${"C".repeat(5000)}`;
rememberImageSize(url, 10, 20);
assert.deepEqual(imageSize(url), { width: 10, height: 20 });
assert.equal(imageSize(other), undefined);
});
test("an image without a real size stays unknown", () => {
rememberImageSize("data:image/svg+xml;base64,AAAA", 0, 0);
assert.equal(imageSize("data:image/svg+xml;base64,AAAA"), undefined);
});
test("the estimate scales a wide image to the text column and keeps a small image", () => {
assert.equal(estimatedImageHeight('<img src="x" alt="">'), -1);
assert.equal(estimatedImageHeight('<img width="1480" height="740">'), 370 + 45);
assert.equal(estimatedImageHeight('<img width="100" height="50">'), 50 + 45);
});
+101
View File
@@ -0,0 +1,101 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { attachmentRel, dataUrlExtension, hasFileDrag, imageFiles, imageInsertion, mayAnimate, pastedImageSource, workspaceImageLink } from "../../../src/lib/workspace/media.ts";
import { copiedImage, keepCopiedImage } from "../../../src/lib/workspace/copiedImage.ts";
import { imageSource, editImageSource, imageSourceRanges } from "../../../src/lib/editor/imageSource.ts";
import { imageDrops, trackImageDrop } from "../../../src/lib/editor/imageDrop.ts";
test("same-name image imports receive distinct safe attachment paths", () => {
const paths = new Set(Array.from({ length: 100 }, () => attachmentRel("photo (1).PNG")));
assert.equal(paths.size, 100);
assert.ok([...paths].every(path => /^attachments\/[\w.-]+\.PNG$/.test(path)));
});
test("protected file drags and files without MIME metadata are recognized", () => {
assert.equal(hasFileDrag({ types: ["Files"], files: [] } as unknown as DataTransfer), true);
assert.equal(hasFileDrag({ types: ["text/plain"] } as unknown as DataTransfer), false);
const files = [{ name: "PHOTO.PNG", type: "" }, { name: "note.md", type: "text/plain" }];
assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]);
});
test("a copied web image names its original file in the clipboard HTML", () => {
const copy = (src: string) => `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`;
assert.equal(pastedImageSource(copy("https://media.example.com/cat.gif")), "https://media.example.com/cat.gif");
assert.equal(pastedImageSource(copy("https://cdn.example.com/a/b.WEBP?width=200&amp;ex=1")), "https://cdn.example.com/a/b.WEBP?width=200&ex=1");
assert.equal(pastedImageSource("<img alt='x' data-src='a.png' src='http://example.com/x.avif'>"), "http://example.com/x.avif");
assert.equal(pastedImageSource("<img src=https://example.com/x.gif>"), "https://example.com/x.gif");
assert.equal(pastedImageSource(copy("https://example.com/photo.jpg")), "https://example.com/photo.jpg");
// Firefox copies the element of the page with all of its attributes.
assert.equal(pastedImageSource('<img id="img" src="https://h.example.net/om/1/x.gif" style="width:640px" onload="update()">'), "https://h.example.net/om/1/x.gif");
// A missing address and other schemes keep the clipboard copy.
assert.equal(pastedImageSource(copy("data:image/gif;base64,R0lGODlh")), undefined);
assert.equal(pastedImageSource(copy("file:///C:/cat.gif")), undefined);
assert.equal(pastedImageSource(copy("cat.gif")), undefined);
assert.equal(pastedImageSource('<img srcset="https://example.com/x.gif 1x">'), undefined);
assert.equal(pastedImageSource(""), undefined);
// A copy of a page part with two images is not a copied image.
assert.equal(pastedImageSource(copy("https://example.com/a.gif") + copy("https://example.com/b.gif")), undefined);
});
test("only formats with frames get a download, and data URLs name their extension", () => {
assert.equal(mayAnimate("https://media.example.com/cat.gif"), true);
assert.equal(mayAnimate("https://cdn.example.com/a/b.WEBP?width=200"), true);
assert.equal(mayAnimate("http://example.com/x.avif"), true);
assert.equal(mayAnimate("https://example.com/photo.jpg"), false);
assert.equal(mayAnimate("https://example.com/image?format=gif"), false);
assert.equal(dataUrlExtension("data:image/gif;base64,R0lGODlh"), "gif");
assert.equal(dataUrlExtension("data:image/jpeg;base64,/9j/"), "jpg");
assert.equal(dataUrlExtension("data:image/webp;base64,UklG"), "webp");
assert.equal(dataUrlExtension("data:image/svg+xml;base64,PHN2Zz4="), undefined);
assert.equal(dataUrlExtension("data:text/html;base64,PGh0bWw+"), undefined);
});
test("a paste uses only the original of the image that the RuneStone browser copied last", async () => {
assert.equal(await copiedImage("https://example.com/a.gif"), undefined);
let finish: (value: string) => void = () => {};
keepCopiedImage("https://example.com/a.gif", new Promise(resolve => { finish = resolve; }));
const waiting = copiedImage("https://example.com/a.gif");
finish("data:image/gif;base64,R0lGODlh");
assert.equal(await waiting, "data:image/gif;base64,R0lGODlh");
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
keepCopiedImage("https://example.com/b.gif", Promise.reject(new Error("engine stopped")));
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
assert.equal(await copiedImage("https://example.com/a.gif"), undefined, "a newer copy replaces the older one");
});
test("image batches form independent Markdown blocks without extra blank lines", () => {
assert.equal(imageInsertion("beforeafter", 6, 6, ["![](a.png)", "![](b.png)"]), "\n\n![](a.png)\n\n![](b.png)\n\n");
assert.equal(imageInsertion("before\n\nafter", 8, 8, ["![](a.png)"]), "![](a.png)\n\n");
assert.equal(imageInsertion("before\r\n\r\nafter", 10, 10, ["![](a.png)"]), "![](a.png)\n\n");
});
test("pending image drops follow intervening edits instead of the current caret", () => {
let state = EditorState.create({ doc: "before\nafter", extensions: [imageDrops] });
const id = Symbol();
state = state.update({ effects: trackImageDrop.of({ id, from: 7, to: 7 }) }).state;
state = state.update({ changes: { from: 0, insert: "new\n" }, selection: { anchor: 0 } }).state;
assert.deepEqual(state.field(imageDrops).get(id), { from: 11, to: 11 });
});
test("navigator image links are relative and encode Markdown and URL punctuation", () => {
assert.equal(workspaceImageLink("notes/drafts/note.md", "images/a (#1).png"), "![](../../images/a%20%28%231%29.png)");
assert.equal(workspaceImageLink("notes/note.md", "notes/photo.png"), "![](photo.png)");
assert.equal(workspaceImageLink("note.md", "日本語/photo%.png"), "![](%E6%97%A5%E6%9C%AC%E8%AA%9E/photo%25.png)");
});
test("image source is explicitly activated, tracks edits, and hides on leaving", () => {
let state = EditorState.create({ doc: "![](a.png)\n\nText", extensions: [imageSource] });
state = state.update({ selection: { anchor: 0, head: 10 } }).state;
assert.equal(state.field(imageSource), null);
state = state.update({ effects: editImageSource.of({ from: 0, to: 10 }) }).state;
state = state.update({ changes: { from: 2, insert: "Alt" } }).state;
assert.deepEqual(state.field(imageSource), { from: 0, to: 13 });
state = state.update({ selection: { anchor: state.doc.length } }).state;
assert.equal(state.field(imageSource), null);
});
test("image ranges distinguish embeds from code and retain reference and wiki syntax", () => {
const source = "`![](code.png)`\n\nText ![alt](<a b.png>) and ![[a b.png|Photo]]\n\n![ref][photo]\n\n[photo]: x.png\n\n```\n![](code.png)\n```";
assert.deepEqual(imageSourceRanges(source).map(range => source.slice(range.from, range.to)), ["![alt](<a b.png>)", "![[a b.png|Photo]]", "![ref][photo]"]);
});
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import test from "node:test";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { noteFormats } from "../../../src/lib/editor/noteFormats.ts";
import { renderMarkdownHtml } from "../../../src/lib/workspace/noteHtml.ts";
const parser = markdown({ base: markdownLanguage, extensions: [noteFormats] }).language.parser;
const render = (source: string) => renderMarkdownHtml(source, new Map());
function mathNodes(source: string) {
const nodes: string[] = [];
parser.parse(source).iterate({ enter(node) {
if (node.name === "NoteMath") nodes.push(source.slice(node.from, node.to));
} });
return nodes;
}
test("dollar amounts stay literal in writing, reading, and table cells", () => {
for (const source of [
"$10", "$10 and $20", "$1,234.56 plus $78.90", "$10-$20", "$0.25-$.50",
"US$10 / CA$20", "$ 10 and $ 20", "$-10 and $-20", "($10) and ($20)",
"$10\n$20", "$10\r\n$20", "$10 **income**, $20 **cost**",
]) {
assert.deepEqual(mathNodes(source), [], source);
const html = render(source);
assert.doesNotMatch(html, /md-inline-math/, source);
assert.equal((html.match(/\$/g) || []).length, (source.match(/\$/g) || []).length, source);
assert.doesNotMatch(render(`| Amounts |\n| --- |\n| ${source.replace(/\r?\n/g, "<br>")} |`), /md-inline-math/, source);
}
});
test("inline math still works next to dollar amounts", () => {
for (const expression of ["$x^2$", "$2 + 2$", "$x + y$", String.raw`$\frac{1}{2}$`, String.raw`$x + \$5$`]) {
const source = `$10 and $20, then ${expression}, then $30 and $40.`;
assert.deepEqual(mathNodes(source), [expression], source);
assert.equal((render(source).match(/md-inline-math/g) || []).length, 1, source);
assert.match(render(source), /\$10 and \$20/);
assert.match(render(source), /\$30 and \$40/);
}
});
test("escaped, incomplete, spaced, multiline, and double delimiters do not create inline math", () => {
for (const source of [String.raw`\$x\$`, "$x", "$ x$", "$x $", "$x\ny$", "$$x$$", "$$\nx\n$$", "`$x$`", "```\n$x$\n```", "$x$2"]) {
assert.deepEqual(mathNodes(source), [], source);
assert.doesNotMatch(render(source), /md-inline-math/, source);
}
});
test("highlight and comment formats keep their existing behavior", () => {
const source = "==**highlight**== %%comment%%";
const tree = parser.parse(source).toString();
assert.match(tree, /NoteHighlight/);
assert.match(tree, /StrongEmphasis/);
assert.match(tree, /NoteComment/);
assert.match(render(source), /<mark><strong>highlight<\/strong><\/mark>/);
assert.match(render(source), /md-inline-comment/);
});
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
import { languageFor } from "../../../src/lib/editor/languageFor.ts";
test("markdown files use the markdown language", () => {
assert.equal(languageFor("notes/inbox.md"), "markdown");
assert.equal(languageFor("README.markdown"), "markdown");
});
test("python and scripts use their languages", () => {
assert.equal(languageFor("src/hello.py"), "python");
assert.equal(languageFor("tools/setup.sh"), "shell");
});
test("unknown extensions are plaintext", () => {
assert.equal(languageFor("Makefile"), "plaintext");
assert.equal(languageFor("notes/data.bin"), "plaintext");
});
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import test from "node:test";
import { markdownBlocks, markdownFences } from "../../../src/lib/workspace/markdownBlocks.ts";
test("fenced block with a language is one fence", () => {
assert.deepEqual(markdownBlocks("hi\n```js\nconst x = 1\n```\nbye"), [
{ type: "text", line: "hi" },
{ type: "fence", lang: "js", body: "const x = 1" },
{ type: "text", line: "bye" },
]);
});
test("fenced block without a language keeps an empty lang", () => {
assert.deepEqual(markdownBlocks("```\nHUGE\n```"), [
{ type: "fence", lang: "", body: "HUGE" },
]);
});
test("inline backticks stay on a text line", () => {
assert.deepEqual(markdownBlocks("say `HUGE` now"), [
{ type: "text", line: "say `HUGE` now" },
]);
});
test("a fence opened and closed on one line is a fence", () => {
assert.deepEqual(markdownBlocks("```this was a triumph```"), [
{ type: "fence", lang: "", body: "this was a triumph" },
]);
});
test("closed fence body is the copy payload", () => {
assert.deepEqual(markdownFences("```js\nconst x = 1\n```"), [
{ lang: "js", body: "const x = 1", openLine: 1, closeLine: 3 },
]);
});
test("one-line fence body excludes ticks", () => {
assert.deepEqual(markdownFences("```this was a triumph```"), [
{ lang: "", body: "this was a triumph", openLine: 1, closeLine: 1 },
]);
});
test("unclosed fence is not MdFence", () => {
assert.deepEqual(markdownFences("```js\nconst x = 1\n"), []);
});
test("markdownBlocks fence body matches markdownFences", () => {
const src = "hi\n```js\nconst x = 1\n```\nbye";
const block = markdownBlocks(src).find((row) => row.type === "fence");
const fence = markdownFences(src)[0];
assert.equal(block && block.type === "fence" ? block.body : null, "const x = 1");
assert.equal(fence.body, "const x = 1");
assert.equal(fence.lang, "js");
assert.equal(fence.openLine, 2);
assert.equal(fence.closeLine, 4);
});
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatText, paragraphText, insertBlock, type MarkdownEdit, type InlineFormat } from "../../../src/lib/editor/markdownCommands.ts";
const apply = (source: string, edit: MarkdownEdit) => source.slice(0, edit.from) + edit.insert + source.slice(edit.to);
test("inline formatting toggles without losing surrounding prose or the selected text", () => {
for (const format of ["bold", "italic", "strike", "highlight", "code", "math", "comment"] as InlineFormat[]) {
const source = "before words after", selection = { from: 7, to: 12 };
const edit = formatText(source, selection, format), changed = apply(source, edit);
assert.equal(changed.slice(edit.anchor, edit.head), "words");
assert.equal(apply(changed, formatText(changed, { from: edit.anchor, to: edit.head }, format)), source, format);
assert.equal(apply(changed, formatText(changed, { from: edit.from, to: edit.from + edit.insert.length }, format)), source, format);
}
assert.equal(apply("word ", formatText("word ", { from: 0, to: 5 }, "bold")), "**word** ");
assert.equal(apply("**bold**", formatText("**bold**", { from: 0, to: 8 }, "italic")), "***bold***");
const empty = formatText("", { from: 0, to: 0 }, "bold");
assert.equal(empty.insert, "****"); assert.equal(empty.anchor, 2); assert.equal(empty.head, 2);
});
test("code delimiters survive backticks and clear formatting preserves literal punctuation and newlines", () => {
const source = "a ` b", edit = formatText(source, { from: 0, to: source.length }, "code");
assert.equal(edit.insert, "``a ` b``");
assert.equal(apply(edit.insert, formatText(edit.insert, { from: edit.anchor, to: edit.head }, "code")), source);
assert.equal(apply(edit.insert, formatText(edit.insert, { from: 0, to: edit.insert.length }, "code")), source);
const rich = "**bold**\r\n==mark== and \\*literal\\*";
assert.equal(formatText(rich, { from: 0, to: rich.length }, "clear").insert, "bold\r\nmark and \\*literal\\*");
assert.equal(apply("***bold***", formatText("***bold***", { from: 3, to: 7 }, "clear")), "bold");
});
test("paragraph commands cover selected lines, omit an unselected next line, and preserve indentation and CRLF", () => {
const source = "before\r\n - [x] first\r\n 2. second\r\nafter";
const selected = { from: source.indexOf("first"), to: source.indexOf("after") };
assert.equal(apply(source, paragraphText(source, selected, 3)), "before\r\n ### first\r\n ### second\r\nafter");
assert.equal(apply(source, paragraphText(source, selected, "body")), "before\r\n first\r\n second\r\nafter");
assert.equal(paragraphText("one\ntwo\n\nthree", { from: 0, to: 14 }, "number").insert, "1. one\n2. two\n\n1. three");
assert.equal(paragraphText("", { from: 0, to: 0 }, "task").insert, "- [ ] ");
assert.equal(apply("one\ntwo", paragraphText("one\ntwo", { from: 4, to: 4 }, "quote")), "one\n> two");
});
test("block inserts retain adjacent text, escape code fences, and select editable placeholders", () => {
const source = "left right", selection = { from: 5, to: 10 };
for (const kind of ["table", "rule"] as const) {
const result = apply(source, insertBlock(source, selection, kind));
assert.ok(result.startsWith(source + "\n\n"));
}
const code = insertBlock("```", { from: 0, to: 3 }, "code");
assert.equal(code.insert, "````\n```\n````\n\n");
const table = insertBlock("", { from: 0, to: 0 }, "table");
assert.equal(table.insert.slice(table.anchor, table.head), "Column 1");
assert.equal(insertBlock("a\r\nb", { from: 3, to: 4 }, "callout").insert, "\r\n> [!note]\r\n> b\r\n\r\n");
});
test("footnotes get unique references, retain the document tail, and select the definition", () => {
const source = "One[^1] and words.\n\n[^1]: existing\n";
const from = source.indexOf("words"), edit = insertBlock(source, { from, to: from + 5 }, "footnote");
const changed = apply(source, edit);
assert.equal(changed, "One[^1] and [^2].\n\n[^1]: existing\n\n[^2]: words\n");
assert.equal(changed.slice(edit.anchor, edit.head), "words");
});
+90
View File
@@ -0,0 +1,90 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { indentUnit } from "@codemirror/language";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { noteFormats } from "../../../src/lib/editor/noteFormats.ts";
import { indentListItems, listLabels, orderedLabel, outdentListItems } from "../../../src/lib/editor/markdownLists.ts";
const extensions = [markdown({ base: markdownLanguage, extensions: [noteFormats] }), indentUnit.of(" ")];
/** A document with `|` at the caret, or two `|` around a selection. */
function editor(marked: string) {
const anchor = marked.indexOf("|"), head = marked.indexOf("|", anchor + 1);
const doc = marked.replaceAll("|", "");
return EditorState.create({ doc, selection: { anchor, head: head < 0 ? anchor : head - 1 }, extensions });
}
function run(move: typeof indentListItems, marked: string) {
const state = editor(marked), specs = move(state);
if (!specs) return null;
const next = state.update(...specs).state;
const { from, to } = next.selection.main;
const doc = next.doc.toString();
return from === to ? doc.slice(0, from) + "|" + doc.slice(from) : doc.slice(0, from) + "|" + doc.slice(from, to) + "|" + doc.slice(to);
}
test("tab makes a nested list and renumbers the items after it", () => {
assert.equal(run(indentListItems, "1. Topic\n2. B|\n3. A"), "1. Topic\n 1. B|\n2. A");
});
test("tab on an empty item keeps the caret after its marker", () => {
assert.equal(run(indentListItems, "1. Topic\n2.|\n3. A"), "1. Topic\n 1.|\n2. A");
assert.equal(run(indentListItems, "1. Topic\n2. |\n3. A"), "1. Topic\n 1. |\n2. A");
});
test("tab adds the item to the nested list of the previous item", () => {
assert.equal(run(indentListItems, "1. A\n 1. x\n2. B|\n3. C"), "1. A\n 1. x\n 2. B|\n2. C");
});
test("tab moves the children of an item with it", () => {
assert.equal(run(indentListItems, "1. A\n2. B|\n 1. b\n3. C"), "1. A\n 1. B|\n 1. b\n2. C");
});
test("tab nests each selected item under the first unselected item", () => {
assert.equal(run(indentListItems, "1. A\n|2. B\n3. C|\n4. D"), "1. A\n| 1. B\n 2. C|\n2. D");
});
test("tab nests bullet items and keeps their marker", () => {
assert.equal(run(indentListItems, "- a\n- b|"), "- a\n - b|");
assert.equal(run(indentListItems, "- [ ] a\n- [x] b|"), "- [ ] a\n - [x] b|");
});
test("tab keeps the first item in place and ignores text outside lists", () => {
assert.deepEqual(indentListItems(editor("1. A|\n2. B")), []);
assert.equal(indentListItems(editor("Plain| text")), null);
assert.equal(indentListItems(editor("1. A\n\n ```\n co|de\n ```")), null);
});
test("shift+tab moves a nested item up and makes the later items its children", () => {
assert.equal(run(outdentListItems, "1. A\n 1. x\n 2. y|\n 3. z\n2. B"), "1. A\n 1. x\n2. y|\n 1. z\n3. B");
});
test("shift+tab gives the item the marker style of the outer list", () => {
assert.equal(run(outdentListItems, "1. A\n - x|\n2. B"), "1. A\n2. x|\n3. B");
assert.equal(run(outdentListItems, "- A\n 1. x|\n- B"), "- A\n- x|\n- B");
});
test("shift+tab keeps a top-level item in place", () => {
assert.deepEqual(outdentListItems(editor("1. A|\n2. B")), []);
assert.equal(outdentListItems(editor("Plain| text")), null);
});
test("ordered labels use numbers, letters, and Roman numerals by level", () => {
assert.equal(orderedLabel(1, 3), "3");
assert.equal(orderedLabel(2, 1), "a");
assert.equal(orderedLabel(2, 27), "aa");
assert.equal(orderedLabel(3, 4), "iv");
assert.equal(orderedLabel(4, 2), "2");
assert.equal(orderedLabel(2, 0), "0");
});
test("nested ordered markers get labels and the first level keeps its source", () => {
const state = editor("1. A\n 1. x\n 1. y\n 1. z\n2. B|");
assert.deepEqual(listLabels(state).map(label => [state.sliceDoc(label.from, label.to), label.label]), [["1.", "a."], ["1.", "b."], ["1.", "i."]]);
});
test("an empty nested marker gets its label before the item has text", () => {
const state = editor("1. Topic\n 1.\n2. A|");
assert.deepEqual(listLabels(state).map(label => label.label), ["a."]);
});
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
findMarkdownImages,
isImagePath,
isRemoteImage,
resolveImageRel,
} from "../../../src/lib/workspace/media.ts";
test("image paths are detected by extension", () => {
assert.equal(isImagePath("screenshot.png"), true);
assert.equal(isImagePath("notes/photo.JPEG"), true);
assert.equal(isImagePath("notes/inbox.md"), false);
});
test("markdown image syntax is parsed", () => {
const found = findMarkdownImages("See ![alt](../shot.png) and ![[screenshot.png|Hero]]");
assert.equal(found.length, 2);
assert.equal(found[0].src, "../shot.png");
assert.equal(found[0].kind, "md");
assert.equal(found[1].src, "screenshot.png");
assert.equal(found[1].alt, "Hero");
assert.equal(found[1].kind, "wiki");
});
test("image paths resolve from the note folder", () => {
assert.equal(resolveImageRel("notes/inbox.md", "pic.png"), "notes/pic.png");
assert.equal(resolveImageRel("notes/inbox.md", "../screenshot.png"), "screenshot.png");
assert.equal(resolveImageRel("notes/inbox.md", "screenshot.png"), "notes/screenshot.png");
assert.equal(resolveImageRel("notes/inbox.md", "/assets/pic.png"), "assets/pic.png");
});
test("remote images stay as URLs", () => {
assert.equal(isRemoteImage("https://example.com/a.png"), true);
assert.equal(isRemoteImage("screenshot.png"), false);
});
+60
View File
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import test from "node:test";
import { htmlToMarkdown } from "../../../src/lib/workspace/htmlToMarkdown.ts";
test("headings and inline marks become markdown", () => {
const html =
"<h1>Heading 1</h1><h2>Heading 2</h2><p>hello <strong>bold</strong> and <code>code</code></p>";
assert.equal(htmlToMarkdown(html), "# Heading 1\n## Heading 2\nhello **bold** and `code`");
});
test("fences keep language and body", () => {
const html = '<pre class="md-code" data-lang="js"><code class="language-js">const x = 1</code></pre>';
assert.equal(htmlToMarkdown(html), "```js\nconst x = 1\n```");
});
test("wiki and markdown links become markdown", () => {
const html =
'<p>see <a class="wiki" href="projects/alpha" data-kind="wiki">projects/alpha</a> and <a href="notes/a.md" data-kind="md">label</a></p>';
assert.equal(htmlToMarkdown(html), "see [[projects/alpha]] and [label](notes/a.md)");
});
test("wiki image uses data-md-kind", () => {
const html =
'<p><img src="data:image/png;base64,xx" alt="screenshot.png" data-md-src="screenshot.png" data-md-kind="wiki" /></p>';
assert.equal(htmlToMarkdown(html), "![[screenshot.png]]");
});
test("strike super and sub become markdown", () => {
const html = "<p><s>old</s> x<sup>2</sup> a<sub>n</sub></p>";
assert.equal(htmlToMarkdown(html), "~~old~~ x^2^ a~n~");
});
test("gfm table becomes markdown", () => {
const html =
"<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table>";
assert.equal(htmlToMarkdown(html), "| A | B |\n| --- | --- |\n| 1 | 2 |");
});
test("checked task item becomes a checkbox line", () => {
const html =
'<ul data-type="taskList"><li data-type="taskItem" data-checked="true"><p>done</p></li></ul>';
assert.equal(htmlToMarkdown(html), "- [x] done");
});
test("unchecked task item becomes an empty checkbox", () => {
const html =
'<ul data-type="taskList"><li data-type="taskItem" data-checked="false"><p>todo</p></li></ul>';
assert.equal(htmlToMarkdown(html), "- [ ] todo");
});
test("italic highlight math and comment become markdown", () => {
const html =
'<p><em>hi</em> <mark>glow</mark> <span data-math="1">x^2</span> <span data-comment="1">note</span></p>';
assert.equal(htmlToMarkdown(html), "*hi* ==glow== $x^2$ %%note%%");
});
test("blockquote and numbered list become markdown", () => {
const html = "<blockquote><p>said</p></blockquote><ol><li>one</li><li>two</li></ol>";
assert.equal(htmlToMarkdown(html), "> said\n1. one\n2. two");
});
+103
View File
@@ -0,0 +1,103 @@
import assert from "node:assert/strict";
import test from "node:test";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections } from "../../../src/lib/workspace/noteHtml.ts";
const render = (text: string) => renderMarkdownHtml(text, new Map());
test("writing sections retain exact source ranges and document-wide references", () => {
const source = '\uFEFF---\r\ntitle: Draft\r\n---\r\n\r\n# Heading\r\n\r\n- Parent\r\n - Child\r\n\r\nA [reference][ref].\r\n\r\n[ref]: https://example.com\r\n';
const sections = renderMarkdownSections(source, new Map());
assert.equal(sections.map(section => source.slice(section.start, section.end)).join(""), source);
assert.equal(sections.length, 4);
assert.match(sections[2].html, /<ul>[\s\S]*<ul>/);
assert.match(sections[3].html, /href="https:\/\/example.com"/);
const paragraph = sections[3];
const edited = source.slice(0, paragraph.start) + 'Changed paragraph.\r\n' + source.slice(paragraph.end);
assert.equal(edited.slice(0, paragraph.start), source.slice(0, paragraph.start));
});
test("writing exposes empty and reference-only documents for editing", () => {
for (const source of ["", "\n\n", "[ref]: https://example.com\n"]) {
assert.deepEqual(renderMarkdownSections(source, new Map()), [{ start: 0, end: source.length, html: "" }]);
}
});
test("Mermaid fences render diagram containers with escaped, copyable source", () => {
const html = render('```mermaid\nflowchart LR\n A["<script>bad</script>"] --> B\n```');
assert.match(html, /class="md-mermaid"/);
assert.match(html, /aria-label="Mermaid diagram"/);
assert.match(html, /<summary>Diagram source<\/summary>/);
assert.match(html, /&lt;script&gt;bad&lt;\/script&gt;/);
assert.doesNotMatch(html, /<script>/);
assert.doesNotMatch(render('```js\nconst x = 1;\n```'), /md-mermaid/);
});
test("reader joins soft-wrapped lines and preserves paragraph boundaries", () => {
assert.equal(render("First line\ncontinues here.\n\nSecond paragraph."), "<p>First line\ncontinues here.</p>\n<p>Second paragraph.</p>\n");
assert.match(render("Hard break \nnext line"), /Hard break<br>\nnext line/);
});
test("reader preserves nested lists, ordered starts and multi-paragraph items", () => {
const html = render("7. Parent\n - Nested **item**\n - Other\n8. Next\n\n Another paragraph.\n");
assert.match(html, /<ol start="7">/);
assert.match(html, /<li>\n<p>Parent<\/p>\n<ul>\n<li>Nested <strong>item<\/strong><\/li>/);
assert.match(html, /<p>Next<\/p>\n<p>Another paragraph\.<\/p>/);
});
test("reader renders aligned tables and read-only nested tasks", () => {
const html = render("| Left | Right |\n| :--- | ---: |\n| **a** | 2 |\n\n- [x] Done\n - [ ] Nested\n");
assert.match(html, /class="md-table-scroll"><table>/);
assert.match(html, /<th style="text-align:right">Right<\/th>/);
assert.equal((html.match(/type="checkbox" disabled/g) || []).length, 2);
assert.equal((html.match(/ checked>/g) || []).length, 1);
assert.doesNotMatch(html, /\[x\]|\[ \]/);
});
test("reader keeps code literal and escapes embedded HTML", () => {
const html = render('```js\nconst text = "[[note]] **bold** <script>alert(1)</script>";\n```\n\n`[[literal]]`\n\n<img src=x onerror=alert(1)>');
assert.match(html, /aria-label="Copy code"/);
assert.match(html, /\[\[note\]\] \*\*bold\*\* &lt;script&gt;/);
assert.match(html, /<code>\[\[literal\]\]<\/code>/);
assert.doesNotMatch(html, /<script>|<img|class="wiki"|<strong>/);
});
test("table cell line breaks render without enabling arbitrary HTML", () => {
const html = render('| Notes |\n| --- |\n| First<br>Second<BR />Third<br/>Fourth |');
assert.match(html, /First<br>\nSecond<br>\nThird<br>\nFourth/);
assert.doesNotMatch(html, /&lt;br/i);
assert.match(render('`<br>`'), /<code>&lt;br&gt;<\/code>/);
assert.doesNotMatch(render('<br onclick="alert(1)">'), /<br /);
});
test("frontmatter is collapsed separately from document headings", () => {
const html = render("\uFEFF---\r\ntitle: Notes\r\ntags: [work]\r\n---\r\n# Document\n");
assert.match(html, /^<details class="md-properties"><summary>Properties<\/summary><pre>title: Notes/);
assert.match(html, /<h1>Document<\/h1>/);
assert.doesNotMatch(html, /<h2>|<hr>|details[^>]*open/);
assert.match(render("---\n\nOrdinary rule"), /^<hr>/);
});
test("wiki links, aliases and reference images retain their targets", () => {
const source = 'See [[notes/one|First note]] and [second](second.md).\n\n![A **diagram**][diagram]\n\n![[assets/screenshot.png|Screenshot]]\n\n[diagram]: assets/my%20diagram.png "Diagram"\n';
const urls = new Map([['assets/my%20diagram.png', 'data:image/png;base64,AA=='], ['assets/screenshot.png', 'data:image/png;base64,BB==']]);
const html = renderMarkdownHtml(source, urls);
assert.match(html, /href="notes\/one" data-kind="wiki" class="wiki">First note/);
assert.match(html, /href="second.md" data-kind="md"/);
assert.match(html, /alt="A diagram"/);
assert.match(html, /data-md-kind="wiki"/);
assert.deepEqual(markdownImages(source + '\n`![[ignored.png]]`\n\n```\n![also ignored](x.png)\n```'), ['assets/my%20diagram.png', 'assets/screenshot.png']);
});
test("reader rejects executable links and image URL injection", () => {
const html = render('[bad](javascript:alert%281%29) [[javascript:alert(1)]] ![bad](javascript:alert%281%29)');
assert.doesNotMatch(html, /<a |<img /);
const image = renderMarkdownHtml('![[safe.png]]', new Map([['safe.png', 'javascript:alert(1)']]));
assert.match(image, /Image unavailable/);
});
test("note callouts separate their title from the Markdown body", () => {
const html = render('> [!tip] Keep context close\n> Use **notes** beside code.\n>\n> A second paragraph.');
assert.match(html, /class="md-callout" data-callout="tip"/);
assert.match(html, /class="md-callout-title">Keep context close<\/strong>Use <strong>notes<\/strong>/);
assert.match(html, /<p>A second paragraph\.<\/p>/);
});
+456
View File
@@ -0,0 +1,456 @@
// The Background feature: the engine (ported from the Background Slideshow plugin), the per-image settings,
// the sources, the settings section, the launch rule, and the first-start migration.
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_BACKGROUND, hasBackgroundSource, migrateBackground, normalizeBackground, normalizeLayout, type BackgroundMigrationHost, type BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
import { LAUNCH_RULES, launchWanted, runsInWindow } from "../../../src/lib/features/launch.ts";
import { BLUR_CACHE, RESCAN_SLIDES, Slideshow, transitionMs, type EngineSettings, type ImageSource, type Runtime } from "../../../src/lib/features/background/engine.ts";
import { imageAppearance, imageNames, parseImageSettings, sequence } from "../../../src/lib/features/background/imageSettings.ts";
import { folderSource, imageSource, readSavedImage } from "../../../src/lib/features/background/sources.ts";
import type { LegacyPlugin } from "../../../src/lib/features/migration.ts";
import type { BackgroundFrame } from "../../../src/lib/plugins/backgroundContracts.ts";
const settle = () => new Promise(resolve => setImmediate(resolve));
const on: EngineSettings = { ...normalizeBackground({ source: "folder", seconds: 3, targets: ["app", "pm-all"] }) };
function fixture({ width = 200, height = 100 } = {}) {
const frames = new Map<string, BackgroundFrame>();
const released: string[] = [];
const reads: string[] = [];
const counts = { list: 0, sidecar: 0, blur: 0 };
let names = ["2.png", "1.png", "10.png"];
let sidecar: string | null = null;
let serial = 0;
let scheduled: { callback: () => void; delay: number } | undefined;
const source = (key = "folder:D:\\Pictures"): ImageSource => ({
key, timed: true,
list: async () => { counts.list++; return names; },
read: async name => { reads.push(name); return new Blob([name]); },
sidecar: async () => { counts.sidecar++; return sidecar; },
});
const runtime: Runtime = {
load: async blob => ({ url: `blob:${await blob.text()}-${serial++}`, width, height }),
blur: async image => { counts.blur++; return `${image.url}-blur`; },
release: url => { released.push(url); },
later: (callback, delay) => { scheduled = { callback, delay }; return scheduled; },
cancel: () => { scheduled = undefined; },
random: () => 0,
now: () => 0,
};
const engine = new Slideshow({ set: (target, frame) => { if (frame) frames.set(target, frame); else frames.delete(target); } }, runtime);
return {
engine, frames, released, reads, counts, runtime, source,
names: (value: string[]) => { names = value; },
sidecar: (value: string | null) => { sidecar = value; },
scheduled: () => scheduled,
/** Run the timer, then let the read of the next prepared image finish. */
tick: async () => { await scheduled!.callback(); await settle(); await settle(); },
};
}
test("settings and names normalize, and the order is natural", () => {
assert.equal(normalizeBackground({ seconds: NaN }).seconds, 60);
assert.equal(normalizeBackground({ seconds: -2 }).seconds, 1);
assert.equal(normalizeBackground({ seconds: 1e9 }).seconds, 86400);
assert.equal(normalizeBackground({ overlay: Infinity }).overlay, 0);
assert.equal(normalizeBackground({ overlay: -3 }).overlay, -1);
assert.deepEqual(normalizeBackground({ targets: ["app", "app", "bogus", "pm-board:../x", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"] }).targets, ["app", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"]);
assert.deepEqual(normalizeBackground(null), { ...DEFAULT_BACKGROUND, targets: ["app"] });
assert.deepEqual(normalizeBackground({ source: "web", order: "shuffle", paused: "yes", position: "middle", size: "100px" }), { ...DEFAULT_BACKGROUND, targets: ["app"] });
assert.deepEqual(normalizeLayout({ overlay: 0.5, position: "top left", size: "auto" }), { overlay: 0.5, position: "top left", size: "auto" });
assert.deepEqual(imageNames(["10.png", "2.png", "README.md", "../bad.png", "2.png", "a.JPEG"]), ["2.png", "10.png", "a.JPEG"]);
assert.deepEqual(sequence(["a", "b", "c"], "b", "name"), ["c", "a", "b"]);
assert.notEqual(sequence(["a", "b", "c"], "a", "random", () => 0)[0], "a");
assert.deepEqual(sequence(["a"], "a", "random"), ["a"]);
});
test("a folder rotates, shows one frame on every target, and a pause keeps the current image", async () => {
const f = fixture();
await f.engine.configure(f.source(), { ...on, overlay: -0.4, position: "top left", size: "contain" });
assert.equal(f.engine.status.image, "1.png");
assert.equal(f.scheduled()!.delay, 3000);
assert.equal(f.frames.get("app")!.overlay, -0.4);
assert.equal(f.frames.get("app")!.size, "contain");
assert.deepEqual(f.frames.get("app"), f.frames.get("pm-all"));
await f.tick();
assert.equal(f.engine.status.image, "2.png");
await f.engine.next();
assert.equal(f.engine.status.image, "10.png");
await f.engine.configure(f.source(), { ...on, paused: true });
assert.equal(f.engine.status.image, "10.png", "A pause keeps the image.");
assert.equal(f.scheduled(), undefined, "A pause has no timer.");
assert.equal(f.frames.size, 2);
await f.engine.next();
assert.equal(f.engine.status.image, "1.png", "Next works during a pause.");
assert.equal(f.scheduled(), undefined);
await f.engine.configure(null, on);
assert.equal(f.frames.size, 0, "Without a source, the frames go away.");
f.engine.dispose();
});
test("unreadable images are skipped, and an empty folder tries again", async () => {
const f = fixture();
const read = f.source();
const source: ImageSource = { ...read, read: async name => { if (name === "1.png") throw new Error("removed"); return read.read(name); } };
await f.engine.configure(source, on);
assert.equal(f.engine.status.image, "2.png");
assert.match(f.engine.status.message, /skipped 1/);
f.names([]);
f.engine.invalidate();
await f.engine.next();
assert.equal(f.frames.size, 0);
assert.equal(f.engine.status.error, true);
assert.equal(f.scheduled()!.delay, 5000);
f.names(["restored.png"]);
f.engine.invalidate();
await f.tick();
assert.equal(f.engine.status.image, "restored.png");
f.engine.dispose();
});
test("both images of a fade stay alive, and each image is released once", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
const first = f.frames.get("app")!;
assert.equal(first.previous, undefined);
await f.engine.next(); await settle();
const second = f.frames.get("app")!;
assert.deepEqual(second.previous, first);
assert.equal(second.transitionMs, transitionMs);
assert.equal(f.released.length, 0);
await f.engine.next(); await settle();
const third = f.frames.get("app")!;
assert.deepEqual(third.previous, { url: second.url, overlay: 0, position: "center", size: "cover" });
assert.deepEqual(f.released, [first.url]);
f.engine.dispose();
await settle();
assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice.");
for (const url of [first.url, second.url, third.url]) assert.ok(f.released.includes(url), url);
});
test("a settings change keeps the current image and applies the new layout without a fade", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
const first = f.frames.get("app")!;
await f.engine.configure(f.source(), { ...on, overlay: 0.4, position: "bottom", targets: ["app"] });
const changed = f.frames.get("app")!;
assert.equal(changed.url, first.url);
assert.equal(changed.overlay, 0.4);
assert.equal(changed.position, "bottom");
assert.equal(changed.previous, undefined);
assert.equal(f.frames.has("pm-all"), false, "A removed target loses its frame.");
assert.equal(f.engine.status.image, "1.png");
assert.deepEqual(f.released, []);
f.engine.dispose();
});
test("the next image is read and decoded before its fade", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
await settle(); await settle();
assert.deepEqual(f.reads, ["1.png", "2.png"], "The next image loads after the current one shows.");
await f.tick();
assert.equal(f.engine.status.image, "2.png");
assert.deepEqual(f.reads, ["1.png", "2.png", "10.png"], "The timer used the prepared image without a new read.");
// A change of order drops the prepared image when the folder no longer has it.
f.names(["1.png", "2.png"]);
f.engine.invalidate();
await f.tick();
assert.equal(f.engine.status.image, "1.png");
assert.ok(f.released.some(url => url.startsWith("blob:10.png")), "The unused prepared image is released.");
f.engine.dispose();
});
test("a missing folder shows an error, and the folder recovers on the next try", async () => {
const f = fixture();
const missing: ImageSource = { ...f.source(), list: async () => { throw new Error("The background folder is missing. Choose the folder again."); } };
await f.engine.configure(missing, on);
assert.equal(f.engine.status.error, true);
assert.match(f.engine.status.message, /Choose the folder again/);
assert.equal(f.frames.size, 0);
await f.engine.configure(f.source("folder:D:\\Other"), on);
assert.equal(f.engine.status.error, false);
assert.equal(f.engine.status.image, "1.png");
f.engine.dispose();
});
test("a host failure clears the published targets and releases every image", async () => {
const f = fixture();
let fail = false;
const engine = new Slideshow({ set: (target, frame) => {
if (fail && target === "pm-all" && frame) throw new Error("Background access ended.");
if (frame) f.frames.set(target, frame); else f.frames.delete(target);
} }, f.runtime);
await engine.configure(f.source(), on);
await engine.next(); await settle();
fail = true;
await engine.next(); await settle();
assert.equal(engine.status.error, true);
assert.equal(f.frames.size, 0);
assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice.");
assert.ok(f.released.length >= 3);
engine.dispose();
});
test("another source starts again, and a late read of the old source is ignored", async () => {
const f = fixture();
let resolve!: (value: string[]) => void;
const slow: ImageSource = { ...f.source("folder:D:\\Slow"), list: () => new Promise(done => { resolve = done; }) };
const pending = f.engine.configure(slow, on);
await settle();
await f.engine.configure(f.source("folder:D:\\Other"), on);
const current = f.frames.get("app")!.url;
resolve(["stale.png"]);
await pending;
assert.equal(f.frames.get("app")!.url, current);
assert.equal(f.engine.status.image, "1.png");
f.engine.dispose();
});
test("the list and the sidecar are read again only after a change, a focus, or every 10 images", async () => {
const f = fixture();
await f.engine.configure(f.source(), { ...on, seconds: 1 });
assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1]);
for (let index = 1; index < RESCAN_SLIDES; index++) await f.tick();
assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1], "Nine timer images read nothing again.");
await f.tick();
assert.deepEqual([f.counts.list, f.counts.sidecar], [2, 2], "The eleventh image reads the folder again.");
f.engine.invalidate();
await f.tick();
assert.deepEqual([f.counts.list, f.counts.sidecar], [3, 3], "A focus reads it again.");
await f.engine.configure(f.source(), { ...on, seconds: 2 });
assert.deepEqual([f.counts.list, f.counts.sidecar], [4, 4], "A settings change reads it again.");
f.engine.dispose();
});
test("a late image after disposal is released and never published", async () => {
const f = fixture();
let resolve!: (value: { url: string; width: number; height: number }) => void;
f.runtime.load = () => new Promise(done => { resolve = done; });
const pending = f.engine.configure(f.source(), on);
await settle(); await settle();
f.engine.dispose();
resolve({ url: "blob:late", width: 1, height: 1 });
await pending;
assert.deepEqual(f.released, ["blob:late"]);
assert.equal(f.frames.size, 0);
assert.equal(f.scheduled(), undefined);
});
test("disposal clears the targets and stops the timer", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
const timer = f.scheduled()!;
f.engine.dispose();
timer.callback();
await settle();
assert.equal(f.frames.size, 0);
assert.equal(f.scheduled(), undefined);
});
test("the image source shows one image without a timer and without the portrait default", async () => {
const f = fixture({ width: 100, height: 300 });
const image: ImageSource = { key: "image:abc", timed: false, list: async () => ["image"], read: async () => new Blob(["saved"]), sidecar: async () => { throw new Error("not asked"); } };
await f.engine.configure(image, { ...on, size: "cover" });
assert.equal(f.frames.get("app")!.size, "cover");
assert.equal(f.frames.get("app")!.blurredUrl, undefined);
assert.equal(f.scheduled(), undefined);
await f.engine.next();
assert.equal(f.frames.get("app")!.previous, undefined, "Next keeps the one image.");
assert.equal(f.counts.blur, 0);
f.engine.dispose();
});
test("the sidecar keeps file names and other data, and rejects invalid appearance", () => {
const value = { schema: 1, owner: "personal", images: { "Portrait.png": { fit: "blurred", position: "top", overlay: -0.25 } } };
assert.deepEqual(parseImageSettings(JSON.stringify(value)), value);
assert.deepEqual(parseImageSettings(null), { schema: 1, images: {} });
for (const source of ["{}", '{"schema":2,"images":{}}', '{"schema":1,"images":[]}', '{"schema":1,"images":{"../a.png":{"fit":"cover"}}}', '{"schema":1,"images":{"a.png":{"fit":"crop"}}}', '{"schema":1,"images":{"a.png":{"overlay":2}}}']) {
assert.throws(() => parseImageSettings(source), source);
}
const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const };
assert.equal(imageAppearance(layout, undefined, true).fit, "blurred");
assert.equal(imageAppearance(layout, undefined, false).fit, "auto");
assert.equal(imageAppearance(layout, { fit: "cover", position: "bottom", overlay: -0.2 }, true).fit, "cover");
});
test("a partial image override inherits every other field", () => {
const source = { schema: 1, owner: "personal", images: { "Portrait.png": { position: "top", note: "keep" }, "Other.png": {} } };
assert.deepEqual(parseImageSettings(JSON.stringify(source)), source);
const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const };
assert.deepEqual(imageAppearance(layout, { position: "top" }, false), { fit: "auto", position: "top", overlay: 0.3 });
assert.deepEqual(imageAppearance({ ...layout, size: "contain", overlay: -0.4 }, { position: "top" }, false), { fit: "contain", position: "top", overlay: -0.4 });
assert.deepEqual(imageAppearance(layout, { overlay: 0 }, true), { fit: "blurred", position: "center", overlay: 0 });
for (const value of [null, [], "cover", 1, { fit: null }, { position: "invalid" }, { overlay: "0" }, { overlay: null }]) {
assert.throws(() => parseImageSettings(JSON.stringify({ schema: 1, images: { "Image.png": value } })));
}
});
test("a partial override stays while the folder layout changes", async () => {
const f = fixture();
f.names(["A.png"]);
f.sidecar(JSON.stringify({ schema: 1, images: { "A.png": { position: "top" } } }));
await f.engine.configure(f.source(), on);
assert.equal(f.frames.get("app")!.size, "cover");
await f.engine.configure(f.source(), { ...on, size: "contain", overlay: -0.4, position: "bottom" });
assert.equal(f.frames.get("app")!.size, "contain");
assert.equal(f.frames.get("app")!.overlay, -0.4);
assert.equal(f.frames.get("app")!.position, "top");
f.engine.dispose();
});
test("a portrait image shows in full over a blurred fill that stays alive through the fade", async () => {
const f = fixture({ width: 100, height: 300 });
f.names(["A.png", "B.png"]);
await f.engine.configure(f.source(), on);
const first = f.frames.get("app")!;
assert.equal(first.size, "contain");
assert.equal(first.blurredUrl, `${first.url}-blur`);
f.sidecar(JSON.stringify({ schema: 1, images: { "B.png": { fit: "cover", position: "bottom", overlay: 0.4 } } }));
f.engine.invalidate();
await f.engine.next(); await settle();
const second = f.frames.get("app")!;
assert.equal(second.size, "cover"); assert.equal(second.position, "bottom"); assert.equal(second.overlay, 0.4);
assert.equal(second.blurredUrl, undefined);
assert.equal(second.previous!.blurredUrl, first.blurredUrl);
assert.equal(f.released.includes(first.blurredUrl!), false, "The fill of the fade stays.");
f.engine.dispose(); await settle();
for (const url of [first.url, first.blurredUrl!, second.url]) assert.ok(f.released.includes(url), url);
});
test("the blurred fills of the last three images stay in the cache", async () => {
const f = fixture({ width: 100, height: 300 });
f.names(["A.png", "B.png", "C.png", "D.png", "E.png"]);
await f.engine.configure(f.source(), { ...on, order: "name" });
for (let index = 0; index < 4; index++) { await f.engine.next(); await settle(); await settle(); }
const blurs = f.counts.blur;
const releasedBlurs = f.released.filter(url => url.endsWith("-blur")).length;
assert.ok(releasedBlurs >= 1, "Old fills beyond the cache are released.");
assert.ok(blurs - releasedBlurs <= BLUR_CACHE + 1, "At most the cache and the prepared fill stay.");
// The same image again uses the cached fill.
const repeat = fixture({ width: 100, height: 300 });
repeat.names(["A.png", "B.png"]);
await repeat.engine.configure(repeat.source(), on);
for (let index = 0; index < 4; index++) { await repeat.engine.next(); await settle(); await settle(); }
assert.equal(repeat.counts.blur, 2, "Two images that alternate use their cached fills.");
f.engine.dispose(); repeat.engine.dispose();
});
test("a late blurred fill is released when the source goes away", async () => {
let resolve!: (url: string) => void;
const f = fixture({ width: 100, height: 300 });
f.names(["A.png"]);
f.runtime.blur = () => new Promise(done => { resolve = done; });
const loading = f.engine.configure(f.source(), on);
await settle(); await settle();
await f.engine.configure(null, on);
resolve("blob:blur");
await loading;
assert.equal(f.frames.size, 0);
assert.ok(f.released.includes("blob:blur"));
assert.ok(f.released.some(url => url.startsWith("blob:A.png")));
f.engine.dispose();
});
test("the sources have stable keys, and the saved image of an old data URL decodes", async () => {
assert.equal(folderSource("D:\\Pictures").key, "folder:D:\\Pictures");
assert.equal(folderSource("D:\\Pictures").timed, true);
const id = "01234567-89ab-cdef-0123-456789abcdef";
assert.equal(imageSource({ imageId: id }).key, `image:${id}`);
assert.equal(imageSource({ imageId: id }).timed, false);
assert.deepEqual(await imageSource({ imageId: id }).list(), ["image"]);
const data = "data:image/png;base64,iVBORw0KGgo=";
const blob = await readSavedImage({ image: data });
assert.equal(blob.type, "image/png");
assert.deepEqual([...new Uint8Array(await blob.arrayBuffer())], [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
assert.notEqual(imageSource({ image: data }).key, imageSource({ image: data.replace("KGgo", "KGgp") }).key);
});
test("Background has a source only with a folder or an existing image", () => {
const appearance = { theme: "default" as const, mode: "dark" as const };
const withImage = { ...appearance, newTabBackground: { imageId: "01234567-89ab-cdef-0123-456789abcdef" } };
assert.equal(hasBackgroundSource(normalizeBackground({ source: "none" }), withImage), false);
assert.equal(hasBackgroundSource(normalizeBackground({ source: "folder" }), appearance), true);
assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), appearance), false);
assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), withImage), true);
});
test("the launch rule starts Background when it has a source, also in browser windows, but not in the settings window", () => {
const rule = LAUNCH_RULES.background!;
assert.equal(rule.browserWindow, true);
assert.equal(LAUNCH_RULES.git, undefined, "Git loads at first need.");
assert.equal(runsInWindow("background", { browserWindow: true }), true);
assert.equal(runsInWindow("git", { browserWindow: true }), false);
assert.equal(runsInWindow("git", { browserWindow: false }), true);
assert.equal(launchWanted("git", { settingsWindow: false }), false);
// In Node the settings are empty, so the source is "none".
assert.equal(rule.wanted(), false);
assert.equal(launchWanted("background", { settingsWindow: false }), false);
const wanted = rule.wanted;
rule.wanted = () => true;
try {
assert.equal(launchWanted("background", { settingsWindow: false }), true);
assert.equal(launchWanted("background", { settingsWindow: true }), false);
} finally { rule.wanted = wanted; }
});
function migrationHost({ image = false, folder = true, fails = false } = {}) {
const calls = { folder: 0 };
const written: BackgroundSettings[] = [];
const host: BackgroundMigrationHost = {
missing: () => true,
hasImage: () => image,
migrateFolder: async () => { calls.folder++; if (fails) throw new Error("no folder"); return folder; },
write: async value => { written.push(value); },
};
return { host, calls, written };
}
const plugin = (installed: boolean, enabled: boolean, settings: unknown): LegacyPlugin => ({ id: "runestone.bg-slideshow", installed, enabled, settings });
const grant = "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90";
const kept = { grant, folder: "D:\\Pictures", seconds: 10, order: "random", enabled: true, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" };
test("the migration selects the folder of an installed, enabled, and running slideshow", async () => {
const { host, calls, written } = migrationHost({ image: true });
const value = await migrateBackground(plugin(true, true, kept), host);
assert.equal(calls.folder, 1);
assert.deepEqual(value, { source: "folder", seconds: 10, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" });
assert.deepEqual(written, [value]);
});
test("a disabled package, a stopped slideshow, or a lost folder gives the image or none, and the folder still migrates", async () => {
for (const [legacy, folder] of [[plugin(true, false, kept), true], [plugin(true, true, { ...kept, enabled: false }), true], [plugin(false, false, kept), true], [plugin(true, true, kept), false]] as const) {
const withImage = migrationHost({ image: true, folder });
assert.equal((await migrateBackground(legacy, withImage.host)).source, "image");
assert.equal(withImage.calls.folder, 1, "A kept grant always migrates its folder.");
const without = migrationHost({ folder });
const value = await migrateBackground(legacy, without.host);
assert.equal(value.source, "none");
assert.equal(value.seconds, 10, "The kept settings still give the sequence and the layout.");
}
});
test("a failed folder migration is not a failed start", async () => {
const errors = console.error;
console.error = () => {};
try {
const { host, written } = migrationHost({ image: true, fails: true });
assert.equal((await migrateBackground(plugin(true, true, kept), host)).source, "image");
assert.equal(written.length, 1);
} finally { console.error = errors; }
});
test("without the old plugin, an image gives the image source and nothing gives none", async () => {
const image = migrationHost({ image: true });
assert.deepEqual(await migrateBackground(undefined, image.host), { ...DEFAULT_BACKGROUND, targets: ["app"], source: "image" });
assert.equal(image.calls.folder, 0, "Without a grant, no folder migrates.");
const none = migrationHost();
assert.deepEqual(await migrateBackground(plugin(false, false, null), none.host), { ...DEFAULT_BACKGROUND, targets: ["app"] });
// Settings of version 0.0.10 and earlier have a path and no grant. Only a grant migrates.
const old = migrationHost();
assert.equal((await migrateBackground(plugin(true, true, { folder: "D:\\Pictures", enabled: true }), old.host)).source, "none");
assert.equal(old.calls.folder, 0);
// Invalid kept values take the defaults.
const invalid = migrationHost();
const value = await migrateBackground(plugin(true, true, { grant, enabled: true, seconds: "x", targets: ["bogus"], overlay: 9 }), invalid.host);
assert.deepEqual([value.source, value.seconds, value.targets, value.overlay], ["folder", 60, [], 1]);
});
+208
View File
@@ -0,0 +1,208 @@
// The native feature runtime: the catalog, the switches, the migration from old plugin packages, the loader, and the session.
import { test } from "node:test";
import assert from "node:assert/strict";
import { FEATURES, featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
import { storedSwitches, switchesFrom } from "../../../src/lib/features/state.ts";
import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts";
import type { BackgroundMigrationHost, BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
import type { TerminalMigrationHost } from "../../../src/lib/features/terminalSettings.ts";
import type { ProjectManagementMigrationHost } from "../../../src/lib/features/pmSettings.ts";
import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts";
import { FeatureSession } from "../../../src/lib/features/session.ts";
import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts";
import { get } from "svelte/store";
test("each feature keeps the ID of its old plugin package as its owner ID", () => {
assert.equal(featureEntry("git").owner, "runestone.git");
assert.equal(featureOfOwner("runestone.git")?.id, "git");
assert.equal(featureOfOwner("runestone.csv-viewer"), undefined);
assert.equal(new Set(FEATURES.map(feature => feature.owner)).size, FEATURES.length);
const git = featureEntry("git");
assert.deepEqual(git.views.map(view => [view.id, view.placement]), [["source-control", "sidebar"], ["diff", "editor"], ["graph", "editor"]]);
assert.equal(git.views[0].title(), "Source control");
assert.deepEqual(git.commands.map(command => [command.id, command.view]), [["graph", "graph"]]);
const background = featureEntry("background");
assert.equal(background.owner, "runestone.bg-slideshow");
assert.equal(featureOfOwner("runestone.bg-slideshow")?.id, "background");
assert.deepEqual(background.views, []);
assert.deepEqual(background.commands.map(command => [command.id, command.view, command.title()]), [["next", undefined, "Next background image"], ["pause", undefined, "Pause background"]]);
assert.equal(background.defaultOn, true);
assert.equal(background.followsPackage, false);
});
test("switches keep known booleans only, and missing keys take the default", () => {
assert.deepEqual(storedSwitches({ git: false, terminal: "no", csv: true, other: "yes" }), { git: false });
assert.deepEqual(storedSwitches(null), {});
assert.deepEqual(storedSwitches(["git"]), {});
assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true, pdf: true, pm: true });
assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false, pdf: false, pm: false }), { git: false, background: false, terminal: false, pdf: false, pm: false });
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true, pdf: true, pm: true });
});
test("an installed package gives its state, and without a package the default applies", () => {
const git = featureEntry("git");
const legacy = (installed: boolean, enabled: boolean): LegacyPlugin => ({ id: "runestone.git", installed, enabled, settings: null });
assert.equal(legacySwitch(git, undefined), true);
assert.equal(legacySwitch(git, legacy(false, false)), true);
assert.equal(legacySwitch(git, legacy(true, false)), false);
assert.equal(legacySwitch(git, legacy(true, true)), true);
// Background is on for every user, also after an update with a disabled Background Slideshow package.
const background = featureEntry("background");
for (const [installed, enabled] of [[false, false], [true, false], [true, true]]) {
assert.equal(legacySwitch(background, { id: "runestone.bg-slideshow", installed, enabled, settings: null }), true);
}
assert.equal(legacySwitch(background, undefined), true);
});
/** A background host with a section already present: the migration of the section does not run. */
function presentBackground(): BackgroundMigrationHost {
return { missing: () => false, hasImage: () => false, migrateFolder: async () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
}
/** A terminal host with a section already present. */
function presentTerminal(): TerminalMigrationHost {
return { missing: () => false, legacy: () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
}
/** A Project Management host with a section already present. */
function presentProjectManagement(): ProjectManagementMigrationHost {
return { missing: () => false, write: async () => { throw new Error("not asked"); }, storage: { getItem: () => { throw new Error("not asked"); }, setItem: () => { throw new Error("not asked"); } } };
}
test("the migration asks only for features without a switch, and keeps other keys", async () => {
const writes: unknown[] = [];
const asked: string[][] = [];
const host = (stored: unknown, packages: LegacyPlugin[]) => ({
read: () => stored,
write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => { asked.push(ids); return packages; },
});
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true, pdf: true, pm: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal(), presentProjectManagement()), ["git"]);
assert.deepEqual(asked, [["runestone.git"]]);
assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, pdf: true, pm: true, git: false }]);
assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true, pdf: true, pm: true }, []), presentBackground(), presentTerminal(), presentProjectManagement()), []);
assert.equal(asked.length, 1, "A stored switch needs no package read.");
assert.equal(writes.length, 1);
});
test("a missing background section asks for the slideshow package and makes the section", async () => {
const asked: string[][] = [];
const switches: unknown[] = [];
const sections: BackgroundSettings[] = [];
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
const host = { read: () => ({ git: true, background: false, terminal: true, pdf: true, pm: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
assert.deepEqual(await migrateFeatures(host, background, presentTerminal(), presentProjectManagement()), []);
assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
assert.deepEqual(switches, [], "Stored switches stay.");
assert.equal(sections.length, 1);
assert.equal(sections[0].source, "image");
// Both migrations together ask once for both packages.
asked.length = 0;
await migrateFeatures({ ...host, read: () => undefined }, background, presentTerminal(), presentProjectManagement());
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm"]]);
assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true, pm: true }]);
});
test("a failed package read writes nothing, so the next start tries again", async () => {
const writes: unknown[] = [];
const error = console.error;
console.error = () => {};
try {
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { writes.push(value); } };
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background, presentTerminal(), presentProjectManagement());
assert.deepEqual(result, []);
assert.deepEqual(writes, []);
} finally { console.error = error; }
});
test("the loader imports a feature one time, reports a failure, and tries again after it", async () => {
let calls = 0;
const module: FeatureModule = { start: () => ({ mount: () => () => {}, dispose() {} }) };
await assert.rejects(loadFeature("git", async () => { calls++; throw new Error("chunk missing"); }), /chunk missing/);
assert.match(get(featureErrors).git ?? "", /chunk missing/);
assert.equal(featureRequested("git"), false);
const first = loadFeature("git", async () => { calls++; return module; });
const second = loadFeature("git", async () => { calls++; return module; });
assert.equal(await first, module);
assert.equal(await second, module);
assert.equal(calls, 2);
assert.equal(featureRequested("git"), true);
assert.equal(get(featureErrors).git, undefined);
});
function fakeContext(opened: string[] = []): FeatureContext {
return { openView: id => { opened.push(id); }, openFile: async () => {}, onWorkspaceChange: () => () => {}, setViewTitle: () => {}, closeView: () => {}, replaceView: () => {} };
}
test("a feature session shows its views and commands without loading the feature", async () => {
let loads = 0;
const opened: string[] = [];
const session = new FeatureSession(featureEntry("git"), fakeContext(opened), async () => { loads++; throw new Error("not loaded"); });
assert.deepEqual([...session.views.keys()], ["source-control", "diff", "graph"]);
assert.equal(session.views.get("source-control")?.navigation, true);
assert.equal(session.views.get("diff")?.launcher, false);
assert.equal(session.views.get("graph")?.title, "Git graph");
assert.equal(session.views.get("diff")?.saveTabState?.(), undefined);
await session.run("graph");
await session.launch("source-control");
assert.deepEqual(opened, ["graph", "source-control"]);
assert.equal(loads, 0, "Commands and navigation do not load the feature.");
assert.equal(session.started, false);
await session.stop();
});
test("an action command loads the feature and runs it, and start loads it without a view", async () => {
const runs: string[] = [];
let starts = 0;
const instance: FeatureInstance = { mount: () => () => {}, run: command => { runs.push(command); }, dispose() { runs.push("dispose"); } };
const session = new FeatureSession(featureEntry("background"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
assert.deepEqual([...session.commands.keys()], ["next", "pause"]);
assert.equal(session.commands.get("pause")?.title, "Pause background");
assert.equal(session.started, false);
await session.run("next");
assert.equal(session.started, true);
await session.start();
await session.run("pause");
assert.equal(starts, 1, "One instance runs the commands and the start.");
await session.stop();
assert.deepEqual(runs, ["next", "pause", "dispose"]);
await assert.rejects(session.run("missing"), /This command is unavailable/);
await assert.rejects(session.start(), /This feature is off/);
});
test("the first mount starts one instance, and stop disposes it", async () => {
const events: string[] = [];
let starts = 0;
const instance: FeatureInstance = {
mount: (view, element) => { events.push(`mount ${view}`); element.textContent = view; return () => { events.push(`unmount ${view}`); }; },
saveTabState: view => ({ view }),
restoreTabState: (view, state) => { events.push(`restore ${view} ${JSON.stringify(state)}`); },
dispose: () => { events.push("dispose"); },
};
const session = new FeatureSession(featureEntry("git"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
const element = { textContent: "", replaceChildren(this: { textContent: string }) { this.textContent = ""; } } as unknown as HTMLElement;
const dispose = await session.mount("diff", element);
await session.views.get("graph")!.restoreTabState!({ selectedId: "a" });
assert.equal(starts, 1);
assert.deepEqual(session.views.get("diff")!.saveTabState!(), { view: "diff" });
await dispose();
assert.equal(element.textContent, "");
await session.stop();
assert.deepEqual(events, ["mount diff", 'restore graph {"selectedId":"a"}', "unmount diff", "dispose"]);
await assert.rejects(session.mount("diff", element), /This feature is off/);
});
test("a failed load leaves no instance, so a later mount tries again", async () => {
let attempt = 0;
const instance: FeatureInstance = { mount: () => () => {}, dispose() {} };
const session = new FeatureSession(featureEntry("git"), fakeContext(), async () => {
if (++attempt === 1) throw new Error("offline");
return { start: () => instance };
});
const element = { replaceChildren() {} } as unknown as HTMLElement;
await assert.rejects(session.mount("graph", element), /offline/);
await session.mount("graph", element);
assert.equal(attempt, 2);
await assert.rejects(session.mount("missing", element), /This view is unavailable/);
await session.stop();
});
+67
View File
@@ -0,0 +1,67 @@
// The Git feature model. These tests come from the Git plugin (`RuneStone_Git/test/model.test.mjs`).
import { test } from "node:test";
import assert from "node:assert/strict";
import { changeLabel, diffLineKind, graphLayout, groups, isConflict, pathsFor } from "../../../src/lib/features/git/model.ts";
import type { GitChange, GitGraphCommit } from "../../../src/lib/git/contracts.ts";
const commit = (id: string, parents: string[]): GitGraphCommit => ({ id, parents, refs: [], summary: id, author: "Test", date: "2026-10-29" });
test("partially staged files occur in both groups, with conflicts only in working files", () => {
const changes: GitChange[] = [
{ path: "both.txt", index: "M", worktree: "M" },
{ path: "new.txt", index: "?", worktree: "?" },
{ path: "conflict.txt", index: "U", worktree: "U" },
{ path: "deleted.txt", index: "D", worktree: " " },
];
assert.deepEqual(groups(changes).staged.map(change => change.path), ["both.txt", "deleted.txt"]);
assert.deepEqual(groups(changes).working.map(change => change.path), ["both.txt", "new.txt", "conflict.txt"]);
assert.equal(isConflict({ path: "a", index: "A", worktree: "A" }), true);
assert.equal(changeLabel(changes[2], false), "Conflict");
assert.equal(changeLabel(changes[1], false), "New");
assert.equal(changeLabel(changes[3], true), "Deleted");
assert.equal(changeLabel({ path: "x", index: "X", worktree: " " }, true), "X");
});
test("rename actions include old and new paths exactly once", () => {
assert.deepEqual(pathsFor([{ path: "new.txt", originalPath: "old.txt", index: "R", worktree: " " }, { path: "old.txt", index: "M", worktree: " " }]), ["old.txt", "new.txt"]);
});
test("diff lines get their kind from the first character", () => {
assert.deepEqual(["+add", "-remove", "+++ b/file", "--- a/file", "@@ -1 +1 @@", " same", ""].map(diffLineKind),
["add", "remove", "context", "context", "range", "context", "context"]);
});
test("graph lanes preserve merge parents, forks, and truncated history", () => {
const layout = graphLayout({ commits: [commit("merge", ["main", "feature"]), commit("feature", ["root"]), commit("main", ["root"]), commit("root", ["older"])] });
assert.deepEqual(layout.nodes.map(node => node.lane), [0, 1, 0, 1]);
assert.equal(layout.edges.length, 5);
assert.deepEqual(layout.edges.filter(edge => edge.from === "merge").map(edge => [edge.to, edge.endRow]), [["main", 2], ["feature", 1]]);
assert.equal(layout.edges.at(-1)!.outside, true);
assert.equal(layout.edges.at(-1)!.endRow, 4);
assert.deepEqual(graphLayout({ commits: [] }).nodes, []);
assert.deepEqual(graphLayout(null).nodes, []);
});
test("graph track colors survive lane changes, joins, and history boundaries", () => {
const history = { commits: [commit("merge", ["main", "feature"]), commit("feature", ["feature-old"]), commit("main", ["root"]), commit("feature-old", ["root"]), commit("root", ["older"])] };
const layout = graphLayout(history);
const node = (id: string) => layout.nodes.find(item => item.id === id)!;
const edge = (from: string, to: string) => layout.edges.find(item => item.from === from && item.to === to)!;
assert.notEqual(node("main").color, node("feature").color);
assert.equal(node("merge").color, node("main").color);
assert.equal(node("feature").color, node("feature-old").color);
assert.equal(edge("merge", "feature").color, node("feature").color);
assert.equal(edge("feature-old", "root").color, node("feature-old").color);
assert.equal(edge("root", "older").color, node("root").color);
assert.deepEqual(graphLayout(history), layout);
const shifted = graphLayout({ commits: [commit("merge", ["main", "feature"]), commit("main", []), commit("feature", ["feature-old"]), commit("feature-old", [])] });
assert.notEqual(shifted.nodes[2].lane, shifted.nodes[3].lane);
assert.equal(shifted.nodes[2].color, shifted.nodes[3].color);
});
test("six concurrent graph tracks use six colors before palette reuse", () => {
const parents = ["a", "b", "c", "d", "e", "f"];
const layout = graphLayout({ commits: [commit("merge", parents), ...parents.map(id => commit(id, []))] });
assert.equal(new Set(layout.nodes.slice(1).map(node => node.color)).size, 6);
assert.equal(new Set(layout.edges.map(edge => edge.color)).size, 6);
});
+136
View File
@@ -0,0 +1,136 @@
// The PDF Viewer feature: the page and zoom limits, the document identification of the catalog, and the document
// mount of a feature session. The model tests come from the PDF Viewer plugin (tests/model.test.ts).
import { test } from "node:test";
import assert from "node:assert/strict";
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
import { identifyPdf } from "../../../src/lib/features/pdfDocument.ts";
import { PAGE_GAP, PAGE_MARGIN, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, zoomLevel } from "../../../src/lib/features/pdf/model.ts";
import { FeatureSession } from "../../../src/lib/features/session.ts";
import type { FeatureContext, FeatureInstance } from "../../../src/lib/features/types.ts";
import type { PluginDocumentContext } from "../../../src/lib/plugins/sdk.ts";
test("PDF identification handles uppercase extensions and distinct paths", () => {
assert.deepEqual(identifyPdf("notes\\Report.PDF"), { id: "notes/Report.PDF" });
assert.notDeepEqual(identifyPdf("a/report.pdf"), identifyPdf("b/report.pdf"));
for (const path of ["report.pdf.md", "pdf", "report.png"]) assert.equal(identifyPdf(path), null);
});
test("page and zoom inputs stay within supported bounds", () => {
assert.equal(pageNumber(NaN, 20), 1);
assert.equal(pageNumber(-3, 20), 1);
assert.equal(pageNumber(99, 20), 20);
assert.equal(pageNumber(2.8, 20), 2);
assert.equal(zoomLevel(Infinity), 1);
assert.equal(zoomLevel(0), .25);
assert.equal(zoomLevel(10), 4);
assert.deepEqual([0, 90, 180, 270].map(nextRotation), [90, 180, 270, 0]);
});
test("a typed zoom is a percent within the limits", () => {
assert.equal(zoomFromText("137"), 1.37);
assert.equal(zoomFromText(" 150 % "), 1.5);
assert.equal(zoomFromText("112,5"), 1.125);
assert.equal(zoomFromText("9000"), 4);
assert.equal(zoomFromText("1"), .25);
for (const text of ["", " ", "text", "-50", "0", "1e999"]) assert.equal(zoomFromText(text), null);
});
test("the pages are one column, and the scroll position gives the current page", () => {
const sizes = [{ width: 600, height: 800 }, { width: 800, height: 600 }, { width: 600, height: 800 }];
const boxes = pageBoxes(sizes, .5, 0);
assert.deepEqual(boxes, [
{ top: PAGE_MARGIN, width: 300, height: 400 },
{ top: PAGE_MARGIN + 400 + PAGE_GAP, width: 400, height: 300 },
{ top: PAGE_MARGIN + 700 + 2 * PAGE_GAP, width: 300, height: 400 },
]);
assert.deepEqual(pageBoxes(sizes, 1, 90).map(box => [box.width, box.height]), [[800, 600], [600, 800], [800, 600]]);
assert.equal(fitZoom(sizes, 0, 400), .5);
assert.equal(fitZoom(sizes, 90, 400), .5);
assert.equal(fitZoom([{ width: 600, height: 900 }], 90, 450), .5);
assert.equal(fitZoom([], 0, 400), 1);
assert.deepEqual(pagesInRange(boxes, 0, 100), [1]);
assert.deepEqual(pagesInRange(boxes, 400, 800), [1, 2, 3]);
assert.deepEqual(pagesInRange(boxes, 5000, 6000), []);
assert.equal(mostVisiblePage(boxes, 0, 300), 1);
assert.equal(mostVisiblePage(boxes, 300, 600), 2);
assert.equal(mostVisiblePage(boxes, 900, 1200), 3);
assert.equal(mostVisiblePage(boxes, 0, 2000), 1, "The first page wins when several pages show in full");
assert.equal(mostVisiblePage([], 0, 100), 1);
});
test("large PDF pages respect canvas dimension and memory limits", () => {
for (const [width, height] of [[612, 792], [20000, 500], [20000, 20000]]) {
const scale = outputScale(width, height, 3);
assert.ok(width * scale <= 8192);
assert.ok(height * scale <= 8192);
assert.ok(width * height * scale * scale <= 16_000_001);
}
});
test("the catalog gives PDF Viewer the old package ID and one binary document type", () => {
const pdf = featureEntry("pdf");
assert.equal(pdf.owner, "runestone.pdf-viewer");
assert.equal(featureOfOwner("runestone.pdf-viewer")?.id, "pdf");
assert.equal(pdf.defaultOn, true);
assert.equal(pdf.followsPackage, true);
assert.deepEqual(pdf.views, []);
assert.deepEqual(pdf.commands, []);
assert.deepEqual(pdf.documentTypes.map(type => [type.id, type.icon, type.content, [...type.extensions], type.title()]), [["pdf", "file", "binary", ["pdf"], "PDF document"]]);
assert.deepEqual(featureEntry("git").documentTypes, []);
});
function fakeContext(): FeatureContext {
return { openView: () => {}, openFile: async () => {}, onWorkspaceChange: () => () => {}, setViewTitle: () => {}, closeView: () => {}, replaceView: () => {} };
}
test("a feature session identifies PDF files without loading the feature", () => {
let loads = 0;
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => { loads++; throw new Error("not loaded"); });
const type = session.documentTypes.get("pdf");
assert.ok(type);
assert.equal(type.title, "PDF document");
assert.equal(type.content, "binary");
assert.deepEqual(type.extensions, ["pdf"]);
assert.deepEqual(type.identify("docs/Guide.PDF", ""), { id: "docs/Guide.PDF" });
assert.equal(type.identify("docs/guide.md", ""), null);
assert.equal(loads, 0, "Identification does not load the feature.");
assert.equal(session.started, false);
});
test("the first document mount starts one instance, each tab gets the document, and stop disposes it", async () => {
const events: string[] = [];
let starts = 0;
const instance: FeatureInstance = {
mount: () => { throw new Error("no views"); },
mountDocument: (type, element, document) => {
events.push(`mount ${type} ${document.path}`);
element.textContent = document.id;
return () => { events.push(`unmount ${document.path}`); };
},
dispose: () => { events.push("dispose"); },
};
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
const element = () => ({ textContent: "", replaceChildren(this: { textContent: string }) { this.textContent = ""; } }) as unknown as HTMLElement;
const first = element(), second = element();
const a: PluginDocumentContext = { id: "a.pdf", path: "a.pdf" };
const b: PluginDocumentContext = { id: "b/B.PDF", path: "b/B.PDF" };
const closeA = await session.mount("pdf", first, a);
const closeB = await session.mount("pdf", second, b);
assert.equal(starts, 1, "Two tabs share one instance.");
assert.equal(first.textContent, "a.pdf");
await closeA();
assert.equal(first.textContent, "", "The host empties the element after the dispose.");
await assert.rejects(session.mount("missing", element(), a), /This view is unavailable/);
await assert.rejects(session.mount("pdf", element()), /This view is unavailable/, "Without a document, the ID names a view.");
await closeB();
await session.stop();
assert.deepEqual(events, ["mount pdf a.pdf", "mount pdf b/B.PDF", "unmount a.pdf", "unmount b/B.PDF", "dispose"]);
await assert.rejects(session.mount("pdf", element(), a), /This feature is off/);
});
test("a feature without a document mount refuses a document", async () => {
const instance: FeatureInstance = { mount: () => () => {}, dispose() {} };
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => ({ start: () => instance }));
await assert.rejects(session.mount("pdf", { replaceChildren() {} } as unknown as HTMLElement, { id: "a.pdf", path: "a.pdf" }), /This view is unavailable/);
await session.stop();
});
+79
View File
@@ -0,0 +1,79 @@
// An in-memory workspace for the tests of the native Project Management feature. It records each read.
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import type { TaskFields, Workspace } from "../../../../src/lib/features/pm/model/model.ts";
export interface MemoryWorkspace extends Workspace {
files: Map<string, string>;
/** Each path that a read asked for, in order. A `readMany` row counts as one read. */
reads: string[];
/** Each folder that a listing asked for. */
lists: string[];
/** The number of Markdown listings. */
markdownLists: number;
}
export function memoryWorkspace(initial: Record<string, string> = {}): MemoryWorkspace {
const files = new Map(Object.entries(initial));
const reads: string[] = [], lists: string[] = [];
const parent = (path: string) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
const workspace: MemoryWorkspace = {
files, reads, lists, markdownLists: 0,
async list(path = "") {
lists.push(path);
const names = new Map<string, "file" | "folder">();
for (const file of files.keys()) {
if (path && !file.startsWith(path + "/")) continue;
const rest = path ? file.slice(path.length + 1) : file;
const name = rest.split("/")[0];
names.set(name, rest.includes("/") ? "folder" : "file");
}
return [...names].map(([name, kind]) => ({ name, rel_path: path ? `${path}/${name}` : name, kind }));
},
async listMarkdown() {
workspace.markdownLists++;
return [...files.keys()].filter(path => /\.(md|markdown|mdown)$/i.test(path) && !path.startsWith(".")).sort();
},
async read(path) {
reads.push(path);
if (!files.has(path)) throw new Error(`Missing file: ${path}`);
return files.get(path)!;
},
async readMany(paths) {
reads.push(...paths);
return paths.map(path => files.has(path) ? { path, source: files.get(path) } : { path, error: "Missing file" });
},
async readOptional(path) {
reads.push(path);
return files.get(path) ?? null;
},
async write(path, contents, expected) {
if (files.get(path) !== expected) throw new Error(`The file changed: ${path}`);
files.set(path, contents);
},
async create(path, contents) {
if (files.has(path)) throw new Error(`The file exists: ${path}`);
void parent(path);
files.set(path, contents);
},
};
return workspace;
}
export const fields = (extra: Partial<TaskFields> = {}): TaskFields => ({ status: "todo", tags: [], sessions: [], archived: false, ...extra });
/** A workspace with hidden storage: one board `board` and the given cards. */
export function hiddenWorkspace(cards: { id: string; title: string; fields?: Partial<TaskFields> }[] = [], extra: Record<string, string> = {}) {
const board = defaultBoard("board");
const files: Record<string, string> = {
[privateRulesPath]: "*\n",
[cardsMarker]: "*\n",
[catalogPath]: JSON.stringify({ schema: 1, boards: [{ name: "Board", value: board }] }, null, 2) + "\n",
...extra,
};
for (const card of cards) files[cardPath(card.id)] = newTask(card.title, fields({ title: card.title, placements: { board: { listId: "todo" } }, ...card.fields }), "Body", card.id).source;
return memoryWorkspace(files);
}
+66
View File
@@ -0,0 +1,66 @@
import test from "node:test";
import assert from "node:assert/strict";
import { allTaskColumns, allTaskGroups } from "../../../../src/lib/features/pm/model/all-tasks.ts";
import { defaultBoard, type BoardDocument } from "../../../../src/lib/features/pm/storage/board.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const board = (id: string): BoardDocument => ({ id, path: `${id}.md`, name: id, source: "", value: defaultBoard(id) });
const task = (title: string, placements: TaskFields["placements"]) => {
const note = newTask(title, { status: "todo", archived: false, tags: [], sessions: [], placements });
return readTask(`${title}.md`, note.source)!;
};
test("All tasks merges list names, preserves custom lists, and includes every matching card once", () => {
const a = board("A"), b = board("B"), c = board("C");
a.value.lists.push({ id: "review", name: "Review", status: null, collapsed: true });
b.value.lists[0].name = " To Do ";
b.value.lists[0].id = "different-id";
c.value.lists[0].maxCards = 2;
const shared = task("Shared", { A: { listId: "todo" }, B: { listId: "different-id" } });
const other = task("Other", { C: { listId: "todo" } });
const review = task("Review", { A: { listId: "review" }, C: { listId: "todo" } });
const unlisted = task("Unlisted", { A: { listId: "removed" }, B: { listId: null } });
const orphan = task("Orphan", { deleted: { listId: "todo" } });
const original = JSON.stringify({ boards: [a, b, c], tasks: [shared, other, review, unlisted, orphan] });
const columns = allTaskColumns([a, b, c], [shared, other, review, unlisted, orphan]);
assert.equal(columns.length, 5);
assert.deepEqual(columns.find(c => c.list?.name === "To do")?.tasks, [shared, other, review, orphan]);
assert.deepEqual(columns.find(c => c.list?.name === "Review")?.tasks, [review]);
assert.deepEqual(columns.find(c => !c.list)?.tasks, [unlisted]);
assert.equal(columns.find(c => c.list?.name === "Review")?.list?.collapsed, false);
assert.equal(columns.find(c => c.list?.name === "To do")?.list?.maxCards, undefined);
assert.equal(columns.find(c => c.list?.name === "To do")?.allowCreate, false);
assert.equal(JSON.stringify({ boards: [a, b, c], tasks: [shared, other, review, unlisted, orphan] }), original);
});
test("matching list IDs with different names remain separate and empty lists stay visible", () => {
const a = board("A"), b = board("B");
b.value.lists[0].name = "Backlog";
const columns = allTaskColumns([a, b], []);
assert.deepEqual(columns.map(c => c.list?.name), ["To do", "In progress", "Done", "Backlog"]);
assert.equal(new Set(columns.map(c => c.list?.id)).size, 4);
});
test("cards on archived boards remain visible and empty workspaces retain default lists", () => {
const archived = { ...board("Archived"), archived: true };
const card = task("Archived board card", { Archived: { listId: "todo" } });
const columns = allTaskColumns([archived], [card]);
assert.deepEqual(columns[0].tasks, [card]);
assert.equal(columns.length, 3);
assert.equal(columns[0].allowCreate, true);
assert.equal(allTaskColumns([], []).length, 3);
});
test("board dividers name shared memberships once and separate cards without active boards", () => {
const a = board("A"), b = board("B");
a.value.lists.push({ id: "review", name: "Review", status: null, collapsed: false });
const shared = task("Shared", { A: { listId: "todo" }, B: { listId: "todo" } });
const separate = task("Separate", { A: { listId: "review" }, B: { listId: "todo" } });
const orphan = task("Orphan", { deleted: { listId: "todo" } });
const columns = allTaskColumns([a, b], [shared, separate, orphan]);
const todo = columns.find(column => column.list?.name === "To do")!;
assert.deepEqual(allTaskGroups([a, b], todo).map(group => [group.name, group.tasks.map(task => task.title)]), [
["A · B", ["Shared"]], ["B", ["Separate"]], ["No active board", ["Orphan"]],
]);
assert.deepEqual(allTaskGroups([a, b], columns.find(column => column.list?.name === "Review")!).map(group => group.name), ["A"]);
});
@@ -0,0 +1,60 @@
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
function fixture(count = 3) {
const files = new Map<string, string>([[cardsMarker, "*\n"], [privateRulesPath, "*\n"]]);
const ids = Array.from({ length: count }, () => crypto.randomUUID());
for (const [index, id] of ids.entries()) files.set(cardPath(id), newTask(`Card ${index}`, {
title: `Card ${index}`, status: "todo", tags: [], sessions: [], archived: false,
...(index === 0 ? { links: [{ taskId: ids[1], relation: "blocks" }, { taskId: ids[2], relation: "relates" }] as const } : {}),
}, "Keep body", id).source);
let batches = 0, singleReads = 0;
const workspace: Workspace = {
async listMarkdown() { return []; },
async list() { return [...files.keys()].filter(path => path.endsWith(".md")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
async read(path) { singleReads++; return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async readMany(paths) { assert.ok(paths.length <= 64); batches++; return paths.map(path => ({ path, source: files.get(path) })); },
async write(path, source, expected) { assert.equal(files.get(path), expected); files.set(path, source); },
async create(path, source) { assert.equal(files.has(path), false); files.set(path, source); },
};
return { files, ids, workspace, counts: () => ({ batches, singleReads }) };
}
test("1000 cards use 16 bounded reads and share parsed cards between board views", async t => {
const f = fixture(1000), store = new TaskStore(f.workspace);
let started = performance.now();
await store.reload();
t.diagnostic(`Initial 1000-card parse: ${Math.round(performance.now() - started)} ms`);
assert.deepEqual(f.counts(), { batches: 16, singleReads: 0 });
const first = store.tasks[0];
const next = new TaskStore(f.workspace);
started = performance.now(); await next.reload();
t.diagnostic(`Switch with unchanged sources: ${Math.round(performance.now() - started)} ms`);
assert.equal(next.tasks[0], first);
started = performance.now(); await next.save(first, { body: "Changed body" });
t.diagnostic(`Save with full conflict scan: ${Math.round(performance.now() - started)} ms`);
assert.deepEqual(f.counts(), { batches: 48, singleReads: 0 });
const stale = next.tasks.find(task => task.id === first.id)!;
f.files.set(stale.path, editTask(stale, { body: "External body" }));
await assert.rejects(next.save(stale, { body: "Overwrite" }), /changed/);
assert.equal(readTask(stale.path, f.files.get(stale.path)!)!.body, "External body");
});
test("incoming unlink preserves unrelated links and rejects stale source cards", async () => {
const f = fixture(), store = new TaskStore(f.workspace); await store.reload();
const source = store.tasks.find(task => task.id === f.ids[0])!;
await store.unlinkIncoming(f.ids[1], [source]);
const saved = readTask(source.path, f.files.get(source.path)!)!;
assert.deepEqual(saved.links, [{ taskId: f.ids[2], relation: "relates" }]);
assert.equal(saved.body, "Keep body");
await store.unlinkIncoming(f.ids[1], [source]); // A retry is harmless.
f.files.set(saved.path, editTask(saved, { body: "External change" }));
await assert.rejects(store.unlinkIncoming(f.ids[2], [saved]), /linked card changed/);
assert.deepEqual(readTask(saved.path, f.files.get(saved.path)!)!.links, saved.links);
});
+237
View File
@@ -0,0 +1,237 @@
import test from "node:test";
import assert from "node:assert/strict";
import { BoardStore, newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
function fixture() {
const source = newBoardSource();
const files = new Map<string, string>([["Board.md", source]]);
const reference = { id: parseBoard(source).id, path: "Board.md" };
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async read(path) {
if (!files.has(path)) throw Error("Missing");
return files.get(path)!;
},
async create(path, text) {
if (files.has(path)) throw Error("Exists");
files.set(path, text);
},
async write(path, text, expected) {
if (files.get(path) !== expected) throw Error("Conflict");
files.set(path, text);
},
async list(parent = "") {
return [...files.keys()]
.filter((path) => !path.startsWith("."))
.map((path) => ({ name: path, rel_path: path, kind: "file" }));
},
};
return { files, workspace, reference };
}
test("list names, completion mapping, order, and collapse survive reload", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace, reference);
await board.reload();
await board.add("Review", null);
const review = board.value.lists.at(-1)!;
await board.edit(review.id, "Approved", "done");
await board.move(review.id, 0);
await board.collapse(review.id);
const reopened = new BoardStore(workspace, reference);
await reopened.reload();
assert.deepEqual(reopened.value.lists[0], {
id: review.id,
name: "Approved",
status: "done",
collapsed: true,
});
await assert.rejects(reopened.add("approved", null), /already exists/);
});
test("list maximum survives edits and reload, rejects invalid values, and can be removed", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace, reference);
await board.reload();
await board.setLimit("todo", 2);
await board.edit("todo", "Next", "todo");
await board.collapse("todo");
await board.reload();
assert.equal(board.value.lists[0].maxCards, 2);
for (const invalid of [0, -1, 1.5, Infinity, NaN, Number.MAX_SAFE_INTEGER + 1])
await assert.rejects(board.setLimit("todo", invalid), /whole number/);
const source = newBoardSource().replace("collapsed: false", "collapsed: false\n maxCards: -2");
assert.throws(() => parseBoard(source), /invalid list/);
await board.setLimit("todo");
await board.reload();
assert.equal(board.value.lists[0].maxCards, undefined);
});
test("deleting a populated list preserves notes and sends its cards to Unlisted", async () => {
const { workspace, files, reference } = fixture();
const note = newTask(
"Keep me",
{ ...fields, placements: { [reference.id]: { listId: "todo" } } },
"Keep the body",
);
files.set("Keep me.md", note.source);
const store = new TaskStore(workspace, reference);
await store.reload();
await store.changeBoard(() => store.board.remove("todo"));
assert.equal(store.board.listFor(store.tasks[0]), undefined);
assert.equal(files.get("Keep me.md"), note.source);
await store.board.add("Replacement", null);
assert.equal(store.board.listFor(store.tasks[0]), undefined);
assert.equal(
store.board.listFor({ status: "todo", listId: undefined }),
undefined,
);
});
test("moving a card stores its list and completion in one guarded note write", async () => {
const { workspace, files, reference } = fixture();
const note = newTask("Task", fields);
files.set("Task.md", note.source);
const store = new TaskStore(workspace, reference);
await store.reload();
await store.moveTask(store.tasks[0], "done");
const saved = readTask("Task.md", files.get("Task.md")!)!;
assert.equal(saved.placements?.[reference.id].listId, "done");
assert.equal(saved.status, "done");
assert.equal(saved.id, store.tasks[0].id);
await store.moveTask(store.tasks[0], null);
assert.equal(store.board.listFor(store.tasks[0]), undefined);
assert.equal(store.tasks[0].status, "todo");
});
test("stale list edits do not overwrite another board revision", async () => {
const { workspace, files, reference } = fixture();
const first = new BoardStore(workspace, reference),
second = new BoardStore(workspace, reference);
await first.reload();
await second.reload();
await first.add("Review", null);
const saved = files.get("Board.md");
await assert.rejects(second.add("Other", null), /changed/);
assert.equal(files.get("Board.md"), saved);
});
test("malformed or future board files stay untouched", async () => {
const { workspace, files, reference } = fixture();
const text = newBoardSource().replace("schema: 1", "schema: 2");
files.set("Board.md", text);
const board = new BoardStore(workspace, reference);
await assert.rejects(board.reload(), /unsupported/);
await assert.rejects(board.add("Oops", null), /Open an available board/);
assert.equal(files.get("Board.md"), text);
});
test("deleting all lists remains empty after reload and allows a new list", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace, reference);
await board.reload();
for (const id of ["todo", "doing", "done"]) await board.remove(id);
const next = new BoardStore(workspace, reference);
await next.reload();
assert.equal(next.value.lists.length, 0);
await next.add("First", null);
assert.equal(next.value.lists[0].name, "First");
});
test("All tasks cannot save board lists", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace);
await board.reload();
await assert.rejects(board.add("Review", null), /Open an available board/);
assert.equal(board.value.lists.length, 3);
});
test("archiving a list scopes by board placement and preserves status, bodies, and other memberships", async () => {
const { workspace, files, reference } = fixture();
const sourceBoard = files.get(reference.path);
for (const [title, placements] of [
["Target", { [reference.id]: { listId: "todo" }, other: { listId: "doing" } }],
["Other list", { [reference.id]: { listId: "doing" } }],
["Other board", { other: { listId: "todo" } }],
] as const) {
const task = newTask(title, { ...fields, placements }, "Keep body");
files.set(task.path, task.source);
}
const store = new TaskStore(workspace, reference);
await store.reload();
const original = store.tasks.find(task => task.title === "Target")!;
await store.archiveList("todo");
await store.reload();
const archived = store.tasks.find(task => task.title === "Target")!;
assert.equal(archived.archived, true);
assert.equal(archived.status, original.status);
assert.deepEqual(archived.placements, original.placements);
assert.equal(archived.body, original.body);
assert.equal(store.tasks.filter(task => task.archived).length, 1);
assert.equal(files.get(reference.path), sourceBoard);
await store.archiveList("todo");
await assert.rejects(store.archiveList("missing"), /unavailable/);
});
test("board image appearance survives legacy saves and hidden catalog saves independently", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace, reference); await board.reload();
const appearance = { overlay: -0.4, position: "bottom right", size: "contain" } as const;
await board.update(value => { value.backgroundImage = "11111111-1111-4111-8111-111111111111"; value.backgroundAppearance = appearance; });
await board.reload(); assert.equal(board.value.backgroundImage, "11111111-1111-4111-8111-111111111111"); assert.deepEqual(board.value.backgroundAppearance, appearance);
const store = new TaskStore(workspace); await store.reload(); const hidden = await store.createBoard("Hidden");
const managed = new BoardStore(workspace, hidden); await managed.reload();
await managed.update(value => { value.backgroundImage = "22222222-2222-4222-8222-222222222222"; value.backgroundAppearance = { overlay: 0.7, position: "top", size: "auto" }; });
await managed.reload(); assert.equal(managed.value.backgroundImage, "22222222-2222-4222-8222-222222222222"); assert.equal(managed.value.backgroundAppearance!.overlay, 0.7);
await board.reload(); assert.deepEqual(board.value.backgroundAppearance, appearance);
});
test("leaving a Done rule reopens a card and neutral moves preserve manual completion", async () => {
const { workspace, files, reference } = fixture();
const note = newTask("Task", { ...fields, status: "done", placements: { [reference.id]: { listId: "done" } } });
files.set("Task.md", note.source);
const store = new TaskStore(workspace, reference); await store.reload();
await store.changeBoard(() => store.board.add("Review", null));
const review = store.board.value.lists.at(-1)!.id;
await store.moveTask(store.tasks[0], review);
await store.reload();
assert.equal(store.tasks[0].status, "todo");
assert.equal(store.tasks[0].placements![reference.id].listId, review);
await store.save(store.tasks[0], { status: "done" });
await store.moveTask(store.tasks[0], null);
await store.reload();
assert.equal(store.tasks[0].status, "done");
await store.changeBoard(() => store.board.edit(review, "Review", "doing"));
await store.moveTask(store.tasks[0], review);
await store.reload(); assert.equal(store.tasks[0].status, "doing");
await store.moveTask(store.tasks[0], "todo");
await store.changeBoard(() => store.board.edit(review, "Review", null));
await store.save(store.tasks[0], { listId: review }, true);
await store.reload(); assert.equal(store.tasks[0].status, "todo");
assert.equal(store.board.value.lists.find(list => list.id === review)!.status, null);
});
test("overview creation writes one assigned card and rejects stale destinations without extra cards", async () => {
const { workspace, files, reference } = fixture();
const store = new TaskStore(workspace);
await store.reload();
await store.create("Assigned card", { ...fields, listId: "doing" }, "Card body", reference.id);
const task = store.tasks.find(task => task.title === "Assigned card")!;
assert.equal(task.placements?.[reference.id].listId, "doing");
assert.equal(Object.keys(task.placements ?? {}).length, 1);
assert.equal(task.body.trim(), "Card body");
const snapshot = new Map(files);
await assert.rejects(store.create("Missing board", fields, "", "missing"), /active board/);
await assert.rejects(store.create("Missing list", { ...fields, listId: "missing" }, "", reference.id), /list no longer exists/);
assert.deepEqual(files, snapshot);
files.delete("Board.md");
const afterDelete = new Map(files);
await assert.rejects(store.create("Deleted board", fields, "", reference.id), /active board/);
assert.deepEqual(files, afterDelete);
});
@@ -0,0 +1,75 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { priorities, type TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
import { renderMarkdown } from "../../../../src/lib/features/pm/model/markdown.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
labels: ["high-priority"],
sessions: [],
archived: false,
};
test("priority round-trips independently of labels and survives unrelated changes", () => {
for (const priority of [...priorities, null]) {
const note = newTask("Priority card", { ...fields, priority });
const task = readTask(note.path, note.source)!;
assert.equal(task.priority, priority);
const changed = readTask(
note.path,
editTask(task, { status: "doing", listId: "review", body: "Edited" }),
)!;
assert.equal(changed.priority, priority);
assert.deepEqual(changed.labels, fields.labels);
}
});
test("unrelated edits preserve absent priority and explicit removal writes null", () => {
const note = newTask("Legacy", fields);
const task = readTask(note.path, note.source)!;
assert.doesNotMatch(editTask(task, { body: "Edit" }), /priority:/);
const cleared = editTask(task, { priority: null });
assert.match(cleared, /priority: null/);
assert.deepEqual(readTask(note.path, cleared)!.labels, fields.labels);
assert.throws(
() => newTask("Invalid", { ...fields, priority: "urgent" as never }),
/priority/,
);
});
test("Markdown preview escapes HTML and rejects active links and external images", () => {
const result = renderMarkdown(
"# Heading\n\n**Bold**\n\n<script>alert(1)</script>\n\n[x](javascript:alert(1))\n\n![remote](https://example.com/tracker.png)\n\n![image](pm-image:12345678-1234-1234-1234-123456789abc)\n\n[safe](https://example.com)",
);
assert.match(result, /<h1>Heading<\/h1>/);
assert.match(result, /<strong>Bold<\/strong>/);
assert.doesNotMatch(result, /<script|src=|href="javascript:/);
assert.match(result, /data-pm-image="12345678-1234-1234-1234-123456789abc"/);
assert.match(result, /rel="noopener noreferrer"/);
});
test("covers, subtasks, and card links round-trip without changing other fields", () => {
const coverImage = "12345678-1234-1234-1234-123456789abc";
const subtasks = [{ id: "subtask", title: "Check the change", done: true }];
const links = [{ taskId: "dependency", relation: "blocked-by" as const }];
const note = newTask("Relationships", { ...fields, coverImage, subtasks, links });
const task = readTask(note.path, note.source)!;
assert.deepEqual(task.subtasks, subtasks); assert.deepEqual(task.links, links); assert.equal(task.coverImage, coverImage);
const edited = readTask(note.path, editTask(task, { body: "Revised", priority: "lowest" }))!;
assert.deepEqual(edited.subtasks, subtasks); assert.deepEqual(edited.links, links); assert.equal(edited.coverImage, coverImage);
assert.throws(() => editTask(task, { coverImage: "../outside.png" }), /image/);
assert.throws(() => editTask(task, { subtasks: [...subtasks, ...subtasks] }), /unique ID/);
assert.throws(() => editTask(task, { links: [...links, ...links] }), /once/);
});
test("attachments round-trip independently of description edits and reject duplicate or invalid IDs", () => {
const attachments = [{ id: "12345678-1234-1234-1234-123456789abc", name: "Screenshot.png" }];
const note = newTask("Attached image", { ...fields, attachments }, "Description");
const task = readTask(note.path, note.source)!;
assert.deepEqual(task.attachments, attachments);
const changed = readTask(note.path, editTask(task, { body: "", status: "doing" }))!;
assert.deepEqual(changed.attachments, attachments);
assert.equal(changed.body, "");
assert.deepEqual(readTask(note.path, editTask(changed, { attachments: [] }))!.attachments, []);
assert.throws(() => editTask(task, { attachments: [...attachments, ...attachments] }), /unique image ID/);
assert.throws(() => editTask(task, { attachments: [{ id: "../outside", name: "Image" }] }), /unique image ID/);
});
@@ -0,0 +1,69 @@
import test from "node:test";
import assert from "node:assert/strict";
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { validateFields, type TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
test("optional card fields survive moves and can be removed without changing other note data", () => {
const note = newTask(
"Customer work",
{
...fields,
color: "purple",
assignees: ["Alex", "Northwind"],
customFields: [
{ name: "Customer ID", value: "0012" },
{ name: "Contact", value: "[email protected]" },
],
},
"Keep **these details**.\n",
);
const source = note.source.replace(
" schema: 1",
" extra: keep-me # future property\n schema: 1",
);
const task = readTask(note.path, source)!;
assert.equal(task.color, "purple");
assert.deepEqual(task.assignees, ["Alex", "Northwind"]);
assert.equal(task.customFields?.[0].value, "0012");
const moved = readTask(
note.path,
editTask(task, { status: "done", listId: "done" }),
)!;
assert.deepEqual(moved.customFields, task.customFields);
assert.equal(moved.color, "purple");
const cleared = editTask(moved, {
color: undefined,
assignees: [],
customFields: [],
});
assert.ok(cleared.includes("extra: keep-me # future property"));
assert.equal(readTask(note.path, cleared)!.body, task.body);
assert.equal(readTask(note.path, cleared)!.color, undefined);
assert.deepEqual(readTask(note.path, cleared)!.customFields, []);
});
test("invalid optional fields and duplicate names cannot enter saved notes", () => {
for (const patch of [
{ color: "url(bad)" },
{ assignees: "Alex" },
{ assignees: [1] },
{ customFields: [null] },
{ customFields: [{ name: "", value: "x" }] },
{
customFields: [
{ name: "ID", value: "1" },
{ name: " id ", value: "2" },
],
},
])
assert.throws(() => validateFields({ ...fields, ...patch } as TaskFields));
const old = newTask("Basic", fields);
assert.equal(readTask(old.path, old.source)!.color, undefined);
});
@@ -0,0 +1,296 @@
import test from "node:test";
import assert from "node:assert/strict";
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { adoptNote, editTask, newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { cardOrder, orderBetween } from "../../../../src/lib/features/pm/storage/order.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts";
import type { TaskFields, Workspace } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
function fixture() {
const board = newBoardSource();
const files = new Map([["Board.md", board]]);
const reads: string[] = [],
lists: string[] = [],
writes: string[] = [];
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async list(parent = "") {
lists.push(parent);
const entries = new Map();
for (const path of files.keys()) {
const prefix = parent ? parent + "/" : "";
if (!path.startsWith(prefix)) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: prefix + parts[0],
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async read(path) {
reads.push(path);
if (!files.has(path)) throw new Error("Missing note");
return files.get(path)!;
},
async write(path, source, expected) {
assert.equal(files.get(path), expected);
writes.push(path);
files.set(path, source);
},
async create(path, source) {
if (files.has(path)) throw new Error("Exists");
files.set(path, source);
},
};
const reference = { id: parseBoard(board).id, path: "Board.md" };
return {
files,
reads,
lists,
writes,
workspace,
reference,
store: new TaskStore(workspace, reference),
};
}
test("card creation reads one board and does not scan unrelated notes after loading", async () => {
const { store, files, lists, reads } = fixture();
for (let index = 0; index < 300; index++)
files.set(`Archive/Note ${index}.md`, "Plain note");
await store.reload();
lists.length = reads.length = 0;
await store.create("New card", fields, "Details");
assert.deepEqual(lists, []);
assert.deepEqual(reads, ["Board.md"]);
assert.equal(store.scopedTasks[0].title, "New card");
assert.equal(store.scopedTasks[0].body, "Details");
await store.create("New card", fields, "Second");
assert.equal(store.scopedTasks.length, 2);
assert.equal(store.scopedTasks[0].body, "Details");
});
test("creation checks the current list before writing a card", async () => {
const { store, files } = fixture();
await store.reload();
await store.board.remove("todo");
const snapshot = new Map(files);
await assert.rejects(
store.create("Missing list", { ...fields, listId: "todo" }, ""),
/list no longer exists/,
);
assert.deepEqual(files, snapshot);
assert.equal(store.tasks.length, 0);
});
test("a background scan cannot replace a newly created card with an older snapshot", async () => {
const { store, workspace } = fixture();
await store.reload();
const list = workspace.list;
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
workspace.list = async (path) => {
const snapshot = await list(path);
await gate;
return snapshot;
};
const pending = store.reload();
await store.create("Keep new card", fields, "");
release();
await pending;
assert.deepEqual(
store.scopedTasks.map((task) => task.title),
["Keep new card"],
);
});
test("title edits preserve the filename, identity, metadata, and body", async () => {
const { store, files } = fixture();
await store.create("Original", fields, "Keep **Markdown**.\n");
const original = store.tasks[0];
files.set(
original.path,
original.source.replace("---\n", "---\nowner: Ada # keep\n"),
);
await store.reload();
await store.save(store.tasks[0], { title: "Edited: title / shared" });
const updated = store.tasks[0];
assert.equal(updated.title, "Edited: title / shared");
assert.equal(updated.id, original.id);
assert.equal(updated.path, original.path);
assert.equal(updated.body, original.body);
assert.match(updated.source, /owner: Ada # keep/);
assert.equal([...files.keys()].filter(isHiddenCard).length, 1);
await store.reload();
assert.equal(store.tasks[0].title, updated.title);
await assert.rejects(store.save(original, { title: "Stale" }), /changed/);
await assert.rejects(
store.save(store.tasks[0], { title: " " }),
/card title/,
);
assert.equal(readTask(original.path, original.source)!.title, "Original");
});
test("legacy notes with long filenames remain editable before a card title is set", () => {
const path = "Long existing note ".repeat(8).trim() + ".md";
const source = adoptNote(path, "Existing description");
const task = readTask(path, source)!;
assert.equal(task.title, path.slice(0, -3));
const edited = readTask(path, editTask(task, { status: "doing" }))!;
assert.equal(edited.title, task.title);
assert.equal(edited.status, "doing");
});
test("cards retain insertion order and can move before, between, and after other cards", async () => {
const { store, workspace, reference, writes } = fixture();
for (const name of ["Zulu", "Alpha", "Middle"])
await store.create(name, fields, "");
const names = () => store.cardsInList("todo").map((task) => task.title);
const task = (title: string) =>
store.tasks.find((task) => task.title === title)!;
assert.deepEqual(names(), ["Zulu", "Alpha", "Middle"]);
await store.save(task("Middle"), { status: "done" });
const middle = task("Middle");
writes.length = 0;
await store.moveTask(middle, "todo", task("Zulu").id);
assert.deepEqual(writes, [middle.path]);
assert.equal(task("Middle").status, "done");
assert.deepEqual(names(), ["Middle", "Zulu", "Alpha"]);
await store.moveTask(task("Alpha"), "todo", task("Zulu").id);
assert.deepEqual(names(), ["Middle", "Alpha", "Zulu"]);
await store.moveTask(task("Middle"), "todo", null);
assert.deepEqual(names(), ["Alpha", "Zulu", "Middle"]);
await store.save(task("Zulu"), {
title: "A renamed card",
listId: "todo",
tags: ["release"],
});
const reopened = new TaskStore(workspace, reference);
await reopened.reload();
assert.deepEqual(
reopened.cardsInList("todo").map((task) => task.title),
["Alpha", "A renamed card", "Middle"],
);
});
test("card order stays independent in each board and All tasks", async () => {
const { store, files, workspace, reference } = fixture();
const secondSource = newBoardSource();
files.set("Second.md", secondSource);
const second = new TaskStore(workspace, {
id: parseBoard(secondSource).id,
path: "Second.md",
});
for (const name of ["Alpha", "Beta", "Gamma"]) {
await store.create(
name,
{ ...fields, due: { date: "2026-10-08" } },
"Shared details",
);
await second.adopt(store.tasks.find((task) => task.title === name)!.path);
}
await store.reload();
const gamma = store.tasks.find((task) => task.title === "Gamma")!;
const secondPlacement = gamma.placements![second.board.reference!.id];
await store.moveTask(
gamma,
"todo",
store.tasks.find((task) => task.title === "Alpha")!.id,
);
await second.reload();
assert.deepEqual(
second.cardsInList("todo").map((task) => task.title),
["Alpha", "Beta", "Gamma"],
);
assert.deepEqual(
second.tasks.find((task) => task.id === gamma.id)!.placements![
second.board.reference!.id
],
secondPlacement,
);
const all = new TaskStore(workspace);
await all.reload();
await all.moveTask(all.tasks[1], "todo", all.tasks[0].id);
assert.deepEqual(
all.cardsInList("todo").map((task) => task.title),
["Beta", "Alpha", "Gamma"],
);
await store.reload();
assert.deepEqual(
store.cardsInList("todo").map((task) => task.title),
["Gamma", "Alpha", "Beta"],
);
await store.moveTask(store.cardsInList("todo")[0], "done", null);
const moved = store.cardsInList("done")[0];
assert.equal(moved.status, "done");
assert.deepEqual(moved.due, { date: "2026-10-08" });
assert.equal(moved.body, "Shared details");
assert.equal(moved.placements![reference.id].listId, "done");
});
test("failed or stale order writes keep card data intact", async () => {
const { store, workspace, files } = fixture();
await store.create("Alpha", fields, "");
await store.create("Beta", fields, "");
const [alpha, beta] = store.cardsInList("todo");
const snapshot = new Map(files);
workspace.write = async () => {
throw new Error("Disk failure");
};
await assert.rejects(store.moveTask(beta, "todo", alpha.id), /Disk failure/);
assert.deepEqual(files, snapshot);
assert.deepEqual(
store.cardsInList("todo").map((task) => task.title),
["Alpha", "Beta"],
);
await assert.rejects(
store.moveTask(beta, "todo", "missing"),
/target card moved/,
);
files.set(beta.path, editTask(beta, { body: "External change" }));
await assert.rejects(store.moveTask(beta, "todo", alpha.id), /changed/);
});
test("ordering handles repeated narrow gaps, legacy notes, and matching saved ranks", () => {
let upper = "j";
for (let index = 0; index < 1200; index++) {
const rank = orderBetween("i", upper);
assert.ok("i" < rank && rank < upper);
assert.match(rank, /^[0-9a-z]*[1-9a-z]$/);
upper = rank;
}
const alphaNote = newTask(
"Alpha",
fields,
"",
"00000000-0000-4000-8000-000000000001",
);
const betaNote = newTask(
"Beta",
fields,
"",
"00000000-0000-4000-8000-000000000002",
);
const alpha = readTask(alphaNote.path, alphaNote.source)!;
const beta = readTask(betaNote.path, betaNote.source)!;
assert.ok(cardOrder(alpha) < cardOrder(beta));
assert.equal(cardOrder(alpha), cardOrder({ ...alpha, title: "Zulu" }));
alpha.order = beta.order = "i";
const between = orderBetween(cardOrder(alpha), cardOrder(beta));
const inserted = cardOrder({ ...alpha, id: "new", order: between });
assert.ok(cardOrder(alpha) < inserted && inserted < cardOrder(beta));
assert.throws(() => editTask(alpha, { order: "invalid!" }), /order/);
});
+198
View File
@@ -0,0 +1,198 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readTask, editTask, newTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts";
import {
addDays,
dayDistance,
validDate,
type Workspace,
type TaskFields,
} from "../../../../src/lib/features/pm/model/model.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
function memory(initial: Record<string, string> = {}) {
const files = new Map(Object.entries(initial));
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async list(parent = "") {
const entries = new Map();
for (const path of files.keys()) {
const prefix = parent ? `${parent}/` : "";
if (!path.startsWith(prefix)) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: `${prefix}${parts[0]}`,
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async read(path) {
const text = files.get(path);
if (text === undefined) throw Error("Missing file");
return text;
},
async write(path, text, expected) {
assert.equal(files.get(path), expected, "Changed on disk");
files.set(path, text);
},
async create(path, text) {
if (files.has(path)) throw Error("Exists");
files.set(path, text);
},
};
return { workspace, files };
}
test("tasks round trip with a stable ID, description, deadline, plan, and sessions", () => {
const note = newTask(
"Launch",
{
...fields,
due: { date: "2026-10-30" },
plan: { start: "2026-10-05", end: "2026-10-31" },
sessions: [
{
id: "session-1",
start: "2026-10-08T16:00:00Z",
end: "2026-10-08T17:00:00Z",
timeZone: "America/Vancouver",
},
],
},
"Keep **Markdown**.\n",
);
const task = readTask(note.path, note.source)!;
const moved = readTask(note.path, editTask(task, { status: "doing" }))!;
assert.equal(moved.id, task.id);
assert.equal(moved.body, task.body);
assert.deepEqual(moved.plan, task.plan);
assert.deepEqual(moved.sessions, task.sessions);
assert.deepEqual(moved.due, task.due);
assert.equal(moved.status, "doing");
});
test("metadata edits preserve unknown properties, comments, and the exact body", () => {
const source =
'\uFEFF---\r\nowner: Ada # keep this\r\nrunestone_pm:\r\n schema: 1\r\n id: stable\r\n kind: task\r\n status: todo # workflow\r\n future: {value: 12}\r\n plan:\r\n start: "2026-10-04"\r\n end: "2026-10-08"\r\n custom: untouched\r\n---\r\n# Body\r\n\r\n- [ ] Keep spacing \r\n';
const original = readTask("Note.md", source)!;
const next = editTask(original, {
status: "doing",
plan: { start: "2026-10-05", end: "2026-10-09" },
});
assert.equal(readTask("Note.md", next)!.body, original.body);
assert.match(next, /owner: Ada # keep this/);
assert.match(next, /# workflow/);
assert.match(next, /future:/);
assert.match(next, /custom: untouched/);
assert.ok(next.startsWith("\uFEFF"));
assert.ok(!/(?<!\r)\n/.test(next));
});
test("adding an existing note preserves its content and does not duplicate its identity", () => {
const source = "---\ncategory: reference\n---\nOriginal body\n";
const adopted = adoptNote("Existing.md", source),
task = readTask("Existing.md", adopted)!;
assert.equal(task.body, "Original body\n");
assert.match(adopted, /category: reference/);
assert.equal(adoptNote("Existing.md", adopted), adopted);
});
test("unsupported metadata and invalid dates are rejected without rewriting a note", () => {
const note = newTask("Task", fields);
assert.throws(
() => readTask(note.path, note.source.replace("schema: 1", "schema: 2")),
/unsupported/,
);
assert.throws(
() =>
readTask(
note.path,
note.source.replace("status: todo", "status: unknown"),
),
/status/,
);
assert.throws(
() =>
editTask(readTask(note.path, note.source)!, {
due: { date: "2026-02-30" },
}),
/deadline/,
);
assert.throws(
() => adoptNote("Bad.md", "---\nkey: 1\nkey: 2\n---\nBody"),
/YAML/,
);
assert.throws(() => newTask("../escape", fields), /name/);
assert.throws(() => newTask("CON", fields), /name/);
assert.throws(
() =>
newTask("Task", {
...fields,
plan: { start: "2026-10-10", end: "2026-10-09" },
}),
/end/,
);
});
test("date arithmetic preserves whole dates over leap years and daylight-saving boundaries", () => {
assert.equal(addDays("2024-02-28", 1), "2024-02-29");
assert.equal(addDays("2026-12-31", 1), "2027-01-01");
assert.equal(dayDistance("2026-03-07", "2026-03-09"), 2);
assert.equal(dayDistance("2026-10-31", "2026-11-02"), 2);
assert.equal(validDate("2026-02-29"), false);
});
test("save and reload use one note, and archive retains its file", async () => {
const { files, workspace } = memory();
const store = new TaskStore(workspace);
await store.create("Launch", fields, "Description");
assert.equal([...files.keys()].filter(isHiddenCard).length, 1);
const original = store.tasks[0];
await store.save(original, { status: "done", archived: true });
const reopened = new TaskStore(workspace);
await reopened.reload();
assert.equal(reopened.tasks[0].id, original.id);
assert.equal(reopened.tasks[0].status, "done");
assert.equal(reopened.tasks[0].archived, true);
assert.equal([...files.keys()].filter(isHiddenCard).length, 1);
});
test("stale edits cannot overwrite external changes", async () => {
const { workspace, files } = memory();
const store = new TaskStore(workspace);
await store.create("Task", fields, "Original");
const original = store.tasks[0];
const external = editTask(original, { body: "External change" });
files.set(original.path, external);
await assert.rejects(store.save(original, { status: "done" }), /changed/);
assert.equal(files.get(original.path), external);
});
test("duplicate identities are excluded and blocked even when introduced after reload", async () => {
const note = newTask("Task", fields);
const { workspace, files } = memory({ [note.path]: note.source });
const store = new TaskStore(workspace);
await store.reload();
const original = store.tasks[0];
files.set("Copy.md", note.source);
await assert.rejects(store.save(original, { status: "done" }), /duplicate/);
assert.equal(store.tasks.length, 0);
assert.match(store.issues[0], /Duplicate/);
assert.equal(files.get(note.path), note.source);
});
test("duplicate card titles preserve both cards and disposal blocks new writes", async () => {
const { workspace, files } = memory();
const store = new TaskStore(workspace);
await store.create("Task", fields, "Original");
const first = store.tasks[0];
await store.create("Task", fields, "Second card");
assert.equal(store.tasks.length, 2);
assert.equal(files.get(first.path), first.source);
assert.equal(new Set(store.tasks.map((task) => task.id)).size, 2);
store.dispose();
await assert.rejects(store.create("Later", fields, ""), /closed/);
});
@@ -0,0 +1,63 @@
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts";
import { migrateCards } from "../../../../src/lib/features/pm/storage/cards.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
function fixture() {
const note = newTask("Delete me", { status: "todo", tags: [], sessions: [], archived: false,
placements: { first: { listId: "todo" }, second: { listId: "doing" } } }, "Keep this source");
const task = readTask("Delete me.md", note.source)!;
const parent = newTask("Related", { status: "todo", tags: [], sessions: [], archived: false,
links: [{ taskId: task.id, relation: "relates" }], subtasks: [{ id: "sub", taskId: task.id, title: task.title, done: false }] }, "");
const files = new Map([[task.path, note.source], ["Related.md", parent.source]]);
let fail = false;
const workspace: Workspace = {
async list(folder = "") { return [...files.keys()].filter(path => folder ? path.startsWith(`${folder}/`) : !path.startsWith(".")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
async read(path) { if (!files.has(path)) throw Error("Missing"); return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async create(path, source) { if (fail || files.has(path)) throw Error("Write failed"); files.set(path, source); },
async write(path, source, expected) { if (fail) throw Error("Write failed"); assert.equal(files.get(path), expected); files.set(path, source); },
};
return { task, files, workspace, setFailure() { fail = true; } };
}
test("confirmed deletion removes legacy and migrated cards from all scopes and retains source records", async () => {
for (const migrate of [false, true]) {
const { workspace, files, task } = fixture();
if (migrate) await migrateCards(workspace, [task]);
const store = new TaskStore(workspace); await store.reload();
const before = new Map(files);
await store.deleteCard(store.tasks.find(item => item.id === task.id)!);
assert.deepEqual(store.tasks.map(item => item.title), ["Related"]);
for (const [path, source] of before) assert.equal(files.get(path), source);
assert.deepEqual(JSON.parse(files.get(deletedCardsPath)!).ids, [task.id]);
const fresh = new TaskStore(workspace); await fresh.reload();
assert.equal(fresh.tasks.some(item => item.id === task.id), false);
await assert.rejects(fresh.openSubtask(fresh.tasks[0].id, "sub"), /unavailable/);
assert.equal(fresh.tasks[0].links![0].taskId, task.id);
await assert.rejects(fresh.save(task, { archived: false }), /changed|duplicate/);
}
});
test("stale cards and failed deletion writes preserve the card", async () => {
const stale = fixture(); const store = new TaskStore(stale.workspace); await store.reload();
stale.files.set(stale.task.path, stale.task.source + "External edit\n");
await assert.rejects(store.deleteCard(stale.task), /changed/);
assert.equal(stale.files.has(deletedCardsPath), false);
const failed = fixture(); const next = new TaskStore(failed.workspace); await next.reload();
failed.setFailure(); await assert.rejects(next.deleteCard(failed.task), /Write failed/);
await next.reload(); assert.equal(next.tasks.length, 2);
});
test("damaged deletion records block card access instead of restoring deleted cards", async () => {
const { workspace, files } = fixture();
for (const source of ['{', '{"schema":2,"ids":[]}', '{"schema":1,"ids":[4]}']) {
files.set(deletedCardsPath, source);
const store = new TaskStore(workspace); await store.reload();
assert.equal(store.tasks.length, 0);
assert.ok(store.issues.some(issue => issue.startsWith("Deleted cards:")));
}
});
@@ -0,0 +1,108 @@
// The image data of description drafts: an image in an unsaved description survives a close, and a discard leaves no image data.
import test from "node:test";
import assert from "node:assert/strict";
import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts";
import { imageMarkdown, imagePath, saveImages } from "../../../../src/lib/features/pm/storage/images.ts";
import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { memoryWorkspace } from "./_memory.ts";
const one = "12345678-1234-1234-1234-123456789abc";
const two = "87654321-1234-1234-1234-123456789abc";
const data = "data:image/png;base64,aGVsbG8=";
const other = "data:image/gif;base64,R0lGOD==";
/** A workspace that records the path of each write and creation, in order. */
function recorded() {
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
const writes: string[] = [];
const { write, create } = workspace;
workspace.write = async (path, contents, expected) => { await write(path, contents, expected); writes.push(path); };
workspace.create = async (path, contents) => { await create!(path, contents); writes.push(path); };
return { workspace, writes };
}
test("a draft from an earlier version, without an image record, still loads", async () => {
const { workspace } = recorded();
const draft = new DescriptionDraft(workspace, "task");
workspace.files.set(draft.path, JSON.stringify({ schema: 1, body: `Old ${imageMarkdown("a.png", one)}` }) + "\n");
const reopened = new DescriptionDraft(workspace, "task");
assert.equal(await reopened.load(), `Old ${imageMarkdown("a.png", one)}`);
assert.deepEqual(await reopened.loadImages(), new Map());
await reopened.save("Newer text");
assert.equal(workspace.files.has(reopened.imagesPath), false, "A draft without images makes no image record");
});
test("the draft keeps the data of its unsaved images, and the image folder stays empty", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
const body = `Text\n${imageMarkdown("a.png", one)}`;
await draft.save(body, new Map([[one, data]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path], "The image data comes before the reference");
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
// A text change does not write the image data again.
await draft.save(`${body}\nMore`, new Map([[one, data]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.path]);
const reopened = new DescriptionDraft(workspace, "task");
assert.equal(await reopened.load(), `${body}\nMore`);
assert.deepEqual(await reopened.loadImages(), new Map([[one, data]]));
// A later save writes the image file from the restored data.
assert.deepEqual(await saveImages(workspace, body, await reopened.loadImages()), [one]);
assert.match(workspace.files.get(imagePath(one))!, /data:image\/png;base64,aGVsbG8=/);
});
test("a removed image keeps its data until the text without the reference is saved", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
await draft.save(`${imageMarkdown("a.png", one)}\n${imageMarkdown("b.gif", two)}`, new Map([[one, data], [two, other]]));
writes.length = 0;
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
assert.deepEqual(writes, [draft.path, draft.imagesPath]);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
// An image that replaces another one: the record holds both images while the text changes.
writes.length = 0;
await draft.save(imageMarkdown("b.gif", two), new Map([[two, other]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.imagesPath]);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[two, other]]));
});
test("a discarded draft keeps no image data and writes no image file", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
writes.length = 0;
await draft.save(null, new Map([[one, data]]));
assert.deepEqual(writes, [draft.path, draft.imagesPath], "The text goes first, so that no saved reference loses its data");
assert.equal(await new DescriptionDraft(workspace, "task").load(), null);
assert.equal(workspace.files.get(draft.imagesPath), JSON.stringify({ schema: 1, images: {} }) + "\n");
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
});
test("an invalid image record stops the draft, and a stale writer cannot overwrite the images", async () => {
const { workspace } = recorded();
const draft = new DescriptionDraft(workspace, "task");
for (const images of [null, [], { "../secret": data }, { [one]: "data:image/svg+xml;base64,PHN2Zz4=" }]) {
workspace.files.set(draft.imagesPath, JSON.stringify({ schema: 1, images }));
await assert.rejects(draft.loadImages(), /description draft is invalid/);
}
workspace.files.delete(draft.imagesPath);
const first = new DescriptionDraft(workspace, "task"), second = new DescriptionDraft(workspace, "task");
await first.loadImages();
await second.loadImages();
await first.save(imageMarkdown("a.png", one), new Map([[one, data]]));
await assert.rejects(second.save(imageMarkdown("b.gif", two), new Map([[two, other]])), /exists/);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
});
test("an image save includes extra IDs, for example a card cover, and returns the saved IDs", async () => {
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
const pending = new Map([[one, data], [two, other]]);
assert.deepEqual(await saveImages(workspace, "", pending, [], [two]), [two]);
assert.equal(workspace.files.has(imagePath(one)), false);
assert.equal(workspace.files.has(imagePath(two)), true);
});
@@ -0,0 +1,31 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { headingEdit } from "../../../../src/lib/features/pm/model/description-format.ts";
function apply(value: string, start: number, end = start) {
const edit = headingEdit(value, start, end);
return { value: value.slice(0, edit.start) + edit.text + value.slice(edit.end), start: edit.selectionStart, end: edit.selectionEnd };
}
test("Heading formats the caret line and preserves the caret inside its text", () => {
assert.deepEqual(apply("Before\nTyped text\nAfter", 12), { value: "Before\n## Typed text\nAfter", start: 15, end: 15 });
assert.deepEqual(apply("Typed text", 0), { value: "## Typed text", start: 3, end: 3 });
assert.deepEqual(apply("Typed text", 10), { value: "## Typed text", start: 13, end: 13 });
});
test("Heading preserves selected text and formats all selected lines", () => {
assert.deepEqual(apply("One line\nTwo lines\nLast", 2, 12), { value: "## One line\n## Two lines\nLast", start: 5, end: 18 });
assert.deepEqual(apply("One\nTwo", 0, 4), { value: "## One\nTwo", start: 3, end: 7 });
});
test("Heading changes an existing heading without duplicate markers", () => {
assert.deepEqual(apply("# Title", 7), { value: "## Title", start: 8, end: 8 });
assert.deepEqual(apply("## Title", 5), { value: "## Title", start: 5, end: 5 });
assert.deepEqual(apply("### Title", 1), { value: "## Title", start: 3, end: 3 });
});
test("Heading leaves the caret after the marker on empty lines", () => {
assert.deepEqual(apply("", 0), { value: "## ", start: 3, end: 3 });
assert.deepEqual(apply("Text\n", 5), { value: "Text\n## ", start: 8, end: 8 });
assert.deepEqual(apply("\nText", 0), { value: "## \nText", start: 3, end: 3 });
});
+107
View File
@@ -0,0 +1,107 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
imageMarkdown,
imageReferences,
imagePath,
parseImage,
saveImages,
maxImageBytes,
} from "../../../../src/lib/features/pm/storage/images.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
const id = "12345678-1234-1234-1234-123456789abc";
const data = "data:image/png;base64,aGVsbG8=";
test("image references preserve surrounding text and restrict private paths", () => {
const markdown = imageMarkdown("shot [one]\n\\test.png", id);
assert.equal(markdown, `![shot one test.png](pm-image:${id})`);
const body = `Before\n${markdown}\nAfter`;
assert.deepEqual(imageReferences(body), [
{ id, name: "shot one test.png", markdown, index: 7 },
]);
assert.deepEqual(
imageReferences(
"![remote](https://example.com/a.png) ![bad](pm-image:../../secret)",
),
[],
);
assert.throws(() => imagePath("../../secret"), /invalid/);
});
test("saved image data rejects unsupported and executable sources", () => {
assert.equal(parseImage(JSON.stringify({ schema: 1, data })), data);
for (const value of [
null,
{},
{ schema: 1, data: "https://example.com/image.png" },
{ schema: 1, data: "data:image/svg+xml;base64,PHN2Zz4=" },
{ schema: 1, data: "data:image/png;base64,***=" },
])
assert.throws(() => parseImage(JSON.stringify(value)));
assert.throws(
() => parseImage("x".repeat(Math.ceil(maxImageBytes / 3) * 4 + 257)),
/50 MiB/,
);
});
test("save writes only referenced images, protects existing files, and permits retry", async () => {
const files = new Map<string, string>();
const writes: string[] = [];
const workspace: Workspace = {
async list() {
return [];
},
async read(path) {
return files.get(path)!;
},
async readOptional(path) {
return files.get(path) ?? null;
},
async create(path, source) {
if (files.has(path)) throw new Error("Already exists");
files.set(path, source);
writes.push(path);
},
async write() {
throw new Error("Unexpected overwrite");
},
};
const pending = new Map([
[id, data],
["87654321-1234-1234-1234-123456789abc", data],
]);
const body = imageMarkdown("Screenshot", id);
await saveImages(workspace, body, pending);
assert.deepEqual(writes, [".runestone/pm/.gitignore", imagePath(id)]);
await saveImages(workspace, body, pending);
assert.equal(writes.length, 2);
files.set(imagePath(id), "other image");
await assert.rejects(saveImages(workspace, body, pending), /Already exists/);
assert.equal(files.get(imagePath(id)), "other image");
});
test("attachment metadata saves staged images without description references", async () => {
const files = new Map<string, string>();
const workspace: Workspace = {
async list() { return []; },
async read(path) { return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async create(path, source) { files.set(path, source); },
async write() { throw new Error("Unexpected overwrite"); },
};
await saveImages(workspace, "", new Map([[id, data]]), [{ id, name: "Attachment.png" }]);
assert.equal(parseImage(files.get(imagePath(id))!), data);
});
test("image storage accepts exactly 50 MiB and rejects one extra byte", async () => {
assert.equal(maxImageBytes, 50 * 1024 * 1024);
const data = `data:image/png;base64,${Buffer.alloc(maxImageBytes).toString("base64")}`;
const files = new Map<string, string>();
const workspace: Workspace = {
async list() { return []; }, async read(path) { return files.get(path)!; }, async readOptional(path) { return files.get(path) ?? null; },
async write() { throw new Error("Unexpected overwrite"); },
async create(path, source) { files.set(path, source); },
};
await saveImages(workspace, "", new Map([[id, data]]), [{ id, name: "large.png" }]);
assert.equal(parseImage(files.get(imagePath(id))!), data);
const tooLarge = `data:image/png;base64,${Buffer.alloc(maxImageBytes + 1).toString("base64")}`;
assert.throws(() => parseImage(JSON.stringify({ schema: 1, data: tooLarge })), /50 MiB/);
});
+364
View File
@@ -0,0 +1,364 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
defaultLabels,
labelsPath,
parseLabels,
validateLabels,
} from "../../../../src/lib/features/pm/storage/labels.ts";
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { editTask, newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import {
validateFields,
type TaskFields,
type Workspace,
} from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
function fixture() {
const files = new Map<string, string>();
const writes: string[] = [];
const workspace: Workspace = {
async list() {
return [...files.keys()].map((path) => ({
name: path.split("/").at(-1)!,
rel_path: path,
kind: "file",
}));
},
async read(path) {
if (!files.has(path)) throw new Error("Missing file");
return files.get(path)!;
},
async readOptional(path) {
return files.get(path) ?? null;
},
async create(path, source) {
if (files.has(path)) throw new Error("File already exists");
files.set(path, source);
writes.push(path);
},
async write(path, source, expected) {
if (files.get(path) !== expected) throw new Error("File changed");
files.set(path, source);
writes.push(path);
},
};
return { files, writes, workspace, store: new TaskStore(workspace) };
}
test("old notes and custom tags remain independent of saved labels", () => {
const note = newTask(
"Task",
{ ...fields, tags: ["customer, success"], color: "pink" },
"Keep **details**.\n",
);
const source = note.source.replace("---\n", "---\nowner: Ada # keep\n");
const old = readTask(note.path, source)!;
assert.equal(old.labels, undefined);
const labeled = readTask(
note.path,
editTask(old, { labels: ["bug", "feature", "missing-label"] }),
)!;
assert.deepEqual(labeled.labels, ["bug", "feature", "missing-label"]);
const moved = readTask(note.path, editTask(labeled, { status: "doing" }))!;
assert.deepEqual(moved.labels, labeled.labels);
const cleared = readTask(note.path, editTask(moved, { labels: [] }))!;
assert.deepEqual(cleared.labels, []);
assert.deepEqual(cleared.tags, old.tags);
assert.equal(cleared.color, old.color);
assert.equal(cleared.body, old.body);
assert.match(cleared.source, /owner: Ada # keep/);
for (const labels of [null, "bug", [1], [""], ["bug", "bug"], ["bad id"]])
assert.throws(
() => validateFields({ ...fields, labels } as TaskFields),
/label IDs/,
);
});
test("one catalog serves every board and renames leave task files unchanged", async () => {
const { files, workspace, writes } = fixture();
const first = newBoardSource(),
second = newBoardSource();
files.set("First.md", first);
files.set("Second.md", second);
const a = new TaskStore(workspace, {
id: parseBoard(first).id,
path: "First.md",
});
const b = new TaskStore(workspace, {
id: parseBoard(second).id,
path: "Second.md",
});
await a.reload();
assert.deepEqual(a.labels.value, defaultLabels());
assert.equal(files.has(labelsPath), false);
await a.create(
"Shared label",
{ ...fields, labels: ["bug"] },
"Keep details.",
);
const task = a.tasks[0];
await a.saveLabels(
[
...a.labels.value,
{ id: "review", name: " Needs review ", color: "purple" },
],
a.labels.source,
);
await b.reload();
assert.equal(b.labels.value.at(-1)!.name, "Needs review");
assert.deepEqual(b.tasks[0].labels, ["bug"]);
const changed = b.labels.value.map((label) =>
label.id === "bug"
? { ...label, name: "Defect", color: "orange" as const, archived: true }
: label,
);
writes.length = 0;
await b.saveLabels(changed, b.labels.source);
await a.reload();
assert.deepEqual(writes, [labelsPath]);
assert.equal(a.labels.value[0].name, "Defect");
assert.equal(a.labels.value[0].color, "orange");
assert.equal(a.labels.value[0].archived, true);
assert.equal(files.get(task.path), task.source);
});
test("expanded palette colors persist in cards and shared labels", async () => {
const { store, workspace } = fixture();
const colors = [
"amber",
"lime",
"teal",
"cyan",
"indigo",
"magenta",
"brown",
"slate",
"gray",
] as const;
await store.reload();
await store.saveLabels(
[
...defaultLabels(),
...colors.map((color) => ({ id: color, name: color, color })),
],
store.labels.source,
);
for (const color of colors)
await store.create(
`Palette ${color}`,
{ ...fields, color, labels: [color] },
"Keep these details.",
);
const reopened = new TaskStore(workspace);
await reopened.reload();
for (const color of colors) {
const task = reopened.tasks.find(
(task) => task.title === `Palette ${color}`,
)!;
assert.equal(task.color, color);
assert.deepEqual(task.labels, [color]);
assert.equal(task.body, "Keep these details.");
assert.equal(
reopened.labels.value.find((label) => label.id === color)!.color,
color,
);
}
});
test("catalog validation blocks duplicate names, bad colors, IDs, and archive states", () => {
for (const labels of [
null,
{},
[null],
[{ id: "bug", name: "Bug", color: "url(bad)" }],
[{ id: "bug", name: "\nBug", color: "red" }],
[{ id: "bug", name: " ", color: "red" }],
[{ id: "bug", name: "Bug", color: "red", archived: "yes" }],
[
...defaultLabels(),
{ id: "other", name: " BUG ", color: "blue", archived: true },
],
[...defaultLabels(), { id: "bug", name: "Another", color: "blue" }],
])
assert.throws(() => validateLabels(labels));
assert.throws(() => parseLabels('{"schema":2,"labels":[]}'), /schema/);
assert.throws(() => parseLabels("broken json"), /saved labels file/);
assert.deepEqual(parseLabels('{"schema":1,"labels":[]}').labels, []);
});
test("concurrent catalog creation and stale edits cannot replace newer labels", async () => {
const { store, workspace, files } = fixture();
const other = new TaskStore(workspace);
await store.reload();
await other.reload();
await store.saveLabels(defaultLabels(), store.labels.source);
const created = files.get(labelsPath);
await assert.rejects(
other.saveLabels(defaultLabels(), other.labels.source),
/already exists/,
);
assert.equal(files.get(labelsPath), created);
await other.reload();
const expected = other.labels.source;
await store.saveLabels(
store.labels.value.map((label) => ({ ...label, archived: true })),
store.labels.source,
);
const updated = files.get(labelsPath);
await assert.rejects(other.saveLabels(defaultLabels(), expected), /changed/);
assert.equal(files.get(labelsPath), updated);
await store.reload();
await store.saveLabels([], store.labels.source);
assert.deepEqual(store.labels.value, []);
});
test("catalog read failures and invalid files leave task editing available without overwriting the catalog", async () => {
const { store, files, workspace } = fixture();
const task = newTask("Keep task", { ...fields, labels: ["unknown"] });
files.set(task.path, task.source);
files.set(labelsPath, "invalid json");
await store.reload();
assert.equal(store.tasks.length, 1);
assert.match(store.issues.join(" "), /Saved labels/);
assert.equal(store.labels.source, undefined);
await assert.rejects(store.saveLabels(defaultLabels(), null), /unavailable/);
await store.save(store.tasks[0], { status: "done" });
assert.equal(files.get(labelsPath), "invalid json");
assert.deepEqual(store.tasks[0].labels, ["unknown"]);
workspace.readOptional = async () => {
throw new Error("Permission denied");
};
await store.reload();
assert.match(store.issues.join(" "), /Permission denied/);
await assert.rejects(store.saveLabels(defaultLabels(), null), /unavailable/);
});
test("catalog writes preserve unknown metadata and propagate filesystem errors", async () => {
const { store, files, workspace } = fixture();
const source = JSON.stringify({
schema: 1,
future: { keep: true },
labels: defaultLabels().map((label) => ({ ...label, extra: "keep" })),
});
files.set(labelsPath, source);
await store.reload();
await store.saveLabels(store.labels.value, store.labels.source);
const data = JSON.parse(files.get(labelsPath)!);
assert.deepEqual(data.future, { keep: true });
assert.equal(data.labels[0].extra, "keep");
const before = files.get(labelsPath);
workspace.write = async () => {
throw new Error("Disk full");
};
await assert.rejects(
store.saveLabels(defaultLabels(), store.labels.source),
/Disk full/,
);
assert.equal(store.labels.source, before);
assert.equal(files.get(labelsPath), before);
});
test("a pending scan cannot replace saved label edits", async () => {
const { store, workspace } = fixture();
await store.reload();
let release!: () => void, entered!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const started = new Promise<void>((resolve) => {
entered = resolve;
});
const read = workspace.readOptional!;
let blocked = false;
workspace.readOptional = async (path) => {
if (path !== labelsPath || blocked) return read(path);
blocked = true;
const source = await read(path);
entered();
await gate;
return source;
};
const pending = store.reload();
await started;
await store.saveLabels(
[...defaultLabels(), { id: "new", name: "New label", color: "pink" }],
null,
);
release();
await pending;
assert.equal(store.labels.value.at(-1)!.id, "new");
assert.notEqual(store.labels.source, null);
});
test("older workspaces can read catalogs through listing but cannot create without create support", async () => {
const { store, workspace, files } = fixture();
delete workspace.readOptional;
delete workspace.create;
await store.reload();
await assert.rejects(
store.saveLabels(defaultLabels(), null),
/Update RuneStone/,
);
files.set(labelsPath, JSON.stringify({ schema: 1, labels: defaultLabels() }));
await store.reload();
assert.deepEqual(store.labels.value, defaultLabels());
store.dispose();
await assert.rejects(
store.saveLabels(defaultLabels(), store.labels.source),
/closed/,
);
});
test("deleting labels clears active, archived, unlisted, and shared cards while preserving unrelated data", async () => {
const { store, files, workspace } = fixture();
for (let index = 0; index < 4; index++) {
const task = newTask(`Card ${index}`, {
...fields, archived: index === 1, labels: ["bug", "feature", "unknown"], tags: ["bug"],
placements: index === 2 ? {} : { a: { listId: "todo", order: "m" }, b: { listId: null } },
}, "Keep **body**.");
files.set(task.path, task.source);
}
await store.reload();
await store.saveLabels(store.labels.value.filter(label => label.id !== "bug"), store.labels.source);
const reopened = new TaskStore(workspace);
await reopened.reload();
assert.equal(reopened.tasks.length, 4);
for (const task of reopened.tasks) {
assert.deepEqual(task.labels, ["feature", "unknown"]);
assert.deepEqual(task.tags, ["bug"]);
assert.equal(task.body, "Keep **body**.");
}
assert.equal(reopened.tasks[1].archived, true);
assert.deepEqual(reopened.tasks[0].placements, { a: { listId: "todo", order: "m" }, b: { listId: null } });
assert.equal(reopened.labels.value.some(label => label.id === "bug"), false);
});
test("failed label deletion keeps definitions and allows guarded retry", async () => {
const { store, files, workspace } = fixture();
for (const name of ["A", "B"]) {
const task = newTask(name, { ...fields, labels: ["bug"] }, "Keep body");
files.set(task.path, task.source);
}
await store.reload();
const next = store.labels.value.filter(label => label.id !== "bug");
const write = workspace.write;
workspace.write = async (path, source, expected) => {
if (path === store.tasks.find(task => task.title === "B")!.path) throw new Error("Disk full");
return write(path, source, expected);
};
await assert.rejects(store.saveLabels(next, store.labels.source), /Disk full/);
assert.equal(store.labels.value.some(label => label.id === "bug"), true);
assert.deepEqual(store.tasks.find(task => task.title === "B")!.labels, ["bug"]);
workspace.write = write;
await store.saveLabels(next, store.labels.source);
await store.reload();
assert.equal(store.tasks.every(task => !task.labels?.includes("bug")), true);
});
+118
View File
@@ -0,0 +1,118 @@
// The legacy format: the native feature finds visible boards, task notes, and the root label file, and offers the
// migration. The migration of the offer is the migration of the plugin, with its backups.
import test from "node:test";
import assert from "node:assert/strict";
import { findLegacy, hasLegacy, mentionsProjectData } from "../../../../src/lib/features/pm/storage/legacy.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { boardMarkdown, catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts";
import { labelsPath, legacyLabelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { fields, hiddenWorkspace, memoryWorkspace } from "./_memory.ts";
const labels = JSON.stringify({ schema: 1, labels: [{ id: "bug", name: "Bug", color: "red" }] });
test("only notes that name runestone_pm in their properties count as Project Management data", () => {
assert.equal(mentionsProjectData("---\nrunestone_pm:\n kind: task\n---\n"), true);
assert.equal(mentionsProjectData(String.fromCharCode(0xfeff) + "---\r\ntitle: x\r\nrunestone_pm: {}\r\n---\r\n"), true);
assert.equal(mentionsProjectData("# Plan\nrunestone_pm: in the body\n"), false);
assert.equal(mentionsProjectData("---\ntitle: x\n---\nrunestone_pm: in the body\n"), false);
assert.equal(mentionsProjectData("---\nother_runestone_pm: x\n---\n"), false);
});
test("an empty workspace or a migrated workspace has nothing to offer", async () => {
assert.equal(hasLegacy(await findLegacy(memoryWorkspace({ "Notes/Plain.md": "# Plain\n" }))), false);
const workspace = hiddenWorkspace([{ id: "hidden", title: "Hidden" }]);
assert.deepEqual(await findLegacy(workspace), { boards: [], cards: [], invalid: [], labels: false });
});
test("visible boards, task notes, and the root label file are found without a parse of plain notes", async () => {
const board = defaultBoard("visible-board");
const workspace = memoryWorkspace({
"Boards/Plan.md": boardMarkdown(board),
"Tasks/Write.md": newTask("Write", fields(), "Body", "write").source,
"Notes/Plain.md": "---\ntitle: [broken yaml\n---\nPlain note.\n",
"Notes/Broken.md": "---\nrunestone_pm: [\n---\n",
[legacyLabelsPath]: labels,
});
const content = await findLegacy(workspace);
assert.deepEqual(content, { boards: ["Boards/Plan.md"], cards: ["Tasks/Write.md"], invalid: ["Notes/Broken.md"], labels: true });
assert.equal(hasLegacy(content), true);
});
test("migrated, deleted, and already saved data does not count again", async () => {
const board = defaultBoard("old-board");
const workspace = hiddenWorkspace([{ id: "copied", title: "Copied" }], {
"Old.md": boardMarkdown(board),
"Gone.md": boardMarkdown(defaultBoard("gone-board")),
"Copied.md": newTask("Copied", fields(), "", "copied").source,
"Deleted.md": newTask("Deleted", fields(), "", "deleted").source,
[deletedCardsPath]: JSON.stringify({ schema: 1, ids: ["deleted"] }),
[legacyLabelsPath]: labels,
[labelsPath]: labels,
});
const catalog = JSON.parse(workspace.files.get(catalogPath)!);
catalog.boards.push({ name: "Old", value: board });
catalog.deletedBoardIds = ["gone-board"];
workspace.files.set(catalogPath, JSON.stringify(catalog));
assert.deepEqual(await findLegacy(workspace), { boards: [], cards: [], invalid: [], labels: false });
});
test("the offer migrates every legacy board, task note, and the label file with backups, and changes no original", async () => {
const board = defaultBoard("visible-board");
const originals = {
"Boards/Plan.md": boardMarkdown(board),
"Tasks/Write.md": newTask("Write", fields({ placements: { "visible-board": { listId: "todo" } } }), "Body", "write").source,
"Tasks/Read.md": newTask("Read", fields(), "", "read").source,
[legacyLabelsPath]: labels,
};
const workspace = memoryWorkspace(originals);
// The native view sees nothing before the migration.
const hidden = new TaskStore(workspace, undefined, { legacy: false });
await hidden.reload();
assert.equal(hidden.tasks.length, 0);
assert.equal(hidden.boards.length, 0);
// The offer: a legacy store migrates all boards, the labels, and every visible task note.
const legacy = new TaskStore(workspace, undefined, { legacy: true });
await legacy.reload();
const files = await legacy.migrateStorage(legacy.tasks.filter(task => !isHiddenCard(task.path)).map(task => task.id));
legacy.dispose();
assert.deepEqual(files.map(file => file.path).sort(), ["Boards/Plan.md", "Tasks/Read.md", "Tasks/Write.md", legacyLabelsPath].sort());
for (const file of files) assert.equal(workspace.files.get(file.backup), file.source);
for (const [path, source] of Object.entries(originals)) assert.equal(workspace.files.get(path), source, path);
assert.equal(hasLegacy(await findLegacy(workspace)), false);
await hidden.reload();
assert.deepEqual(hidden.tasks.map(task => task.id).sort(), ["read", "write"]);
assert.deepEqual(hidden.boards.map(item => [item.id, item.name]), [["visible-board", "Plan"]]);
assert.deepEqual(hidden.labels.value.map(label => label.id), ["bug"]);
});
test("Add existing note copies a plain note into a private card and leaves the note unchanged", async () => {
const note = "---\ntags: [keep]\n---\n# Research\nDetails.\n";
const workspace = hiddenWorkspace([], { "Notes/Research.md": note });
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
await store.reload();
const card = await store.adopt("Notes/Research.md");
assert.equal(workspace.files.get("Notes/Research.md"), note);
assert.equal(card.path, cardPath(card.id));
assert.equal(card.title, "Research");
assert.equal(card.body, "# Research\nDetails.\n");
assert.equal(card.placements?.board.listId, "todo");
assert.match(workspace.files.get(card.path)!, /^tags: \[ keep \]$/m);
assert.deepEqual(store.tasks.map(task => task.id), [card.id]);
// A legacy task note migrates with a backup and keeps its ID.
const legacyNote = newTask("Legacy", fields(), "Old body", "legacy-id").source;
workspace.files.set("Notes/Legacy.md", legacyNote);
const migrated = await store.adopt("Notes/Legacy.md");
assert.equal(migrated.id, "legacy-id");
assert.equal(migrated.path, cardPath("legacy-id"));
assert.equal(workspace.files.get("Notes/Legacy.md"), legacyNote);
assert.equal(workspace.files.get(".runestone/pm/backups/Notes/Legacy.md"), legacyNote);
assert.equal(readTask(migrated.path, workspace.files.get(migrated.path)!)!.placements?.board.listId, "todo");
// A second add of the same note finds the same card.
assert.equal((await store.adopt("Notes/Legacy.md")).path, migrated.path);
assert.equal(store.tasks.length, 2);
});
@@ -0,0 +1,514 @@
import test from "node:test";
import assert from "node:assert/strict";
import { newBoardSource, parseBoard, boardDocument } from "../../../../src/lib/features/pm/storage/board.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: ["shared"],
sessions: [
{
id: "session",
start: "2026-10-08T16:00:00Z",
end: "2026-10-08T17:00:00Z",
timeZone: "America/Vancouver",
},
],
due: { date: "2026-10-30" },
plan: { start: "2026-10-05", end: "2026-10-31" },
archived: false,
};
function fixture() {
const first = newBoardSource(),
second = newBoardSource();
const files = new Map<string, string>([
["Project/Launch.md", first],
["Project/Personal.md", second],
["Task.md", newTask("Task", fields, "Keep this description.").source],
]);
let fail = false;
const writes: string[] = [];
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async list(parent = "") {
const entries = new Map();
for (const path of files.keys()) {
const prefix = parent ? parent + "/" : "";
if (!path.startsWith(prefix)) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: prefix + parts[0],
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async read(path) {
const source = files.get(path);
if (source === undefined) throw Error("Missing");
return source;
},
async write(path, source, expected) {
if (fail) throw Error("Disk failure");
assert.equal(files.get(path), expected);
writes.push(path);
files.set(path, source);
},
async create(path, source) {
if (files.has(path)) throw Error("Exists");
files.set(path, source);
},
};
const a = new TaskStore(workspace, {
id: parseBoard(first).id,
path: "Project/Launch.md",
});
const b = new TaskStore(workspace, {
id: parseBoard(second).id,
path: "Project/Personal.md",
});
const all = new TaskStore(workspace);
return {
files,
workspace,
a,
b,
all,
writes,
failWrites() {
fail = true;
},
};
}
test("a shared task synchronizes status lists and keeps one schedule", async () => {
const { a, b, all, files, writes } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.reload();
const original = a.tasks[0];
writes.length = 0;
await a.moveTask(original, "done");
await b.reload();
await all.reload();
assert.deepEqual(writes, ["Task.md"]);
assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "done");
assert.equal(b.board.listFor(b.scopedTasks[0])?.id, "done");
assert.equal(b.scopedTasks[0].status, "done");
assert.equal(all.scopedTasks.length, 1);
assert.equal(all.scopedTasks[0].id, original.id);
assert.deepEqual(all.scopedTasks[0].plan, fields.plan);
assert.deepEqual(all.scopedTasks[0].sessions, fields.sessions);
assert.deepEqual(all.scopedTasks[0].due, fields.due);
assert.equal(all.scopedTasks[0].body, original.body);
assert.equal(files.size, 3);
await b.save(b.scopedTasks[0], { due: { date: "2026-11-01" } });
await a.reload();
assert.equal(a.scopedTasks[0].due?.date, "2026-11-01");
});
test("leaving a Done list reopens completion and removal affects only one board", async () => {
const { a, b, all } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.reload();
await a.moveTask(a.tasks[0], "done");
await a.changeBoard(() => a.board.add("This week", null));
await a.moveTask(a.tasks[0], a.board.value.lists.at(-1)!.id);
assert.equal(a.tasks[0].status, "todo");
await a.removeFromBoard(a.tasks[0]);
assert.equal(a.scopedTasks.length, 0);
await b.reload();
await all.reload();
assert.equal(b.scopedTasks.length, 1);
assert.equal(all.scopedTasks.length, 1);
assert.equal(all.scopedTasks[0].archived, false);
});
test("All tasks moves synchronize memberships in one write and append to destination lists", async () => {
const { a, b, all, writes } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.create("Existing done", { ...fields, status: "done" }, "");
await all.reload();
const task = all.tasks.find((task) => task.title === "Task")!;
writes.length = 0;
await all.moveTask(task, "done");
assert.deepEqual(writes, ["Task.md"]);
for (const board of [a, b]) {
await board.reload();
const saved = board.scopedTasks.find((item) => item.id === task.id)!;
assert.equal(saved.status, "done");
assert.equal(board.board.listFor(saved)?.id, "done");
assert.deepEqual(saved.sessions, task.sessions);
assert.deepEqual(saved.plan, task.plan);
assert.deepEqual(saved.due, task.due);
assert.equal(saved.body, task.body);
}
assert.deepEqual(
a.cardsInList("done").map((task) => task.title),
["Existing done", "Task"],
);
assert.deepEqual(
b.scopedTasks.map((task) => task.title),
["Task"],
);
});
test("status changes use each board's designated list and preserve unmatched placements", async () => {
const { a, b, all } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.changeBoard(() => a.board.add("Released", "done"));
const destination = a.board.value.lists.at(-1)!.id;
await a.changeBoard(() =>
a.board.update((board) => {
board.defaults.done = destination;
}),
);
await b.changeBoard(() => b.board.remove("done"));
await all.reload();
const previous = all.tasks[0].placements![b.board.reference!.id];
await all.save(all.tasks[0], { status: "done" });
await a.reload();
await b.reload();
assert.equal(a.board.listFor(a.tasks[0])?.id, destination);
assert.deepEqual(b.tasks[0].placements![b.board.reference!.id], previous);
assert.equal(b.tasks[0].status, "done");
});
test("status changes preserve absent memberships and unavailable board placements", async () => {
const { a, b, all, files } = fixture();
await a.adopt("Task.md");
await all.reload();
await all.moveTask(all.tasks[0], "doing");
assert.equal(
Object.hasOwn(all.tasks[0].placements!, b.board.reference!.id),
false,
);
await a.reload();
const previous = a.tasks[0].placements![a.board.reference!.id];
files.delete("Project/Launch.md");
await all.moveTask(all.tasks[0], "done");
assert.deepEqual(all.tasks[0].placements![a.board.reference!.id], previous);
});
test("failed All tasks moves preserve every placement and the shared status", async () => {
const { a, b, all, files, failWrites } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await all.reload();
const before = all.tasks[0];
failWrites();
await assert.rejects(all.moveTask(before, "done"), /Disk failure/);
assert.equal(files.get("Task.md"), before.source);
assert.deepEqual(all.tasks[0], before);
});
test("board creation does not collect every workspace task", async () => {
const { a, b } = fixture();
await a.reload();
await b.reload();
assert.equal(a.scopedTasks.length, 0);
await a.create("New", fields, "");
await b.reload();
assert.equal(a.scopedTasks.length, 1);
assert.equal(b.scopedTasks.length, 0);
assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "todo");
});
test("moving or deleting a board never moves or deletes its tasks", async () => {
const { a, all, files } = fixture();
await a.adopt("Task.md");
const taskSource = files.get("Task.md");
files.set("Elsewhere/Renamed.md", files.get("Project/Launch.md")!);
files.delete("Project/Launch.md");
await a.reload();
assert.equal(a.board.reference?.path, "Elsewhere/Renamed.md");
assert.equal(a.board.name, "Renamed");
assert.equal(a.scopedTasks.length, 1);
files.delete("Elsewhere/Renamed.md");
await a.reload();
await all.reload();
assert.equal(a.board.available, false);
assert.equal(all.scopedTasks.length, 1);
assert.equal(files.get("Task.md"), taskSource);
await assert.rejects(a.create("Lost", fields, ""), /unavailable/);
});
test("invalid and duplicate boards do not block the workspace schedule", async () => {
const { a, all, files } = fixture();
files.set("Copy.md", files.get("Project/Launch.md")!);
files.set(
"Project/Personal.md",
files.get("Project/Personal.md")!.replace("schema: 1", "schema: 99"),
);
await all.reload();
await a.reload();
assert.equal(all.tasks.length, 1);
assert.equal(all.boards.length, 0);
assert.equal(a.board.available, false);
assert.ok(all.issues.some((issue) => issue.includes("Duplicate board ID")));
assert.ok(all.issues.some((issue) => issue.includes("unsupported format")));
});
test("failed placement writes preserve both membership and status", async () => {
const { a, files, failWrites } = fixture();
await a.adopt("Task.md");
const source = files.get("Task.md");
failWrites();
await assert.rejects(a.moveTask(a.tasks[0], "done"), /Disk failure/);
assert.equal(files.get("Task.md"), source);
assert.equal(a.tasks[0].status, "todo");
assert.equal(a.board.listFor(a.tasks[0])?.id, "todo");
});
test("an open stale card cannot overwrite another board's edit", async () => {
const { a, b, files } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.reload();
const stale = a.tasks[0];
await b.moveTask(b.tasks[0], "doing");
const source = files.get("Task.md");
await assert.rejects(a.moveTask(stale, "done"), /task changed/);
assert.equal(files.get("Task.md"), source);
});
test("board properties and prose survive edits and boards cannot become task notes", async () => {
const { a, files } = fixture();
const source =
files
.get("Project/Launch.md")!
.replace("runestone_pm:", "owner: Ada # keep\nrunestone_pm:") +
"Board description.\n";
files.set("Project/Launch.md", source);
await a.reload();
await a.changeBoard(() => a.board.add("Review", null));
const saved = files.get("Project/Launch.md")!;
assert.ok(saved.includes("owner: Ada # keep"));
assert.ok(saved.endsWith("Board description.\n"));
assert.equal(readTask("Board.md", saved), null);
assert.throws(() => adoptNote("Board.md", saved), /already contains Project Management data/);
assert.equal(boardDocument("# A normal note", "Board.md"), null);
});
test("renaming a board resolves its current path and preserves shared tasks and lists", async () => {
const { a, b, all, files, writes } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.changeBoard(() => a.board.add("Review", null));
const source = files.get("Project/Launch.md")!;
const taskSource = files.get("Task.md");
files.set("Moved/Launch.md", source);
files.delete("Project/Launch.md");
writes.length = 0;
await a.renameBoard(" Release 1.2 ", async (document, name) => {
assert.equal(document.path, "Moved/Launch.md");
assert.equal(document.id, parseBoard(source).id);
assert.equal(name, "Release 1.2");
files.set("Moved/Release 1.2.md", files.get(document.path)!);
files.delete(document.path);
return "Moved/Release 1.2.md";
});
assert.equal(a.board.name, "Release 1.2");
assert.equal(a.board.reference?.path, "Moved/Release 1.2.md");
assert.equal(a.board.value.lists.at(-1)?.name, "Review");
assert.equal(files.get("Moved/Release 1.2.md"), source);
assert.equal(files.get("Task.md"), taskSource);
assert.deepEqual(writes, []);
await b.reload();
await all.reload();
assert.equal(a.scopedTasks.length, 1);
assert.equal(b.scopedTasks.length, 1);
assert.equal(all.scopedTasks.length, 1);
await a.changeBoard(() => a.board.add("After rename", null));
await a.moveTask(a.scopedTasks[0], "doing");
assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "doing");
});
test("failed renames and unavailable boards preserve workspace files", async () => {
const { a, all, files } = fixture();
await a.reload();
const before = [...files];
await assert.rejects(
a.renameBoard("Personal", async () => {
throw Error("Exists");
}),
/Exists/,
);
assert.equal(a.board.reference?.path, "Project/Launch.md");
assert.deepEqual([...files], before);
const rename = async () => {
assert.fail("Rename must not run");
return "";
};
await assert.rejects(all.renameBoard("All", rename), /available board/);
files.set("Copy.md", files.get("Project/Launch.md")!);
await assert.rejects(a.renameBoard("Duplicate", rename), /available board/);
files.delete("Copy.md");
files.delete("Project/Launch.md");
await assert.rejects(a.renameBoard("Missing", rename), /available board/);
});
test("board transfers preserve metadata and other memberships in one card write", async () => {
const { a, b, all, files, workspace, writes } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
const destination = await a.createBoard("Destination");
const target = new TaskStore(workspace, destination);
await target.reload();
await target.create("Already there", { ...fields, status: "doing" }, "");
await a.reload();
await a.save(a.tasks.find((task) => task.title === "Task")!, {
priority: "high", color: "pink", labels: ["bug"], assignees: ["Ada"],
customFields: [{ name: "Customer", value: "Keep" }],
});
files.set("Task.md", files.get("Task.md")!.replace("runestone_pm:", "owner: Ada # keep\nrunestone_pm:"));
await a.reload();
const before = a.tasks.find((task) => task.title === "Task")!;
writes.length = 0;
await a.transferTask(before, destination.id, "doing");
assert.deepEqual(writes, [before.path]);
assert.equal(a.scopedTasks.length, 0);
await target.reload();
await b.reload();
await all.reload();
const saved = target.tasks.find((task) => task.id === before.id)!;
const { placements: _oldPlacements, source: _oldSource, ...oldDetails } = before;
const { placements: _newPlacements, source: _newSource, ...newDetails } = saved;
assert.deepEqual(newDetails, oldDetails);
assert.deepEqual(saved.placements![b.board.reference!.id], before.placements![b.board.reference!.id]);
assert.equal(Object.hasOwn(saved.placements!, a.board.reference!.id), false);
assert.equal(saved.placements![destination.id].listId, "doing");
assert.ok(saved.source.includes("owner: Ada # keep"));
assert.deepEqual(target.cardsInList("doing").map((task) => task.title), ["Already there", "Task"]);
assert.equal(b.scopedTasks.length, 1);
assert.equal(all.tasks.filter((task) => task.id === before.id).length, 1);
});
test("hidden cards transfer to existing memberships, custom lists, and Unlisted without copies", async () => {
const { a, b, workspace, files } = fixture();
await a.reload();
await a.create("Private", fields, "![Keep image](runestone-pm-image:asset-id)");
const privateCard = a.scopedTasks[0];
assert.ok(privateCard.path.startsWith(".runestone/pm/cards/"));
await a.save(privateCard, { placements: {
...privateCard.placements,
[b.board.reference!.id]: { listId: "todo", order: "a" },
} });
await b.reload();
await b.changeBoard(() => b.board.add("Review", null));
const reviewId = b.board.value.lists.at(-1)!.id;
const before = a.tasks.find((task) => task.id === privateCard.id)!;
const paths = [...files.keys()];
await a.transferTask(before, b.board.reference!.id, reviewId);
await b.reload();
assert.equal(b.scopedTasks.length, 1);
assert.equal(b.board.listFor(b.scopedTasks[0])?.id, reviewId);
assert.equal(b.scopedTasks[0].body, privateCard.body);
assert.deepEqual([...files.keys()], paths);
const managed = await b.createBoard("Unlisted destination");
await b.transferTask(b.scopedTasks[0], managed.id, null);
const target = new TaskStore(workspace, managed);
await target.reload();
assert.equal(target.scopedTasks.length, 1);
assert.equal(target.scopedTasks[0].placements![managed.id].listId, null);
assert.equal(target.scopedTasks[0].status, "todo");
});
test("transfers reject missing, duplicated, deleted, and archived destinations without card changes", async () => {
for (const condition of ["missing", "duplicate", "deleted", "archived", "list"] as const) {
const { a, b, files, workspace, writes } = fixture();
await a.adopt("Task.md");
const before = a.scopedTasks[0];
let destination = b.board.reference!;
if (condition === "missing") files.delete(destination.path);
if (condition === "duplicate") files.set("Copy.md", files.get(destination.path)!);
if (condition === "deleted") {
await b.reload();
await b.changeBoard(() => b.board.deleteBoard());
}
if (condition === "archived") {
destination = await a.createBoard("Archived");
const target = new TaskStore(workspace, destination);
await target.reload();
await target.changeBoard(() => target.board.manage({ archived: true }));
}
if (condition === "list") {
await b.reload();
await b.changeBoard(() => b.board.remove("doing"));
}
writes.length = 0;
await assert.rejects(a.transferTask(before, destination.id, "doing"), /destination/);
assert.equal(files.get(before.path), before.source, condition);
assert.deepEqual(writes, [], condition);
assert.deepEqual(a.scopedTasks[0], before, condition);
}
});
test("transfers require a current source membership and active source board", async () => {
const { a, b, all, files } = fixture();
await all.reload();
await assert.rejects(all.transferTask(all.tasks[0], b.board.reference!.id, "todo"), /active board/);
await a.reload();
await assert.rejects(a.transferTask(a.tasks[0], b.board.reference!.id, "todo"), /no longer belongs/);
await a.adopt("Task.md");
const before = a.scopedTasks[0];
await assert.rejects(a.transferTask(before, a.board.reference!.id, "todo"), /different destination/);
files.delete(a.board.reference!.path);
await assert.rejects(a.transferTask(before, b.board.reference!.id, "todo"), /active board/);
assert.equal(files.get(before.path), before.source);
});
test("stale cards and failed transfer writes preserve every membership", async () => {
const { a, b, files, failWrites, writes } = fixture();
await a.adopt("Task.md");
const stale = a.scopedTasks[0];
await b.reload();
await b.save(b.tasks[0], { body: "An external edit." });
const external = files.get(stale.path);
await assert.rejects(a.transferTask(stale, b.board.reference!.id, "done"), /card changed/);
assert.equal(files.get(stale.path), external);
const current = a.scopedTasks[0];
writes.length = 0;
failWrites();
await assert.rejects(a.transferTask(current, b.board.reference!.id, "done"), /Disk failure/);
assert.equal(files.get(current.path), current.source);
assert.deepEqual(a.scopedTasks[0], current);
assert.deepEqual(writes, []);
});
test("detail board changes save draft fields and membership atomically with stale-write protection", async () => {
const { a, b, files, writes, failWrites } = fixture();
await a.reload(); await a.adopt("Task.md"); await b.reload();
const task = a.tasks[0]; const original = files.get(task.path);
writes.length = 0;
await a.saveToBoard(task, b.board.reference!.id, "doing", { body: "Draft preserved", priority: "highest" });
assert.equal(writes.length, 1);
const changed = readTask(task.path, files.get(task.path)!)!;
assert.equal(changed.body, "Draft preserved"); assert.equal(changed.priority, "highest");
assert.equal(changed.status, "doing"); assert.equal(changed.placements?.[a.board.reference!.id], undefined);
assert.equal(changed.placements?.[b.board.reference!.id]?.listId, "doing");
await assert.rejects(a.saveToBoard(task, b.board.reference!.id, "todo", { body: "Stale draft" }), /changed/);
const saved = files.get(task.path); failWrites();
await assert.rejects(b.saveToBoard(changed, a.board.reference!.id, "todo", { body: "Failed draft" }), /Disk failure/);
assert.equal(files.get(task.path), saved); assert.notEqual(saved, original);
});
test("pasted relative paths reuse one card and reject paths outside the workspace", async () => {
const { a, files } = fixture(); await a.reload();
const original = readTask("Task.md", files.get("Task.md")!)!;
await a.createOrLink("./Task.md", { ...fields, listId: "doing" });
assert.equal(a.tasks.length, 1); assert.equal(a.tasks[0].id, original.id);
assert.equal(a.tasks[0].placements?.[a.board.reference!.id]?.listId, "doing");
const before = new Map(files);
for (const path of ["../Task.md", "D:/Task.md", "/Task.md", "https://example.com/Task.md"])
await assert.rejects(a.createOrLink(path, fields), /relative Markdown path/);
assert.deepEqual(files, before);
});
+187
View File
@@ -0,0 +1,187 @@
// The main-bundle parts of the native Project Management feature: the catalog entry, the board view pattern of the
// session, the settings and their first-start migration, and the board reader of Background and Settings.
import test from "node:test";
import assert from "node:assert/strict";
import { featureEntry, featureOfOwner } from "../../../../src/lib/features/catalog.ts";
import { FeatureSession } from "../../../../src/lib/features/session.ts";
import { migrateFeatures, type LegacyPlugin } from "../../../../src/lib/features/migration.ts";
import type { FeatureContext, FeatureInstance } from "../../../../src/lib/features/types.ts";
import { boardOfView, boardViewId, PLANNING } from "../../../../src/lib/features/pm/views.ts";
import { DEFAULT_PROJECT_MANAGEMENT, migrateProjectManagement, normalizeProjectManagement, readViewStates, VIEW_STATES_KEY, writeViewStates, type ProjectManagementMigrationHost, type ProjectManagementSettings } from "../../../../src/lib/features/pmSettings.ts";
import { BOARD_CATALOG_PATH, parseBoardCatalog, readBoardCatalog, writeDefaultBoard } from "../../../../src/lib/features/pmBoards.ts";
import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../../src/lib/settings/store.ts";
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { parseCatalog } from "../../../../src/lib/features/pm/storage/catalog.ts";
function memoryStorage(initial: Record<string, string> = {}) {
const values = new Map(Object.entries(initial));
return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
}
function context(log: string[] = []): FeatureContext {
return {
openView: id => { log.push(`open ${id}`); }, openFile: async () => {}, onWorkspaceChange: () => () => {},
setViewTitle: (id, title) => { log.push(`title ${id} ${title}`); }, closeView: id => { log.push(`close ${id}`); },
replaceView: (current, next) => { log.push(`replace ${current} ${next}`); },
};
}
test("Project Management keeps the plugin ID, is on by default, and follows its package", () => {
const pm = featureEntry("pm");
assert.equal(pm.owner, "runestone.pm");
assert.equal(featureOfOwner("runestone.pm")?.id, "pm");
assert.equal(pm.defaultOn, true);
assert.equal(pm.followsPackage, true);
assert.deepEqual(pm.views.map(view => [view.id, view.placement, view.launch]), [["planning", "editor", true]]);
assert.deepEqual(pm.documentTypes, [], "The file tree reads no Markdown file for Project Management.");
assert.equal((SETTINGS_SECTIONS as readonly string[]).includes("projectManagement"), true);
assert.equal(LEGACY_KEYS.projectManagement, "runestone.project-management");
});
test("board view IDs are the plugin IDs, and only valid board IDs match", () => {
const id = "0c18bcdc-f41e-4a31-87f4-87c369f398c1";
const view = boardViewId(id);
assert.equal(view, "board-" + Buffer.from(id).toString("hex"));
assert.equal(boardOfView(view), id);
assert.equal(boardOfView(boardViewId("Plan ✓")), "Plan ✓");
for (const other of [PLANNING, "board-", "board-6", "board-zz", "board-ff", "board-41-42", "graph"]) assert.equal(boardOfView(other), null, other);
const pattern = featureEntry("pm").viewPatterns![0].match;
assert.equal(pattern.test(view), true);
assert.equal(pattern.test(PLANNING), false);
assert.equal(pattern.test(view + "x"), false);
});
test("the session answers for board views before the module loads, and gives them the board name later", async () => {
let loads = 0;
const log: string[] = [];
const restored: [string, unknown][] = [];
const mounted: string[] = [];
const instance: FeatureInstance = {
mount: view => { mounted.push(view); return () => {}; },
launch: view => { log.push(`launch ${view}`); },
restoreTabState: (view, state) => { restored.push([view, state]); },
saveTabState: view => ({ view }),
dispose() {},
};
const session = new FeatureSession(featureEntry("pm"), context(log), async () => { loads++; return { start: () => instance }; });
const view = boardViewId("board-a");
assert.equal(session.views.has(view), false);
const pattern = session.patternView(view)!;
assert.equal(pattern.placement, "editor");
assert.equal(pattern.title, "Project Management");
assert.equal(pattern.navigation, false);
assert.equal(pattern.launcher, false);
assert.equal(session.patternView(view), pattern, "One view for each ID");
assert.equal(session.patternView("board-zz"), undefined);
assert.equal(loads, 0, "No module load for a pattern view");
assert.equal(session.setViewTitle(view, "Roadmap"), true);
assert.equal(session.setViewTitle(view, "Roadmap"), false);
assert.equal(session.setViewTitle("planning", "Other"), false, "A catalog view keeps its title");
assert.equal(pattern.title, "Roadmap");
// A tab transfer restores the state, which loads the module.
await pattern.restoreTabState!({ search: "x" });
assert.deepEqual(restored, [[view, { search: "x" }]]);
assert.equal(loads, 1);
assert.deepEqual(pattern.saveTabState!(), { view });
const element = { replaceChildren() {} } as unknown as HTMLElement;
const dispose = await session.mount(boardViewId("board-b"), element);
assert.deepEqual(mounted, [boardViewId("board-b")]);
await dispose();
// The ribbon button launches `planning` through the feature, which chooses the default board.
await session.launch("planning");
assert.deepEqual(log, ["launch planning"]);
await session.stop();
assert.equal(session.patternView(boardViewId("board-c")), undefined, "An off feature makes no views");
});
test("the settings keep 2, 3, or 5 priority levels", () => {
assert.deepEqual(normalizeProjectManagement(undefined), DEFAULT_PROJECT_MANAGEMENT);
assert.deepEqual(normalizeProjectManagement({ priorityLevels: 5, other: 1 }), { priorityLevels: 5 });
assert.deepEqual(normalizeProjectManagement({ priorityLevels: 2 }), { priorityLevels: 2 });
for (const value of [4, "5", null, 0]) assert.deepEqual(normalizeProjectManagement({ priorityLevels: value }), { priorityLevels: 3 });
});
test("view states stay in localStorage, and a write keeps the states of other tabs", () => {
const storage = memoryStorage({ [VIEW_STATES_KEY]: JSON.stringify({ planning: { view: "gantt" } }) });
writeViewStates({ "board-61": { search: "bug" } }, storage);
assert.deepEqual(readViewStates(storage), { planning: { view: "gantt" }, "board-61": { search: "bug" } });
assert.deepEqual(readViewStates(memoryStorage({ [VIEW_STATES_KEY]: "not json" })), {});
});
function pmHost(missing: boolean, storage = memoryStorage()) {
const written: ProjectManagementSettings[] = [];
const host: ProjectManagementMigrationHost & { written: ProjectManagementSettings[] } = {
written, missing: () => missing, storage, write: async value => { written.push(value); },
};
return host;
}
test("the first start makes the section and the view states from the kept plugin settings", async () => {
const legacy: LegacyPlugin = { id: "runestone.pm", installed: true, enabled: true, settings: { priorityLevels: 5, viewStates: { planning: { view: "calendar" } }, other: true } };
const host = pmHost(true);
assert.deepEqual(await migrateProjectManagement(legacy, host), { priorityLevels: 5 });
assert.deepEqual(host.written, [{ priorityLevels: 5 }]);
assert.deepEqual(JSON.parse(host.storage.getItem(VIEW_STATES_KEY)!), { planning: { view: "calendar" } });
// Existing view states in localStorage stay.
const kept = pmHost(true, memoryStorage({ [VIEW_STATES_KEY]: "{\"planning\":{}}" }));
await migrateProjectManagement(legacy, kept);
assert.equal(kept.storage.getItem(VIEW_STATES_KEY), "{\"planning\":{}}");
// Without plugin settings, the defaults apply. A present section stays.
const fresh = pmHost(true);
assert.deepEqual(await migrateProjectManagement(undefined, fresh), DEFAULT_PROJECT_MANAGEMENT);
assert.equal(fresh.storage.getItem(VIEW_STATES_KEY), null);
const present = pmHost(false);
assert.equal(await migrateProjectManagement(legacy, present), null);
assert.deepEqual(present.written, []);
});
test("the feature migration asks for the Project Management package when the section is missing", async () => {
const asked: string[][] = [];
const switches: unknown[] = [];
const host = { read: () => ({ git: true, background: true, terminal: true, pdf: true }), write: async (value: unknown) => { switches.push(value); },
legacy: async (ids: string[]) => { asked.push(ids); return ids.map(id => ({ id, installed: true, enabled: false, settings: { priorityLevels: 2 } })); } };
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
const terminal = { missing: () => false, legacy: () => null, write: async () => {} };
const pm = pmHost(true);
assert.deepEqual(await migrateFeatures(host, background, terminal, pm), ["pm"]);
assert.deepEqual(asked, [["runestone.pm"]]);
assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true, pm: false }], "The switch follows the disabled package.");
assert.deepEqual(pm.written, [{ priorityLevels: 2 }]);
});
test("the board reader lists the boards of workspace.json without the feature code", async () => {
const value = {
schema: 1, defaultBoardId: "b", defaultBoardPath: "pm-board:b", future: { keep: true },
boards: [{ name: "Roadmap", value: defaultBoard("a") }, { name: "Bugs", value: defaultBoard("b"), archived: true }, { name: "Copy", value: defaultBoard("a") }, { name: "No value" }],
};
const source = JSON.stringify(value);
assert.deepEqual(parseBoardCatalog(source), { source, defaultBoardId: "b", boards: [{ id: "a", name: "Roadmap", archived: false }, { id: "b", name: "Bugs", archived: true }] });
assert.deepEqual(parseBoardCatalog(null), { boards: [], defaultBoardId: null, source: null });
assert.throws(() => parseBoardCatalog("{\"schema\":2,\"boards\":[]}"), /unsupported/);
const reads: string[] = [];
const catalog = await readBoardCatalog(async path => { reads.push(path); return source; });
assert.deepEqual(reads, [BOARD_CATALOG_PATH]);
assert.deepEqual(catalog.boards.map(board => board.id), ["a", "b"]);
});
test("Settings saves the default board with a guarded write and keeps the other keys", async () => {
const files = new Map([[BOARD_CATALOG_PATH, JSON.stringify({ schema: 1, boards: [{ name: "Roadmap", value: defaultBoard("a") }], future: 1 }, null, 2) + "\n"]]);
const read = async (path: string) => files.get(path) ?? null;
const write = async (path: string, contents: string, expected: string) => {
if (files.get(path) !== expected) throw new Error("The file changed.");
files.set(path, contents);
};
await writeDefaultBoard("a", read, write);
const saved = JSON.parse(files.get(BOARD_CATALOG_PATH)!);
assert.equal(saved.defaultBoardId, "a");
assert.equal(saved.defaultBoardPath, "pm-board:a");
assert.equal(saved.future, 1);
// The feature code accepts the file.
assert.equal(parseCatalog(files.get(BOARD_CATALOG_PATH)!).defaultBoardId, "a");
await writeDefaultBoard(null, read, write);
assert.equal(JSON.parse(files.get(BOARD_CATALOG_PATH)!).defaultBoardId, null);
await assert.rejects(writeDefaultBoard("missing", read, write), /unavailable/);
await assert.rejects(writeDefaultBoard("a", read, async () => { throw new Error("The file changed."); }), /changed/);
// Without a catalog, All tasks needs no write.
await writeDefaultBoard(null, async () => null, async () => { throw new Error("no write"); });
});
@@ -0,0 +1,63 @@
import test from "node:test";
import assert from "node:assert/strict";
import { newTask, readTask, editTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts";
import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts";
import { defaultBoardPath } from "../../../../src/lib/features/pm/model/workspace-default.ts";
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { catalogPath, boardMarkdown } from "../../../../src/lib/features/pm/storage/catalog.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
function fixture() {
const files = new Map<string, string>();
const workspace: Workspace = {
async list() { throw new Error("No task scan expected"); },
async read(path) { if (!files.has(path)) throw new Error("Missing"); return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async create(path, source) { if (files.has(path)) throw new Error("Exists"); files.set(path, source); },
async write(path, source, expected) { if (files.get(path) !== expected) throw new Error("Conflict"); files.set(path, source); },
};
return { files, workspace };
}
const fields = { status: "todo" as const, tags: [], sessions: [], archived: false };
test("new captures record immutable timestamps and existing legacy cards keep an unknown date", () => {
const before = Date.now();
const note = newTask("Timestamp", fields);
const task = readTask(note.path, note.source)!;
assert.ok(Date.parse(task.createdAt!) >= before && Date.parse(task.createdAt!) <= Date.now());
const edited = readTask(task.path, editTask(task, { body: "Updated", status: "done", placements: { next: { listId: "done" } } }))!;
assert.equal(edited.createdAt, task.createdAt);
assert.throws(() => editTask(task, { createdAt: undefined }), /cannot change/);
assert.throws(() => editTask(task, { createdAt: "2026-01-01T00:00:00Z" }), /cannot change/);
assert.ok(Date.parse(readTask("Old.md", adoptNote("Old.md", "Original note"))!.createdAt!) >= before);
const legacy = readTask(note.path, note.source.replace(/^ createdAt:.*\n/m, ""))!;
assert.equal(readTask(legacy.path, editTask(legacy, { title: "Legacy edit" }))!.createdAt, undefined);
assert.equal(adoptNote(legacy.path, legacy.source), legacy.source);
});
test("description drafts persist separately, cancel clears them, and stale writers cannot overwrite drafts", async () => {
const { files, workspace } = fixture();
const draft = new DescriptionDraft(workspace, "task");
assert.equal(await draft.load(), null);
await draft.save("Uncommitted text");
const other = new DescriptionDraft(workspace, "task");
assert.equal(await other.load(), "Uncommitted text");
await draft.save("Newer draft");
await assert.rejects(other.save("Stale draft"), /Conflict/);
await draft.save(null);
assert.equal(await new DescriptionDraft(workspace, "task").load(), null);
assert.ok([...files.keys()].every(path => !path.includes("/cards/")));
});
test("default board resolves without scanning cards and keeps unavailable selections fixed", async () => {
const { files, workspace } = fixture();
const board = defaultBoard("chosen");
const catalog = { schema: 1, boards: [{ name: "Chosen", value: board }], defaultBoardId: "chosen", unknown: "keep" };
files.set(catalogPath, JSON.stringify(catalog));
assert.equal(await defaultBoardPath(workspace), "pm-board:chosen");
files.set(catalogPath, JSON.stringify({ ...catalog, boards: [] }));
assert.equal(await defaultBoardPath(workspace), undefined);
assert.equal(JSON.parse(files.get(catalogPath)!).defaultBoardId, "chosen");
files.set("Legacy.md", boardMarkdown(board));
files.set(catalogPath, JSON.stringify({ ...catalog, boards: [], defaultBoardPath: "Legacy.md" }));
assert.equal(await defaultBoardPath(workspace), "Legacy.md");
files.set(catalogPath, JSON.stringify({ ...catalog, boards: [], defaultBoardPath: "Legacy.md", deletedBoardIds: ["chosen"] }));
assert.equal(await defaultBoardPath(workspace), undefined);
});
@@ -0,0 +1,142 @@
// The hidden mode of the store (`legacy: false`): it reads only `.runestone/pm/`, and a save, a delete, a move,
// or a watcher event reads only the changed files again.
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts";
import { labelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
import { editTask, newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { newBoardSource } from "../../../../src/lib/features/pm/storage/board.ts";
import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { fields, hiddenWorkspace } from "./_memory.ts";
const cards = [{ id: "a", title: "Card A" }, { id: "b", title: "Card B" }, { id: "c", title: "Card C" }];
test("the hidden mode reads only .runestone/pm and never a visible Markdown note", async () => {
const workspace = hiddenWorkspace(cards, {
"Notes/Task.md": newTask("Task", fields(), "", "visible").source,
"Board.md": newBoardSource(),
});
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
await store.reload();
assert.equal(store.legacy, false);
assert.deepEqual(store.issues, []);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "b", "c"]);
assert.deepEqual(store.boards.map(board => board.id), ["board"]);
assert.equal(workspace.markdownLists, 0);
assert.ok(workspace.reads.every(path => path.startsWith(".runestone/pm/") || path === "runestone-pm-labels.json"), workspace.reads.join(", "));
assert.equal(workspace.reads.some(path => path.endsWith(".md") && !path.startsWith(".runestone/")), false);
// The legacy mode, for the migration and the skill helper, still reads the visible notes.
const legacy = new TaskStore(workspace);
await legacy.reload();
assert.equal(legacy.legacy, true);
assert.ok(legacy.tasks.some(task => task.id === "visible"));
});
test("a save, a move, and a delete read only the changed card again", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
await store.reload();
const card = (id: string) => store.tasks.find(task => task.id === id)!;
// Each write also checks the Git exclusion file of `.runestone/pm/`. It is not a reload.
const reads = () => workspace.reads.filter(path => path !== privateRulesPath);
workspace.reads.length = 0;
await store.save(card("a"), { body: "Changed" });
assert.deepEqual(reads(), [cardPath("a")]);
assert.equal(card("a").body, "Changed");
workspace.reads.length = 0;
await store.moveTask(card("b"), "doing");
assert.deepEqual(reads(), [cardPath("b")]);
assert.equal(card("b").placements!.board.listId, "doing");
assert.equal(card("b").status, "doing");
workspace.reads.length = 0;
await store.deleteCard(card("c"));
assert.deepEqual(reads().filter(path => path !== deletedCardsPath), [cardPath("c")]);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "b"]);
assert.match(workspace.files.get(deletedCardsPath)!, /"c"/);
});
test("a save still stops when another window changed the card", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, undefined, { legacy: false });
await store.reload();
const card = store.tasks.find(task => task.id === "a")!;
workspace.files.set(cardPath("a"), editTask(card, { body: "Other window" }));
await assert.rejects(store.save(card, { body: "This window" }), /changed/);
assert.equal(store.tasks.find(task => task.id === "a")!.body, "Other window");
});
test("watcher paths read only the changed files of .runestone/pm", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
await store.reload();
// A change outside `.runestone/pm/`, or of images and drafts, reads nothing.
workspace.reads.length = 0; workspace.lists.length = 0;
await store.reloadPaths(["Notes/Plan.md", ".runestone/pm/images/x.json", ".runestone/pm/drafts/61.json", ".runestone/tabs.json"]);
assert.deepEqual(workspace.reads, []);
assert.deepEqual(workspace.lists, []);
// A new card from another window.
workspace.files.set(cardPath("d"), newTask("Card D", fields({ title: "Card D", placements: { board: { listId: "done" } } }), "", "d").source);
workspace.reads.length = 0;
await store.reloadPaths([cardPath("d")]);
assert.deepEqual(workspace.reads, [cardPath("d")]);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "b", "c", "d"]);
// A deleted card file.
workspace.files.delete(cardPath("b"));
workspace.reads.length = 0;
await store.reloadPaths([cardPath("b")]);
assert.deepEqual(workspace.reads, [cardPath("b"), cardPath("b")]);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "c", "d"]);
// A renamed board reads only the catalog.
const catalog = JSON.parse(workspace.files.get(catalogPath)!);
catalog.boards[0].name = "Renamed";
workspace.files.set(catalogPath, JSON.stringify(catalog));
workspace.reads.length = 0;
await store.reloadPaths([catalogPath]);
assert.deepEqual(workspace.reads, [catalogPath]);
assert.equal(store.board.name, "Renamed");
// Labels and deleted cards each read their own file.
workspace.files.set(labelsPath, JSON.stringify({ schema: 1, labels: [{ id: "x", name: "X", color: "red" }] }));
workspace.files.set(deletedCardsPath, JSON.stringify({ schema: 1, ids: ["d"] }));
workspace.reads.length = 0;
await store.reloadPaths([labelsPath, deletedCardsPath]);
assert.deepEqual(workspace.reads.sort(), [deletedCardsPath, labelsPath].sort());
assert.deepEqual(store.labels.value.map(label => label.id), ["x"]);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "c"]);
});
test("an invalid card from a watcher event hides all cards until it is valid again", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, undefined, { legacy: false });
await store.reload();
const valid = workspace.files.get(cardPath("a"))!;
workspace.files.set(cardPath("a"), "---\nrunestone_pm: [\n---\n");
await store.reloadPaths([cardPath("a")]);
assert.deepEqual(store.tasks, []);
assert.match(store.issues.join(" "), /\.runestone\/pm\/cards\/61\.md/);
workspace.files.set(cardPath("a"), valid);
await store.reloadPaths([cardPath("a")]);
assert.deepEqual(store.issues, []);
assert.equal(store.tasks.length, 3);
});
test("a folder change, a marker change, or an unknown change reads everything again", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, undefined, { legacy: false });
await store.reload();
for (const paths of [[".runestone/pm/cards"], [".runestone/pm/cards/.gitignore"], [".runestone"], undefined]) {
workspace.lists.length = 0;
await store.reloadPaths(paths);
assert.deepEqual(workspace.lists, [".runestone/pm/cards"], String(paths));
}
});
@@ -0,0 +1,278 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
mkdtemp,
readFile,
writeFile,
mkdir,
readdir,
rm,
} from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import { resolve, join, dirname } from "node:path";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { cardOrder } from "../../../../src/lib/features/pm/storage/order.ts";
import {
privateRulesPath,
cardsMarker,
isHiddenCard,
} from "../../../../src/lib/features/pm/storage/persistence.ts";
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
import { defaultLabels, labelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: ["keep"],
labels: ["bug"],
archived: false,
sessions: [],
due: { date: "2026-10-30" },
plan: { start: "2026-10-07", end: "2026-10-10" },
placements: { board: { listId: "todo" } },
};
async function fixture(t: test.TestContext) {
const root = await mkdtemp(join(tmpdir(), "runestone-pm-private-"));
t.after(async () => {
assert.ok(
resolve(root).startsWith(resolve(tmpdir(), "runestone-pm-private-")),
);
await rm(root, { recursive: true, force: true });
});
const file = (path: string) => {
const absolute = resolve(root, path);
assert.ok(
absolute === root ||
absolute.startsWith(root + "/") ||
absolute.startsWith(root + "\\"),
);
return absolute;
};
const workspace: Workspace = {
async readOptional(path) {
try {
return await readFile(file(path), "utf8");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
throw error;
}
},
async read(path) {
return readFile(file(path), "utf8");
},
async list(path = "") {
return (await readdir(file(path), { withFileTypes: true }))
.filter((entry) => ![".git", ".runestone"].includes(entry.name))
.map((entry) => ({
name: entry.name,
rel_path: (path ? path + "/" : "") + entry.name,
kind: entry.isDirectory() ? "folder" : "file",
}));
},
async create(path, source) {
await mkdir(dirname(file(path)), { recursive: true });
await writeFile(file(path), source, { flag: "wx" });
},
async write(path, source, expected) {
assert.equal(await workspace.read(path), expected, "Changed on disk");
await writeFile(file(path), source);
},
};
const git = (...args: string[]) =>
execFileSync("git", args, {
cwd: root,
encoding: "utf8",
windowsHide: true,
}).trim();
return { root, file, workspace, git, store: new TaskStore(workspace) };
}
test("new cards and other Project Management data stay outside navigation and normal Git staging", async (t) => {
const { store, workspace, git } = await fixture(t);
git("init", "--quiet");
await workspace.create!("README.md", "Shared project\n");
await store.createBoard("Board");
await store.create("Card: / duplicate?", fields, "Private details");
await store.create("Card: / duplicate?", fields, "Second card");
await store.saveLabels(defaultLabels(), store.labels.source);
await store.reload();
assert.equal(store.tasks.length, 2);
assert.equal(new Set(store.tasks.map((task) => task.id)).size, 2);
assert.ok(store.tasks.every((task) => isHiddenCard(task.path)));
assert.deepEqual(
(await workspace.list()).map((entry) => entry.name),
["README.md"],
);
assert.equal(await workspace.readOptional!(".gitignore"), null);
for (const path of [
catalogPath,
labelsPath,
privateRulesPath,
cardsMarker,
...store.tasks.map((task) => task.path),
])
assert.equal(git("check-ignore", "--", path), path);
git("add", ".");
assert.equal(git("ls-files"), "README.md");
});
test("Git protection is installed before data writes and failures preserve privacy", async (t) => {
const { store, workspace } = await fixture(t);
const create = workspace.create!;
const writes: string[] = [];
workspace.create = async (path, source) => {
writes.push(path);
if (path === privateRulesPath)
throw new Error("Cannot create Git exclusion");
await create(path, source);
};
await assert.rejects(store.create("Private", fields, ""), /Git exclusion/);
assert.deepEqual(writes, [privateRulesPath]);
workspace.create = async (path, source) => {
writes.push(path);
await create(path, source);
};
writes.length = 0;
await store.create("Private", fields, "");
assert.deepEqual(writes, [
privateRulesPath,
cardsMarker,
store.tasks[0].path,
]);
});
test("selected legacy cards migrate with exact backups, stable order, and no changes to linked notes", async (t) => {
const { store, workspace, file, git } = await fixture(t);
git("init", "--quiet");
const original = newTask("Existing", fields, "Preserve **body**.\n");
const source = original.source.replace("---\n", "---\nowner: Ada # retain\n");
await workspace.create!(original.path, source);
const linked = newTask("Shared", fields, "Keep as a note");
await workspace.create!("Docs/Shared.md", linked.source);
git("add", ".");
await store.reload();
const before = store.tasks.find((task) => task.title === "Existing")!;
const stale = new TaskStore(workspace);
await stale.reload();
const report = await store.migrateStorage([before.id]);
assert.equal(report.length, 1);
const current = store.tasks.find((task) => task.id === before.id)!;
assert.equal(current.path, cardPath(before.id));
assert.equal(current.title, before.title);
assert.equal(current.body, before.body);
for (const key of [
"status",
"tags",
"labels",
"due",
"plan",
"sessions",
"archived",
] as const)
assert.deepEqual(current[key], before[key]);
assert.equal(cardOrder(current, "board"), cardOrder(before, "board"));
assert.equal(cardOrder(current), cardOrder(before));
assert.equal(await workspace.read(original.path), source);
assert.equal(await workspace.read(report[0].backup), source);
assert.equal(await workspace.read("Docs/Shared.md"), linked.source);
assert.match(current.source, /owner: Ada # retain/);
await assert.rejects(stale.save(before, { status: "done" }), /changed/);
await store.save(current, { title: "Private: edited", status: "doing" });
await store.migrateStorage([before.id]);
assert.equal(
store.tasks.find((task) => task.id === before.id)!.title,
"Private: edited",
);
await rm(file(original.path));
await store.reload();
assert.equal(store.tasks.length, 2);
assert.equal(
store.tasks.find((task) => task.id === before.id)!.status,
"doing",
);
git("add", "-A");
assert.equal(git("ls-files"), "Docs/Shared.md");
});
test("partial card migration resumes without replacing newer hidden edits", async (t) => {
const { workspace, store } = await fixture(t);
for (const title of ["A", "B"]) {
const note = newTask(title, fields);
await workspace.create!(note.path, note.source);
}
await store.reload();
const ids = store.tasks.map((task) => task.id);
const blocked = cardPath(ids[1]);
const create = workspace.create!;
workspace.create = async (path, source) => {
if (path === blocked) throw new Error("Disk full");
await create(path, source);
};
await assert.rejects(store.migrateStorage(ids), /Disk full/);
await store.reload();
assert.equal(store.tasks.length, 2);
const first = store.tasks.find((task) => task.id === ids[0])!;
await store.save(first, { body: "Later edit" });
workspace.create = create;
await store.migrateStorage(ids);
assert.ok(store.tasks.every((task) => isHiddenCard(task.path)));
assert.equal(
store.tasks.find((task) => task.id === ids[0])!.body,
"Later edit",
);
});
test("changed originals block further migration and stale saves without losing either version", async (t) => {
const { workspace, store } = await fixture(t);
const note = newTask("A", fields);
await workspace.create!(note.path, note.source);
await store.reload();
const id = store.tasks[0].id;
await store.migrateStorage([id]);
const hidden = store.tasks[0];
await workspace.write(
note.path,
editTask(readTask(note.path, note.source)!, { body: "Outside edit" }),
note.source,
);
await assert.rejects(store.save(hidden, { status: "done" }), /changed/);
await assert.rejects(store.migrateStorage(), /issues/);
assert.equal(await workspace.read(hidden.path), hidden.source);
});
test("migration retains long filename titles and an existing Project Management ignore file", async (t) => {
const { workspace, store } = await fixture(t);
const note = newTask("A", fields);
const path = "Legacy/" + "a".repeat(130) + ".md";
await workspace.create!(path, note.source);
await workspace.create!(
privateRulesPath,
"# Personal rules\ncache/\n!keep.json\n",
);
await store.reload();
await store.migrateStorage([store.tasks[0].id]);
assert.equal(store.tasks[0].title, "a".repeat(130));
assert.equal(
await workspace.read(privateRulesPath),
"# Personal rules\ncache/\n!keep.json\n# RuneStone Project Management local data\n*\n",
);
});
test("an invalid hidden card cannot fall back to editing its old visible note", async (t) => {
const { workspace, store } = await fixture(t);
const note = newTask("A", fields);
await workspace.create!(note.path, note.source);
await store.reload();
const legacy = store.tasks[0];
await store.migrateStorage([legacy.id]);
const hidden = store.tasks[0];
await workspace.write(hidden.path, "broken data", hidden.source);
await store.reload();
assert.equal(store.tasks.length, 0);
assert.match(store.issues.join(" "), /hidden card ID/);
await assert.rejects(store.save(legacy, { status: "done" }), /changed/);
assert.equal(await workspace.read(note.path), note.source);
});
@@ -0,0 +1,195 @@
import test from "node:test";
import assert from "node:assert/strict";
import { setTimeout as delay } from "node:timers/promises";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { newTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { mapConcurrent, scanConcurrency } from "../../../../src/lib/features/pm/storage/scan.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
test("native discovery avoids directory bridge calls and retains save conflicts", async () => {
const boardSource = newBoardSource();
const boardId = parseBoard(boardSource).id;
const id = crypto.randomUUID();
const taskPath = cardPath(id);
const original = newTask(id, {
title: "Latency card", status: "todo", tags: [], sessions: [], archived: false,
placements: { [boardId]: { listId: "todo" } },
}, "Original details", id).source;
const files = new Map([["Board.md", boardSource], [taskPath, original], [cardsMarker, "*\n"], [privateRulesPath, "*\n"]]);
let scans = 0, lists = 0, writes = 0;
let scanFailure = false;
const workspace: Workspace = {
async listMarkdown() {
scans++;
if (scanFailure) throw new Error("Directory unavailable");
return [...files.keys()].filter(path => !path.startsWith(".") && path.endsWith(".md"));
},
async list(path) {
lists++;
assert.equal(path, ".runestone/pm/cards", "Visible folders must use the native listing");
return [{ name: taskPath.split("/").at(-1)!, rel_path: taskPath, kind: "file" }];
},
async read(path) { const value = files.get(path); assert.notEqual(value, undefined); return value!; },
async readOptional(path) { return files.get(path) ?? null; },
async create() { throw new Error("Unexpected create"); },
async write(path, source, expected) { assert.equal(files.get(path), expected); writes++; files.set(path, source); },
};
const store = new TaskStore(workspace, { id: boardId, path: "Board.md" });
await store.reload();
await store.moveTask(store.tasks[0], "doing");
await store.save(store.tasks[0], { body: "Updated details" });
assert.equal(scans, 3);
assert.equal(lists, 3);
assert.equal(writes, 2);
const stale = store.tasks[0];
const external = editTask(stale, { body: "External details" });
files.set(taskPath, external);
await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/);
const current = store.tasks[0];
files.set("Copy.md", current.source);
await assert.rejects(store.moveTask(current, "done"), /duplicate/);
files.delete("Copy.md");
await store.reload();
scanFailure = true;
await assert.rejects(store.save(store.tasks[0], { body: "Blocked details" }), /Directory unavailable/);
assert.equal(files.get(taskPath), external);
assert.equal(writes, 2);
});
test("load, move, and detail saves overlap bounded reads without weakening conflict checks", async (t) => {
const source = newBoardSource();
const boardId = parseBoard(source).id;
const files = new Map([
["Board.md", source],
[cardsMarker, "*\n"],
[privateRulesPath, "*\n"],
]);
for (let index = 0; index < 32; index++) {
files.set(`Notes${index % 4}/Note${index}.md`, "An ordinary note.");
const id = crypto.randomUUID();
files.set(
cardPath(id),
newTask(
id,
{
title: `Card ${index}`,
status: "todo",
tags: [],
sessions: [],
archived: false,
placements: { [boardId]: { listId: "todo" } },
},
"Original details",
id,
).source,
);
}
let active = 0,
peak = 0,
reads = 0;
const readDelay = 15;
const workspace: Workspace = {
async list(parent = "") {
const entries = new Map();
const prefix = parent ? `${parent}/` : "";
for (const path of files.keys()) {
if (!path.startsWith(prefix)) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: prefix + parts[0],
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async read(path) {
reads++;
peak = Math.max(peak, ++active);
try {
await delay(readDelay);
const value = files.get(path);
if (value === undefined) throw new Error("Missing note");
return value;
} finally {
active--;
}
},
async readOptional(path) {
return files.get(path) ?? null;
},
async write(path, source, expected) {
assert.equal(files.get(path), expected);
files.set(path, source);
},
async create(path, source) {
assert.equal(files.has(path), false);
files.set(path, source);
},
};
const store = new TaskStore(workspace, { id: boardId, path: "Board.md" });
for (const [name, action] of [
["load", () => store.reload()],
["move", () => store.moveTask(store.tasks[0], "doing")],
["edit", () => store.save(store.tasks[0], { body: "Updated details" })],
] as const) {
peak = reads = 0;
const started = performance.now();
await action();
const elapsed = performance.now() - started;
assert.equal(reads, 65);
assert.equal(peak, scanConcurrency);
assert.equal(active, 0);
// The serial delay alone is 975 ms. Keep generous headroom for busy runners.
assert.ok(elapsed < reads * readDelay * 0.75, `${name} took ${elapsed} ms`);
t.diagnostic(
`${name}: ${reads} reads, peak ${peak}, ${Math.round(elapsed)} ms (serial delay ${reads * readDelay} ms)`,
);
}
assert.equal(store.tasks[0].body, "Updated details");
assert.equal(store.tasks[0].status, "doing");
const cached = store.tasks[1];
await store.reload();
assert.equal(
store.tasks.find((task) => task.id === cached.id),
cached,
);
const stale = store.tasks[0];
const external = editTask(stale, { body: "External details" });
files.set(stale.path, external);
await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/);
assert.equal(files.get(stale.path), external);
const current = store.tasks.find((task) => task.id === stale.id)!;
files.set("Notes0/Copied card.md", current.source);
await assert.rejects(store.moveTask(current, "done"), /duplicate/);
assert.equal(files.get(current.path), external);
});
test("parallel scanning retains input order and drains pending work on failure", async () => {
let active = 0;
await assert.rejects(
mapConcurrent([0, 1, 2, 3], async (value) => {
active++;
try {
await delay(value === 0 ? 1 : 20);
if (value === 0) throw new Error("Directory unavailable");
return value;
} finally {
active--;
}
}),
/Directory unavailable/,
);
assert.equal(active, 0);
assert.deepEqual(
await mapConcurrent([0, 1, 2, 3], async (value) => {
await delay(4 - value);
return value;
}),
[0, 1, 2, 3],
);
});
@@ -0,0 +1,330 @@
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newBoardSource, parseBoard, BoardStore } from "../../../../src/lib/features/pm/storage/board.ts";
import {
catalogPath,
createBoard,
readCatalog,
boardKey,
parseCatalog,
} from "../../../../src/lib/features/pm/storage/catalog.ts";
import { migrateStorage } from "../../../../src/lib/features/pm/storage/migration.ts";
import { labelsPath, legacyLabelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
import { newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
function fixture() {
const source = newBoardSource() + "Keep the board description.\n";
const id = parseBoard(source).id;
const task = newTask(
"Keep task",
{
status: "doing",
tags: ["tag"],
labels: ["bug"],
archived: false,
sessions: [],
placements: { [id]: { listId: "doing", order: "a" } },
},
"Keep task body.",
);
const files = new Map([
["Project/Launch.md", source],
[task.path, task.source],
[
legacyLabelsPath,
JSON.stringify({
schema: 1,
extra: "keep",
labels: [{ id: "bug", name: "Defect", color: "red" }],
}),
],
]);
let fail = "";
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async read(path) {
if (!files.has(path)) throw new Error("Missing file");
return files.get(path)!;
},
async list(parent = "") {
const entries = new Map();
for (const path of files.keys()) {
const prefix = parent ? parent + "/" : "";
if (!path.startsWith(prefix) || path.startsWith(".")) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: prefix + parts[0],
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async create(path, source) {
if (path === fail) throw new Error("Disk failure");
if (files.has(path)) throw new Error("Exists");
files.set(path, source);
},
async write(path, source, expected) {
if (path === fail) throw new Error("Disk failure");
if (files.get(path) !== expected) throw new Error("Conflict");
files.set(path, source);
},
};
return {
files,
workspace,
id,
task,
source,
setFailure(path: string) {
fail = path;
},
};
}
test("migration backs up exact originals, preserves cards and survives removal of visible metadata", async () => {
const { files, workspace, id, task, source } = fixture();
const originalLabels = files.get(legacyLabelsPath)!;
const store = new TaskStore(workspace, { id, path: "Project/Launch.md" });
const report = await store.migrateStorage();
assert.equal(report.length, 2);
for (const file of report)
assert.equal(files.get(file.backup), files.get(file.path));
assert.equal(files.get("Project/Launch.md"), source);
assert.equal(files.get(task.path), task.source);
assert.equal(store.board.reference?.path, boardKey(id));
assert.equal(store.scopedTasks.length, 1);
assert.equal(store.scopedTasks[0].placements?.[id].order, "a");
assert.equal(store.labels.value[0].name, "Defect");
await store.board.edit("doing", "Building", "doing");
await store.reload();
await store.saveLabels(
[{ id: "bug", name: "Issue", color: "blue" }],
store.labels.source,
);
await store.migrateStorage();
assert.equal(store.board.value.lists[1].name, "Building");
assert.equal(store.labels.value[0].name, "Issue");
assert.equal(files.get(legacyLabelsPath), originalLabels);
files.delete("Project/Launch.md");
files.delete(legacyLabelsPath);
const reopened = new TaskStore(workspace, { id, path: boardKey(id) });
await reopened.reload();
assert.equal(reopened.scopedTasks[0].id, store.tasks[0].id);
assert.equal(reopened.labels.value[0].name, "Issue");
assert.equal(reopened.board.value.lists[1].name, "Building");
assert.equal(reopened.issues.length, 0);
});
test("a label write failure can resume after boards commit without duplicating data", async () => {
const { files, workspace, setFailure } = fixture();
const store = new TaskStore(workspace);
setFailure(labelsPath);
await assert.rejects(store.migrateStorage(), /Disk failure/);
assert.equal((await readCatalog(workspace)).value.boards.length, 1);
assert.ok(files.has(legacyLabelsPath));
setFailure("");
await store.migrateStorage();
assert.equal((await readCatalog(workspace)).value.boards.length, 1);
assert.ok(files.has(labelsPath));
});
test("backup failure prevents migration publication", async () => {
const { files, workspace, setFailure } = fixture();
setFailure(".runestone/pm/backups/Project/Launch.md");
await assert.rejects(
new TaskStore(workspace).migrateStorage(),
/Disk failure/,
);
assert.equal(files.has(catalogPath), false);
assert.equal(files.has(labelsPath), false);
});
test("a legacy editor cannot write its original board after another view migrates it", async () => {
const { files, workspace, id, source } = fixture();
const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" });
await stale.reload();
await new TaskStore(workspace).migrateStorage();
await assert.rejects(stale.add("Old edit", null), /hidden storage/);
assert.equal(files.get("Project/Launch.md"), source);
await stale.reload();
assert.equal(stale.reference?.path, boardKey(id));
await stale.add("New edit", null);
assert.equal(
(await readCatalog(workspace)).value.boards[0].value.lists.at(-1)?.name,
"New edit",
);
});
test("invalid or duplicate originals and conflicting labels block migration without writes", async () => {
for (const kind of [
"duplicate",
"invalid-labels",
"hidden-labels",
"future",
]) {
const { files, workspace, source } = fixture();
if (kind === "duplicate") files.set("Duplicate.md", source);
if (kind === "invalid-labels") files.set(legacyLabelsPath, "broken");
if (kind === "hidden-labels")
files.set(labelsPath, files.get(legacyLabelsPath)!);
if (kind === "future") files.set(catalogPath, '{"schema":99,"boards":[]}');
const before = new Map(files);
await assert.rejects(new TaskStore(workspace).migrateStorage());
assert.deepEqual(files, before);
}
});
test("changed legacy files or damaged backups never receive a successful migration check", async () => {
for (const path of [
"Project/Launch.md",
".runestone/pm/backups/Project/Launch.md",
legacyLabelsPath,
]) {
const { files, workspace } = fixture();
const store = new TaskStore(workspace);
await store.migrateStorage();
files.set(path, files.get(path)! + "\n");
const before = new Map(files);
await assert.rejects(store.migrateStorage());
assert.deepEqual(files, before);
}
});
test("hidden boards rename, archive, restore, and reject stale writes without changing task notes", async () => {
const { files, workspace, task } = fixture();
const reference = await createBoard(workspace, "New board");
const store = new TaskStore(workspace, reference);
await store.reload();
await store.renameBoard("Release");
const stale = new BoardStore(workspace, reference);
await stale.reload();
await store.board.manage({ archived: true });
await assert.rejects(stale.add("Review", null), /changed/);
await store.reload();
assert.equal(store.board.editable, false);
await assert.rejects(
store.create(
"No card",
{ status: "todo", tags: [], sessions: [], archived: false },
"",
),
/Restore/,
);
await store.board.manage({ archived: false });
await store.reload();
assert.equal(store.board.name, "Release");
assert.equal(store.board.editable, true);
assert.equal(files.get(task.path), task.source);
await assert.rejects(createBoard(workspace, "release"), /already exists/);
});
test("hidden data is isolated by workspace and unknown catalog fields survive edits", async () => {
const a = fixture(),
b = fixture();
const reference = await createBoard(a.workspace, "Private");
const value = JSON.parse(a.files.get(catalogPath)!);
value.futureMapping = { externalId: "remote-1" };
a.files.set(catalogPath, JSON.stringify(value));
const board = new BoardStore(a.workspace, reference);
await board.reload();
await board.add("Review", null);
assert.deepEqual(
JSON.parse(a.files.get(catalogPath)!).futureMapping,
value.futureMapping,
);
assert.equal((await readCatalog(b.workspace)).value.boards.length, 0);
});
test("deleting a board preserves cards, other boards, and unknown catalog fields", async () => {
for (const archived of [false, true]) {
const { files, workspace, task, id } = fixture();
const reference = await createBoard(workspace, "Accidental board");
const initial = JSON.parse(files.get(catalogPath)!);
initial.futureMapping = { keep: "value" };
initial.boards[0].archived = archived;
files.set(catalogPath, JSON.stringify(initial));
const store = new TaskStore(workspace, reference);
await store.reload();
await store.changeBoard(() => store.board.deleteBoard());
assert.equal(store.board.available, false);
assert.equal(store.board.editable, false);
assert.equal(files.get(task.path), task.source);
const all = new TaskStore(workspace);
await all.reload();
assert.deepEqual(all.boards.map((board) => board.id), [id]);
assert.equal(all.tasks[0].placements?.[id].listId, "doing");
const catalog = (await readCatalog(workspace)).value;
assert.deepEqual(catalog.boards, []);
assert.deepEqual(catalog.deletedBoardIds, [reference.id]);
assert.deepEqual(catalog.futureMapping, initial.futureMapping);
await assert.rejects(store.board.deleteBoard(), /available/);
}
});
test("deleted legacy and migrated boards stay deleted after reload and migration", async () => {
for (const migrated of [false, true]) {
const { files, workspace, id, source, task } = fixture();
const store = new TaskStore(workspace, { id, path: "Project/Launch.md" });
await store.reload();
const original = store.boards[0];
const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" });
await stale.reload();
if (migrated) await store.migrateStorage();
await store.changeBoard(() => store.board.deleteBoard());
assert.equal(files.get("Project/Launch.md"), source);
assert.equal(files.get(task.path), task.source);
if (migrated) assert.equal(files.get(".runestone/pm/backups/Project/Launch.md"), source);
await assert.rejects(stale.add("Stale list", null), /deleted/);
await assert.rejects(stale.reload(), /deleted/);
assert.equal(stale.available, false);
await assert.rejects(migrateStorage(workspace, [original]), /deleted/);
const all = new TaskStore(workspace);
await all.reload();
assert.equal(all.boards.length, 0);
assert.equal(all.legacyBoards.length, 0);
assert.equal(all.tasks.length, 1);
await all.migrateStorage();
await all.reload();
assert.equal(all.boards.length, 0);
assert.equal(all.issues.length, 0);
}
});
test("changed boards and failed catalog writes block deletion", async () => {
for (const managed of [false, true]) {
const { files, workspace, id, setFailure } = fixture();
const reference = managed ? await createBoard(workspace, "New") : { id, path: "Project/Launch.md" };
const board = new BoardStore(workspace, reference);
await board.reload();
const path = managed ? catalogPath : reference.path;
files.set(path, files.get(path)! + "\n");
const before = new Map(files);
await assert.rejects(board.deleteBoard(), /changed/);
assert.deepEqual(files, before);
await board.reload();
setFailure(catalogPath);
await assert.rejects(board.deleteBoard(), /Disk failure/);
assert.equal(board.available, true);
assert.equal((await readCatalog(workspace)).value.deletedBoardIds, undefined);
}
});
test("a legacy board cannot be deleted from a stale view after migration", async () => {
const { workspace, id } = fixture();
const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" });
await stale.reload();
await new TaskStore(workspace).migrateStorage();
await assert.rejects(stale.deleteBoard(), /hidden storage/);
assert.equal((await readCatalog(workspace)).value.boards.length, 1);
});
test("invalid deletion records fail closed", () => {
for (const deletedBoardIds of ["id", [null], [""], ["id", "id"]])
assert.throws(() => parseCatalog(JSON.stringify({ schema: 1, boards: [], deletedBoardIds })), /deleted board/);
});
@@ -0,0 +1,32 @@
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
test("subtask promotion retains checklist data and retries without duplicate cards", async () => {
const parent = newTask("Parent", { status: "todo", tags: [], sessions: [], archived: false,
subtasks: [{ id: "child", title: "Child", done: true }], priority: "high" }, "Keep the description");
const files = new Map([["Parent.md", parent.source]]);
const parentId = readTask("Parent.md", parent.source)!.id;
let fail = true;
const workspace: Workspace = {
async list(folder = "") { return [...files.keys()].filter(path => folder ? path.startsWith(`${folder}/`) : !path.startsWith(".")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
async read(path) { if (!files.has(path)) throw Error("Missing"); return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async create(path, source) { if (files.has(path)) throw Error("Exists"); files.set(path, source); },
async write(path, source, expected) { if (fail) throw Error("Write failed"); assert.equal(files.get(path), expected); files.set(path, source); },
};
const store = new TaskStore(workspace);
await store.reload();
await assert.rejects(store.openSubtask(parentId, "child"), /Write failed/);
fail = false;
const child = await store.openSubtask(parentId, "child");
assert.equal(child.title, "Child"); assert.equal(child.status, "done"); assert.equal(child.priority, undefined);
assert.equal(store.tasks.length, 2);
const saved = readTask("Parent.md", files.get("Parent.md")!)!;
assert.equal(saved.subtasks![0].taskId, child.id);
assert.equal(saved.body, "Keep the description"); assert.equal(saved.priority, "high");
assert.equal((await store.openSubtask(parentId, "child")).id, child.id);
assert.equal(store.tasks.length, 2);
});
@@ -0,0 +1,149 @@
import test from "node:test";
import assert from "node:assert/strict";
import { watchBackground, type BackgroundFrame, type PMBackgroundApi } from "../../../../src/lib/features/pm/model/transient-background.ts";
const frame = (url: string): BackgroundFrame => ({ url, overlay: 0, position: "center", size: "cover" });
function fixture() {
const frames = new Map<string, BackgroundFrame>();
const listeners = new Set<(target: string) => void>();
// The shape of `backgroundHub` in `src/lib/plugins/backgrounds.ts`.
const api: PMBackgroundApi = {
get: target => frames.get(target) ?? null,
subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
};
const set = (target: string, value: BackgroundFrame | null) => {
if (value) frames.set(target, value); else frames.delete(target);
for (const listener of listeners) listener(target);
};
return { api, set, listeners };
}
test("slides override saved images and removal restores them without writes", async () => {
const { api, set, listeners } = fixture();
const seen: (BackgroundFrame | null)[] = [];
let savedReads = 0;
const watcher = watchBackground("pm-board:one", api, async () => { savedReads++; return frame("saved"); }, value => seen.push(value));
await watcher.refresh();
set("pm-board:one", frame("slide"));
assert.equal(seen.at(-1)?.url, "slide");
assert.equal(savedReads, 1);
set("pm-board:one", null);
await Promise.resolve();
assert.equal(seen.at(-1)?.url, "saved");
watcher.dispose();
watcher.dispose();
assert.equal(listeners.size, 0);
});
test("pending saved reads cannot replace a new slide or change a closed mount", async () => {
const { api, set } = fixture();
let resolve!: (value: BackgroundFrame) => void;
const pending = new Promise<BackgroundFrame>(done => { resolve = done; });
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-all", api, () => pending, value => seen.push(value));
const refresh = watcher.refresh();
set("pm-all", frame("slide"));
resolve(frame("stale"));
await refresh;
assert.deepEqual(seen.map(value => value?.url), ["slide"]);
set("pm-all", null);
watcher.dispose();
await Promise.resolve();
await watcher.refresh();
assert.equal(seen.length, 1);
});
test("late failures cannot clear a slide", async () => {
const { api, set } = fixture();
let reject!: (error: Error) => void;
const pending = new Promise<BackgroundFrame>( (_resolve, fail) => { reject = fail; });
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-all", api, () => pending, value => seen.push(value));
const refresh = watcher.refresh();
set("pm-all", frame("slide"));
reject(new Error("Missing image"));
await refresh;
assert.deepEqual(seen.map(value => value?.url), ["slide"]);
watcher.dispose();
});
test("split mounts subscribe separately and filter board and all-task targets", async () => {
const { api, set, listeners } = fixture();
const seen = [[], [], []] as (BackgroundFrame | null)[][];
const mounts = ["pm-board:one", "pm-board:two", "pm-all"].map((target, index) =>
watchBackground(target, api, async () => null, value => seen[index].push(value)));
set("pm-board:one", frame("one"));
assert.deepEqual(seen.map(values => values.length), [1, 0, 0]);
mounts[0].dispose();
set("pm-board:two", frame("two"));
set("pm-all", frame("all"));
assert.deepEqual(seen.map(values => values.at(-1)?.url), ["one", "two", "all"]);
mounts[1].dispose(); mounts[2].dispose();
assert.equal(listeners.size, 0);
});
test("all-board slides override saved boards and specific slides retain priority", async () => {
const { api, set } = fixture();
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-board:one", api, async () => frame("saved"), value => seen.push(value));
await watcher.refresh();
set("pm-all", frame("all"));
assert.equal(seen.at(-1)?.url, "all");
set("pm-board:one", frame("specific"));
set("pm-all", frame("next-all"));
assert.equal(seen.at(-1)?.url, "specific");
set("pm-board:one", null);
assert.equal(seen.at(-1)?.url, "next-all");
set("pm-all", null);
await Promise.resolve();
assert.equal(seen.at(-1)?.url, "saved");
watcher.dispose();
});
test("older hosts use saved images and failures clear the background", async () => {
const seen: (BackgroundFrame | null)[] = [];
let fails = false;
const watcher = watchBackground("pm-all", undefined, async () => {
if (fails) throw new Error("Missing image");
return frame("saved");
}, value => seen.push(value));
await watcher.refresh(); fails = true; await watcher.refresh();
assert.deepEqual(seen.map(value => value?.url ?? null), ["saved", null]);
watcher.dispose();
});
test("shared app slides use one host layer and react to either target changing", async () => {
const { api, set } = fixture();
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-board:one", api, async () => frame("saved"), value => seen.push(value));
set("pm-all", frame("shared"));
assert.equal(seen.at(-1)?.url, "shared");
set("app", frame("shared"));
assert.equal(seen.at(-1), null);
set("app", frame("next"));
assert.equal(seen.at(-1)?.url, "shared");
set("pm-all", frame("next"));
assert.equal(seen.at(-1), null);
set("pm-board:one", frame("specific"));
assert.equal(seen.at(-1)?.url, "specific");
set("pm-board:one", null);
assert.equal(seen.at(-1), null);
set("app", null);
assert.equal(seen.at(-1)?.url, "next");
watcher.dispose();
});
test("different image appearance and transitions keep an independent PM layer", () => {
const { api, set } = fixture();
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-all", api, async () => null, value => seen.push(value));
set("app", frame("same"));
for (const difference of [{ blurredUrl: "blob:blur" }, { overlay: 0.4 }, { size: "contain" as const }, { position: "top left" as const },
{ previous: frame("old"), transitionMs: 500 }]) {
set("pm-all", { ...frame("same"), ...difference });
assert.equal(seen.at(-1)?.url, "same");
}
set("app", { ...frame("same"), previous: frame("old"), transitionMs: 500 });
assert.equal(seen.at(-1), null);
watcher.dispose();
});
+275
View File
@@ -0,0 +1,275 @@
// The Terminal feature: the catalog entry, the shell commands and tasks, the shortcuts, the session lifecycle,
// the theme map, the settings section, and the first-start migration of the plugin settings.
import { test } from "node:test";
import assert from "node:assert/strict";
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
import { migrateFeatures } from "../../../src/lib/features/migration.ts";
import { TERMINAL_KEYS, TERMINAL_SHORTCUTS, terminalShortcut, type TerminalAction } from "../../../src/lib/features/terminalKeys.ts";
import { DEFAULT_TERMINAL, migrateTerminal, normalizeTerminal, type TerminalMigrationHost, type TerminalSettings } from "../../../src/lib/features/terminalSettings.ts";
import { directoryCommand, fileCommand, parseTasks, pickProfile, quoteShell, remember, type ShellProfile } from "../../../src/lib/features/terminal/model.ts";
import { TerminalSessions, type PtyRequest, type PtyTransport } from "../../../src/lib/features/terminal/sessions.ts";
import { SELECTION_ALPHA, TERMINAL_TOKENS, terminalColors } from "../../../src/lib/features/terminal/theme.ts";
import { ANSI_COLORS } from "../../../src/lib/theme/roles.ts";
import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../src/lib/settings/store.ts";
import type { ProjectManagementMigrationHost } from "../../../src/lib/features/pmSettings.ts";
/** A Project Management host with a section already present. */
function presentProjectManagement(): ProjectManagementMigrationHost {
return { missing: () => false, write: async () => { throw new Error("not asked"); }, storage: { getItem: () => null, setItem: () => {} } };
}
test("Terminal keeps the ID of the Terminal plugin and follows its package", () => {
const terminal = featureEntry("terminal");
assert.equal(terminal.owner, "runestone.terminal");
assert.equal(featureOfOwner("runestone.terminal")?.id, "terminal");
assert.equal(terminal.defaultOn, true);
assert.equal(terminal.followsPackage, true);
assert.deepEqual(terminal.views, []);
assert.deepEqual(terminal.commands, []);
});
test("paths are shell-quoted without evaluating metacharacters", () => {
assert.equal(directoryCommand("C:\\a'b\\$notes", "powershell"), "Set-Location -LiteralPath 'C:\\a''b\\$notes'");
assert.equal(quoteShell("/tmp/it's $(bad)", "bash"), "'/tmp/it'\\''s $(bad)'");
assert.equal(directoryCommand("C:\\two words", "cmd"), 'cd /d "C:\\two words"');
assert.equal(directoryCommand("C:\\two words", "node"), 'process.chdir("C:\\\\two words")');
assert.equal(directoryCommand("C:\\two words", "bash"), "cd -- 'C:/two words'");
assert.throws(() => quoteShell("C:\\%PATH%", "cmd"), /PowerShell/);
assert.throws(() => fileCommand("a\nwhoami.py", "powershell"), /line breaks/);
});
test("run file selects a runner and refuses documents that do not run", () => {
assert.equal(fileCommand("D:\\project\\hello world.py", "powershell"), "python 'D:\\project\\hello world.py'");
assert.equal(fileCommand("/project/app.mjs", "bash"), "node '/project/app.mjs'");
assert.equal(fileCommand("D:\\tools\\app.exe", "powershell"), "& 'D:\\tools\\app.exe'");
assert.equal(fileCommand("D:\\tools\\build.cmd", "cmd"), 'cmd /c "D:\\tools\\build.cmd"');
assert.throws(() => fileCommand("notes.md", "powershell"), /cannot run this file type/);
assert.throws(() => fileCommand("app.js", "node"), /Node\.js REPL/);
});
test("the tasks file must be valid before the panel offers a task", () => {
assert.deepEqual(parseTasks('{"tasks":[{"label":"Test","command":"npm test","profile":"pwsh"}]}'), [{ label: "Test", command: "npm test", profile: "pwsh" }]);
for (const text of ["{}", "null", '{"tasks":[null]}', '{"tasks":[{"label":"x","command":" "}]}', '{"tasks":[{"label":"x","command":"echo hi","profile":4}]}']) assert.throws(() => parseTasks(text), text);
});
test("history puts the newest value first, has no duplicates, and keeps 100 values", () => {
assert.deepEqual(remember(["one", "two"], "two"), ["two", "one"]);
assert.equal(remember(Array.from({ length: 100 }, (_, i) => String(i)), "new").length, 100);
assert.deepEqual(remember(["one"], " "), ["one"]);
});
test("a new terminal takes the default profile, then the first shell that is not Node.js", () => {
const profiles: ShellProfile[] = [{ id: "node", title: "JavaScript Debug Terminal", kind: "node" }, { id: "powershell", title: "PowerShell", kind: "powershell" }, { id: "cmd", title: "Command Prompt", kind: "cmd" }];
assert.equal(pickProfile(profiles, "cmd")?.id, "cmd");
assert.equal(pickProfile(profiles, "")?.id, "powershell");
assert.equal(pickProfile(profiles, "missing")?.id, "powershell");
assert.equal(pickProfile([profiles[0]], "")?.id, "node");
assert.equal(pickProfile([], ""), undefined);
});
/** A key event for a written combination such as "Mod+Shift+`". Mod is Ctrl. */
function press(combination: string) {
const parts = combination.split("+");
const key = parts.pop()!;
const has = (name: string) => parts.includes(name);
const code = key === "`" ? "Backquote" : /^\d$/.test(key) ? `Digit${key}` : key.length === 1 ? `Key${key.toUpperCase()}` : key;
return { ctrlKey: has("Mod") || has("Ctrl"), metaKey: false, altKey: has("Alt"), shiftKey: has("Shift"), code, key: key.length === 1 ? key.toLowerCase() : key };
}
test("physical key shortcuts tell new, split, window, and hide apart", () => {
const key = { ctrlKey: true, metaKey: false, altKey: false, shiftKey: true, code: "Backquote", key: "~" };
assert.equal(terminalShortcut(key), "new");
assert.equal(terminalShortcut({ ...key, altKey: true }), "window");
assert.equal(terminalShortcut({ ...key, code: "Digit5", key: "%" }), "split");
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyJ", key: "j" }), "toggle");
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyC", key: "c" }), null);
assert.equal(terminalShortcut({ ...key, ctrlKey: false, metaKey: true, shiftKey: false }), "toggle", "Cmd works as Ctrl on macOS.");
assert.equal(terminalShortcut({ ...key, ctrlKey: false }), null);
// Each combination that menus and Help show gives its own action.
for (const [action, combination] of Object.entries(TERMINAL_KEYS)) assert.equal(terminalShortcut(press(combination)), action as TerminalAction, combination);
assert.ok(TERMINAL_SHORTCUTS.every(row => row.label && row.keys && !/Ctrl/.test(row.keys)), "Help rows use Mod, so macOS shows Cmd.");
});
/** A fake host. `hold()` makes the next open wait for `release()`. */
function fakeTransport() {
const calls: string[] = [];
const outputs = new Map<string, { data: (bytes: Uint8Array) => void; exit: (code: number | null) => void }>();
let holding: Promise<void> = Promise.resolve();
let release: () => void = () => {};
let failClose = false;
const transport: PtyTransport = {
open: async (request: PtyRequest, data, exit) => {
calls.push(`open:${request.id}:${request.profile ?? ""}:${request.directory ?? ""}`);
outputs.set(request.id, { data, exit });
await holding;
},
write: async (id, data) => { calls.push(`write:${id}:${data}`); },
resize: async (id, cols, rows) => { calls.push(`resize:${id}:${cols}x${rows}`); },
close: async id => { calls.push(`close:${id}`); if (failClose) throw new Error("close failed"); },
profiles: async () => [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }],
openWindow: async () => { calls.push("window"); },
dictation: async () => { calls.push("dictation"); },
};
return {
transport, calls, outputs,
hold() { holding = new Promise(resolve => { release = resolve; }); },
release: () => release(),
failClose(value: boolean) { failClose = value; },
};
}
const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes);
const options = (output: string[] = [], exits: (number | null)[] = []) => ({ cwd: "C:\\work", cols: 80, rows: 24, onData: (data: Uint8Array) => output.push(text(data)), onExit: (code: number | null) => exits.push(code) });
test("sessions deliver their own output, write, resize, and close once", async () => {
const host = fakeTransport();
const sessions = new TerminalSessions(host.transport);
assert.deepEqual(await sessions.profiles(), [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }]);
const output: string[] = [];
await sessions.open("a", { ...options(output), profile: "pwsh", directory: "C:\\work\\src" });
await sessions.open("b", options());
assert.deepEqual(host.calls.slice(0, 2), ["open:a:pwsh:C:\\work\\src", "open:b::"]);
host.outputs.get("a")!.data(new TextEncoder().encode("ready"));
await sessions.write("a", "dir\r");
await sessions.resize("a", 100, 30);
assert.deepEqual(output, ["ready"]);
assert.deepEqual(host.calls.slice(-2), ["write:a:dir\r", "resize:a:100x30"]);
await assert.rejects(sessions.open("a", options()), /already running/);
await Promise.all([sessions.close("a"), sessions.close("a")]);
assert.equal(host.calls.filter(call => call === "close:a").length, 1);
await assert.rejects(sessions.write("a", "x"), /not running/);
host.outputs.get("a")!.data(new TextEncoder().encode("late"));
assert.deepEqual(output, ["ready"], "A closed pane gets no more output.");
await assert.rejects(sessions.open("a", options()), /closed/);
await assert.rejects(sessions.write("missing", "x"), /not running/);
await sessions.openWindow();
await sessions.dictation();
assert.deepEqual(host.calls.slice(-2), ["window", "dictation"]);
});
test("a close waits for the start of its shell, and a closed pane cannot start", async () => {
const host = fakeTransport();
const sessions = new TerminalSessions(host.transport);
host.hold();
const start = sessions.open("starting", options());
const close = sessions.close("starting");
assert.equal(sessions.close("starting"), close, "A second close returns the same promise.");
await Promise.resolve();
assert.deepEqual(host.calls, ["open:starting::"]);
host.release();
await Promise.all([start, close]);
assert.deepEqual(host.calls, ["open:starting::", "close:starting"]);
await sessions.close("not-started");
await assert.rejects(sessions.open("not-started", options()), /closed/);
assert.equal(host.calls.length, 2);
});
test("an exited shell needs no close, and a failed close can be tried again", async () => {
const host = fakeTransport();
const sessions = new TerminalSessions(host.transport);
const exits: (number | null)[] = [];
await sessions.open("exits", options([], exits));
host.outputs.get("exits")!.exit(3);
host.outputs.get("exits")!.exit(4);
assert.deepEqual(exits, [3], "The exit reaches the pane one time.");
await assert.rejects(sessions.write("exits", "x"), /not running/);
await sessions.close("exits");
assert.equal(host.calls.includes("close:exits"), false);
await sessions.open("writer", options());
host.failClose(true);
await assert.rejects(sessions.close("writer"), /close failed/);
host.failClose(false);
await sessions.close("writer");
assert.equal(host.calls.filter(call => call === "close:writer").length, 2);
});
test("closeAll stops every shell, also one that is starting, and later calls fail", async () => {
const host = fakeTransport();
const sessions = new TerminalSessions(host.transport);
await sessions.open("one", options());
host.hold();
const late = sessions.open("late", options());
const stopping = sessions.closeAll();
assert.equal(sessions.signal.aborted, true);
host.release();
await late;
await stopping;
assert.deepEqual(host.calls.filter(call => call.startsWith("close:")).sort(), ["close:late", "close:one"]);
await assert.rejects(sessions.open("again", options()), /This feature is off/);
await assert.rejects(sessions.profiles(), /This feature is off/);
await assert.rejects(sessions.openWindow(), /This feature is off/);
});
test("the terminal colors come from the theme tokens, with the 16 ANSI colors from --rs-ansi-*", () => {
const asked: [string, number][] = [];
const theme = terminalColors((css, maxAlpha) => { asked.push([css, maxAlpha]); return css; });
assert.equal(theme.background, "#00000000", "The panel surface shows through the terminal.");
assert.equal(theme.foreground, "var(--rs-text)");
assert.equal(theme.cursor, "var(--rs-accent)");
assert.equal(theme.cursorAccent, "var(--rs-bg)");
assert.equal(theme.selectionBackground, "var(--rs-selection)");
assert.deepEqual(asked.find(([css]) => css === "var(--rs-selection)"), ["var(--rs-selection)", SELECTION_ALPHA]);
assert.equal(SELECTION_ALPHA, 165);
for (const color of ANSI_COLORS) {
const bright = `bright${color[0].toUpperCase()}${color.slice(1)}` as keyof typeof theme;
assert.equal(theme[color], `var(--rs-ansi-${color})`);
assert.equal(theme[bright], `var(--rs-ansi-bright-${color})`);
}
assert.equal(TERMINAL_TOKENS.filter(item => item.token.startsWith("var(--rs-ansi-")).length, 16);
assert.ok(asked.filter(([css]) => css !== "var(--rs-selection)").every(([, alpha]) => alpha === 255), "Only the selection has an alpha cap.");
});
test("the terminal settings section has valid values and its own old key", () => {
assert.ok((SETTINGS_SECTIONS as readonly string[]).includes("terminal"));
assert.equal(LEGACY_KEYS.terminal, "runestone.terminal");
assert.deepEqual(normalizeTerminal(undefined), DEFAULT_TERMINAL);
assert.deepEqual(normalizeTerminal(["x"]), DEFAULT_TERMINAL);
assert.deepEqual(normalizeTerminal({ defaultProfile: "cmd", fontSize: 40, scrollback: 5, cursorBlink: false, future: 1 }),
{ defaultProfile: "cmd", fontSize: 28, scrollback: 100, cursorBlink: false });
assert.deepEqual(normalizeTerminal({ defaultProfile: 3, fontSize: 2, scrollback: 250000, cursorBlink: "no" }),
{ defaultProfile: "", fontSize: 9, scrollback: 100000, cursorBlink: true });
assert.equal(normalizeTerminal({ fontSize: 14.6 }).fontSize, 15);
assert.equal(normalizeTerminal({ fontSize: Number.NaN }).fontSize, 13);
});
function terminalHost(missing: boolean, legacy: string | null | (() => never)): TerminalMigrationHost & { written: TerminalSettings[] } {
const written: TerminalSettings[] = [];
return { written, missing: () => missing, legacy: () => typeof legacy === "function" ? legacy() : legacy, write: async value => { written.push(value); } };
}
test("the first start copies the plugin settings into the terminal section once", async () => {
const plugin = JSON.stringify({ defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false });
const copy = terminalHost(true, plugin);
assert.deepEqual(await migrateTerminal(copy), { defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false });
assert.deepEqual(copy.written, [{ defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false }]);
const present = terminalHost(false, plugin);
assert.equal(await migrateTerminal(present), null);
assert.deepEqual(present.written, [], "An existing section stays.");
const none = terminalHost(true, null);
assert.equal(await migrateTerminal(none), null);
assert.deepEqual(none.written, [], "Without the old key, the defaults apply and nothing is written.");
const damaged = terminalHost(true, "{not json");
assert.deepEqual(await migrateTerminal(damaged), DEFAULT_TERMINAL);
const blocked = terminalHost(true, () => { throw new Error("storage is blocked"); });
assert.equal(await migrateTerminal(blocked), null);
});
test("the feature migration copies the terminal settings also when the package report fails", async () => {
const error = console.error;
console.error = () => {};
try {
const terminal = terminalHost(true, JSON.stringify({ fontSize: 20 }));
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
const host = { read: () => undefined, write: async () => { throw new Error("not asked"); }, legacy: async () => { throw new Error("no host"); } };
assert.deepEqual(await migrateFeatures(host, background, terminal, presentProjectManagement()), []);
assert.deepEqual(terminal.written, [{ ...DEFAULT_TERMINAL, fontSize: 20 }]);
} finally { console.error = error; }
});
test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => {
const writes: unknown[] = [];
const host = { read: () => ({ git: true, background: true, pdf: true, pm: true }), write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => ids.map(id => ({ id, installed: true, enabled: false, settings: null })) };
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null), presentProjectManagement()), ["terminal"]);
assert.deepEqual(writes, [{ git: true, background: true, pdf: true, pm: true, terminal: false }]);
});
+80
View File
@@ -0,0 +1,80 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { catalogs, messageRows } from '../../src/lib/i18n/messages.ts';
import { get } from 'svelte/store';
import { LANGUAGE_KEY, locale, normalizeLocale, setLocale, t, translate, syncLocale } from '../../src/lib/i18n/index.ts';
import { initSettings } from '../../src/lib/settings/store.ts';
test('Every catalog entry has all translations and preserves its placeholders', () => {
const seen = new Set<string>();
for (const [english, ...translations] of messageRows) {
assert(!seen.has(english), `Duplicate message: ${english}`); seen.add(english);
const placeholders = (value: string) => [...value.matchAll(/\{(\w+)\}/g)].map(match => match[1]).sort();
for (const value of translations) {
assert(value.trim(), `Empty translation: ${english}`);
assert.deepEqual(placeholders(value), placeholders(english), english);
}
}
assert.equal(Object.keys(catalogs.fr).length, messageRows.length);
});
test('Locale parsing rejects unsupported values and interpolation preserves user text', () => {
assert.equal(normalizeLocale('ja'), 'ja');
assert.equal(normalizeLocale('zh-CN'), 'zh-CN');
for (const value of [null, undefined, 'constructor', 'de', [], {}]) assert.equal(normalizeLocale(value), 'en');
assert.equal(translate('fr', 'Missing source text'), 'Missing source text');
assert.equal(translate('ja', 'Close {name}', { name: '<script>例.md</script>' }), '<script>例.md</script>を閉じる');
});
test('Language saves before reactive changes and syncs across windows', async () => {
const stored = new Map<string, string>();
const events = new Map<string, Function>();
const priorStorage = globalThis.localStorage, priorWindow = globalThis.window, priorDocument = globalThis.document;
try {
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage;
globalThis.window = { addEventListener: (key: string, handler: Function) => events.set(key, handler), removeEventListener: (key: string) => events.delete(key) } as unknown as Window & typeof globalThis;
globalThis.document = { documentElement: { lang: '' } } as unknown as Document;
// Without the desktop host, the settings store keeps the language in localStorage and listens for storage events.
await initSettings(() => ({}));
const stop = syncLocale();
await setLocale('fr');
assert.equal(stored.get(LANGUAGE_KEY), 'fr');
assert.equal(get(t)('Settings'), 'Paramètres');
assert.equal(document.documentElement.lang, 'fr');
stored.set(LANGUAGE_KEY, 'zh-CN'); events.get('storage')!({ key: LANGUAGE_KEY });
assert.equal(get(locale), 'zh-CN'); assert.equal(get(t)('Settings'), '设置');
globalThis.localStorage.setItem = () => { throw new Error('Storage unavailable'); };
assert.throws(() => setLocale('ja'));
assert.equal(get(locale), 'zh-CN');
stop();
stored.set(LANGUAGE_KEY, 'ja'); events.get('storage')!({ key: LANGUAGE_KEY });
assert.equal(get(locale), 'zh-CN', 'A stopped sync ignores later changes');
} finally { globalThis.localStorage = priorStorage; globalThis.window = priorWindow; globalThis.document = priorDocument; locale.set('en'); }
});
import { readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
function sourceFiles(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap(entry => entry.isDirectory() ? sourceFiles(path.join(dir, entry.name)) : /\.(ts|svelte)$/.test(entry.name) ? [path.join(dir, entry.name)] : []);
}
test('Every static host translation call has all three catalog entries', () => {
const missing: string[] = [];
for (const file of sourceFiles('src/lib')) {
const source = readFileSync(file, 'utf8');
for (const match of source.matchAll(/(?:\$t|\btr)\(\s*((?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'))/g)) {
const parsed = ts.createSourceFile('literal.ts', match[1], ts.ScriptTarget.Latest, true);
const statement = parsed.statements[0];
const value = ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression) ? statement.expression.text : '';
if (value && !Object.hasOwn(catalogs.fr, value)) missing.push(`${file}: ${value}`);
}
}
assert.deepEqual(missing, []);
});
test('Keyboard identifiers remain untranslated in event handlers', () => {
const failures: string[] = [];
for (const file of sourceFiles('src/lib')) {
const source = readFileSync(file, 'utf8');
for (const line of source.split(/\r?\n/)) {
if (/event\.(?:key|code)\s*[!=]==?\s*(?:tr|\$t)\(/.test(line) || /(?:tr|\$t)\([^\n]+\]\.(?:includes|indexOf)\(event\.(?:key|code)/.test(line)) failures.push(`${file}: ${line.trim()}`);
}
}
assert.deepEqual(failures, []);
});
+184
View File
@@ -0,0 +1,184 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView, splitWithContent, showInActivePane, paneOf, releaseSolePlugin, dropInPane, moveToNewPane, resizeDocumentPanes } from "../../../src/lib/workspace/documentPanes.ts";
import { paneBounds, splitDividers, splitSibling, stackLayout, setSplitRatio } from "../../../src/lib/workspace/splitLayout.ts";
import { registerSelection, selectedEditorText } from "../../../src/lib/editor/selection.ts";
test("opening a link to the right keeps its source and focuses an existing pane for duplicate targets", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
const primary = state.active;
state = readDocumentPane(state, primary, true);
state = splitDocumentPane(state, primary, "b", "right");
assert.deepEqual(state.panes.map(pane => pane.documentId), ["a", "b"]);
assert.equal(state.active, "right");
assert.deepEqual(paneBounds(state.layout).right, { left: 50, top: 0, width: 50, height: 100 });
state = splitDocumentPane(state, "right", "a", "unused");
assert.equal(state.active, primary);
assert.equal(state.panes.length, 2);
assert.equal(state.panes[0].reading, true);
state = splitDocumentPane(state, "right", "c", "third");
assert.equal(paneBounds(state.layout).third.left, 75);
});
test("Read and Split exclude each other, and a closed document resets both", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
const pane = state.active;
state = splitDocumentView(state, pane, true);
assert.deepEqual([state.panes[0].reading, state.panes[0].split], [false, true]);
state = readDocumentPane(state, pane, true);
assert.deepEqual([state.panes[0].reading, state.panes[0].split], [true, false]);
state = splitDocumentView(state, pane, true);
assert.deepEqual([state.panes[0].reading, state.panes[0].split], [false, true]);
// Write and Source keep the Split view.
state = readDocumentPane(state, pane, false);
assert.equal(state.panes[0].split, true);
state = syncDocumentPanes(state, ["b"], "b");
assert.deepEqual([state.panes[0].documentId, state.panes[0].reading, state.panes[0].split], ["b", false, false]);
});
test("closing a split preserves the remaining pane and a later tab selection can restore its hidden document", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
state = splitDocumentPane(state, state.active, "b", "right");
state = closeDocumentPane(state, "right");
assert.equal(state.panes[0].documentId, "a");
assert.equal(state.layout, state.active);
state = syncDocumentPanes(state, ["a", "b"], "b");
assert.equal(state.panes[0].documentId, "b");
});
test("tab replacement stays in its focused pane, and closing another tab collapses only its empty pane", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
state = splitDocumentPane(state, state.active, "b", "right");
state = syncDocumentPanes(state, ["a", "c"], "c");
assert.deepEqual(state.panes.map(pane => pane.documentId), ["a", "c"]);
assert.equal(state.active, "right");
const unchanged = syncDocumentPanes(state, ["a", "c"], "c");
assert.equal(unchanged, state);
state = syncDocumentPanes(state, ["c"], "c");
assert.equal(state.panes.length, 1);
assert.equal(state.layout, "right");
assert.equal(selectPane(state, "missing"), state);
});
test("selection readers remain available in both panes and disposal cannot clear a replacement reader", () => {
const first = registerSelection("a", () => "first selection");
const second = registerSelection("b", () => "second selection");
assert.equal(selectedEditorText("a"), "first selection");
assert.equal(selectedEditorText("b"), "second selection");
const replacement = registerSelection("a", () => "new selection");
first(); second();
assert.equal(selectedEditorText("a"), "new selection");
assert.equal(selectedEditorText("b"), "");
replacement();
});
test("a pane shows a document or a plugin view, and each tab has at most one pane", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
const primary = state.active;
state = splitWithContent(state, primary, { pluginKey: "browser" }, "web");
assert.deepEqual(state.panes.map(pane => [pane.documentId, pane.pluginKey]), [["a", null], [null, "browser"]]);
assert.equal(state.active, "web");
assert.equal(splitWithContent(state, primary, { pluginKey: "browser" }, "again"), selectPane(state, "web"));
// A document change does not remove the plugin pane.
assert.equal(syncDocumentPanes(state, ["a", "b"], null), state);
// A selected document replaces the view of the active pane. The view stays open as a tab.
const replaced = syncDocumentPanes(state, ["a", "b"], "b");
assert.deepEqual(replaced.panes.map(pane => [pane.documentId, pane.pluginKey]), [["a", null], ["b", null]]);
// A plugin view replaces the document of the active pane, and a shown document selects its pane.
state = showInActivePane(selectPane(replaced, primary), { pluginKey: "board" });
assert.deepEqual(state.panes.map(pane => [pane.documentId, pane.pluginKey]), [[null, "board"], ["b", null]]);
assert.equal(showInActivePane(state, { documentId: "b" }).active, "web");
assert.equal(paneOf(state, { pluginKey: "board" })?.id, primary);
});
test("a closed plugin view leaves its pane, and the last pane gives its plugin view back to the whole area", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a"], "a");
state = splitWithContent(state, state.active, { pluginKey: "browser" }, "web", "down");
assert.deepEqual(paneBounds(state.layout).web, { left: 0, top: 50, width: 100, height: 50 });
assert.deepEqual(paneBounds(stackLayout({ direction: "right", first: "x", second: "y" })).y, { left: 0, top: 50, width: 100, height: 50 });
const closed = syncDocumentPanes(state, ["a"], null, []);
assert.deepEqual(closed.panes.map(pane => pane.id), ["document-main"]);
const remaining = closeDocumentPane(state, "document-main");
assert.equal(remaining.active, "web");
const released = releaseSolePlugin(remaining);
assert.equal(released.pluginKey, "browser");
assert.deepEqual([released.state.panes[0].documentId, released.state.panes[0].pluginKey], [null, null]);
assert.equal(releaseSolePlugin(closed).state, closed);
});
test("the split sibling names the pane that a plugin view opened beside", () => {
const tree = { direction: "right" as const, first: "a", second: { direction: "down" as const, first: "b", second: "c" } };
assert.deepEqual(splitSibling(tree, "c"), { direction: "down", sibling: "b" });
assert.deepEqual(splitSibling(tree, "a"), { direction: "right", sibling: "b" });
assert.equal(splitSibling("a", "a"), null);
});
test("a divider changes the ratio of its split, within limits, and the narrow layout keeps the ratio", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
state = splitDocumentPane(state, state.active, "b", "right");
state = splitWithContent(state, "right", { documentId: "c" }, "low", "down");
const dividers = splitDividers(state.layout);
assert.deepEqual(dividers.map(divider => [divider.path.join("/"), divider.direction, divider.ratio]), [["", "right", 0.5], ["second", "down", 0.5]]);
state = resizeDocumentPanes(state, [], 0.3);
state = resizeDocumentPanes(state, ["second"], 0.75);
const bounds = paneBounds(state.layout);
assert.equal(bounds["document-main"].width, 30);
assert.deepEqual(bounds.right, { left: 30, top: 0, width: 70, height: 75 });
assert.equal(bounds.low.top, 75);
assert.equal(paneBounds(stackLayout(state.layout))["document-main"].height, 30);
assert.equal(paneBounds(resizeDocumentPanes(state, [], 0.02).layout)["document-main"].width, 10, "A pane keeps a tenth of the split at least");
assert.equal(setSplitRatio("only", [], 0.4), "only");
assert.equal(resizeDocumentPanes(state, ["second", "first"], 0.4), state, "A path to a pane changes nothing");
});
test("a tab drop replaces the content of a pane or opens a pane beside it, and the content leaves its old pane", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
const main = state.active;
state = splitWithContent(state, main, { pluginKey: "web" }, "right");
// A document dropped in the browser pane replaces the browser there. The browser stays open as a tab.
let next = dropInPane(state, { documentId: "b" }, "right", "center", "new");
assert.deepEqual(next.panes.map(pane => [pane.documentId, pane.pluginKey]), [["a", null], ["b", null]]);
assert.equal(next.active, "right");
// A drop on the bottom side of a pane opens a new pane there.
next = dropInPane(state, { documentId: "c" }, main, "down", "new");
assert.deepEqual(paneBounds(next.layout).new, { left: 0, top: 50, width: 50, height: 50 });
assert.equal(next.active, "new");
// A drop on the left side of a pane opens a new pane before it.
next = dropInPane(state, { documentId: "c" }, "right", "left", "new");
assert.deepEqual(paneBounds(next.layout), { [main]: { left: 0, top: 0, width: 50, height: 100 }, new: { left: 50, top: 0, width: 25, height: 100 }, right: { left: 75, top: 0, width: 25, height: 100 } });
assert.equal(next.active, "new");
// A visible tab moves: its old pane closes.
next = dropInPane(state, { pluginKey: "web" }, main, "down", "new");
assert.deepEqual(next.panes.map(pane => [pane.id, pane.pluginKey]), [[main, null], ["new", "web"]]);
assert.deepEqual(paneBounds(next.layout).new, { left: 0, top: 50, width: 100, height: 50 });
next = dropInPane(state, { pluginKey: "web" }, main, "center", "new");
assert.deepEqual(next.panes.map(pane => pane.pluginKey), ["web"]);
// A drop on the pane that shows the content only makes it active.
assert.equal(dropInPane(state, { pluginKey: "web" }, "right", "down", "new").panes.length, 2);
assert.equal(dropInPane(state, { documentId: "a" }, "missing", "center", "new"), state);
});
test("the content of a pane moves to a new pane beside it, and the pane shows other content", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
const main = state.active;
state = readDocumentPane(state, main, true);
// The visible document moves to the right. Its pane shows the next document, in the default view.
let next = moveToNewPane(state, main, { documentId: "b" }, { documentId: "a" }, "right", "new");
assert.deepEqual(next.panes.map(pane => [pane.id, pane.documentId, pane.reading]), [[main, "b", false], ["new", "a", false]]);
assert.deepEqual(paneBounds(next.layout).new, { left: 50, top: 0, width: 50, height: 100 });
assert.equal(next.active, "new");
// A plugin view that covers the area moves below. The pane keeps its document and its view.
next = moveToNewPane(state, main, { documentId: "a" }, { pluginKey: "web" }, "down", "new");
assert.deepEqual(next.panes.map(pane => [pane.documentId, pane.pluginKey, pane.reading]), [["a", null, true], [null, "web", false]]);
assert.deepEqual(paneBounds(next.layout).new, { left: 0, top: 50, width: 100, height: 50 });
// The visible document moves to a new pane on the left.
next = moveToNewPane(state, main, { documentId: "b" }, { documentId: "a" }, "left", "new");
assert.deepEqual(next.panes.map(pane => [pane.id, pane.documentId]), [[main, "b"], ["new", "a"]]);
assert.deepEqual(paneBounds(next.layout), { new: { left: 0, top: 0, width: 50, height: 100 }, [main]: { left: 50, top: 0, width: 50, height: 100 } });
next = moveToNewPane(state, main, { documentId: "a" }, { pluginKey: "web" }, "down", "new");
// Content that a different pane shows cannot stay, and cannot move from this pane.
assert.equal(moveToNewPane(next, main, { pluginKey: "web" }, { documentId: "a" }, "right", "third"), next);
assert.equal(moveToNewPane(next, main, { documentId: "b" }, { pluginKey: "web" }, "right", "third"), next);
assert.equal(moveToNewPane(state, "missing", { documentId: "b" }, { documentId: "a" }, "right", "new"), state);
});
+55
View File
@@ -0,0 +1,55 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_SETTINGS, SETTINGS_KEY, normalizeSettings, parseSettings, readSettings, saveSettings } from "../../../src/lib/workspace/settings.ts";
test("missing or damaged preferences keep safe defaults", () => {
for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) {
assert.deepEqual(parseSettings(raw), DEFAULT_SETTINGS);
}
for (const autosaveSeconds of [0, -1, 301, 1.5, "10", null]) {
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds, showInternalFolder: false })), { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false });
}
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false });
});
function withStorage(storage: Pick<Storage, "getItem" | "setItem">, body: () => void) {
const prior = globalThis.localStorage;
try { globalThis.localStorage = storage as Storage; body(); }
finally { globalThis.localStorage = prior; }
}
test("preferences persist and load at both interval limits", () => {
const store = new Map<string, string>();
withStorage({ getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => { store.set(key, value); } }, () => {
for (const autosaveSeconds of [1, 23, 300]) {
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false, tableFormulas: autosaveSeconds !== 23, showFileTitle: autosaveSeconds !== 300, keepLineBreaks: autosaveSeconds === 1 };
void saveSettings(settings);
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
assert.deepEqual(readSettings(), settings);
}
});
});
test("invalid changes never reach storage and storage failures reach the caller", () => {
let writes = 0;
withStorage({ getItem: () => null, setItem: () => { writes++; } }, () => {
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
assert.throws(() => saveSettings({ autosaveEnabled: true, autosaveSeconds, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false }));
}
});
assert.equal(writes, 0);
withStorage({ getItem: () => null, setItem: () => { throw new Error("Storage unavailable"); } }, () => {
assert.throws(() => saveSettings({ ...DEFAULT_SETTINGS }), /Storage unavailable/);
});
});
test("stored values of any type normalize to safe settings", () => {
for (const value of [undefined, null, 42, "text", [], { autosaveSeconds: 0 }]) assert.deepEqual(normalizeSettings(value), DEFAULT_SETTINGS);
assert.deepEqual(normalizeSettings({ autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true }), { autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true, tableFormulas: true, showFileTitle: true, keepLineBreaks: false });
assert.equal(normalizeSettings({ tableFormulas: false }).tableFormulas, false);
for (const tableFormulas of [null, 0, "false", {}]) assert.equal(normalizeSettings({ tableFormulas }).tableFormulas, true);
assert.equal(normalizeSettings({ showFileTitle: false }).showFileTitle, false);
for (const showFileTitle of [null, 0, "false", {}]) assert.equal(normalizeSettings({ showFileTitle }).showFileTitle, true);
assert.equal(normalizeSettings({ keepLineBreaks: true }).keepLineBreaks, true);
for (const keepLineBreaks of [null, 1, "true", {}]) assert.equal(normalizeSettings({ keepLineBreaks }).keepLineBreaks, false);
});
+18
View File
@@ -0,0 +1,18 @@
import test from "node:test";
import assert from "node:assert/strict";
import { splitPane, removePane, paneBounds, containsPane } from "../../../src/lib/workspace/splitLayout.ts";
test("nested splits preserve the source and divide the requested pane", () => {
const right = splitPane("a", "a", "b", "right");
const nested = splitPane(right, "b", "c", "down");
assert.deepEqual(paneBounds(nested), {
a: { left: 0, top: 0, width: 50, height: 100 },
b: { left: 50, top: 0, width: 50, height: 50 },
c: { left: 50, top: 50, width: 50, height: 50 },
});
assert.equal(containsPane(nested, "c"), true);
const closed = removePane(nested, "b")!;
assert.deepEqual(paneBounds(closed).c, { left: 50, top: 0, width: 50, height: 100 });
assert.equal(removePane(closed, "a"), "c");
assert.equal(removePane("c", "c"), null);
});
+46
View File
@@ -0,0 +1,46 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { tabsToClose } from "../../../src/lib/workspace/tabActions.ts";
import { Documents } from "../../../src/lib/workspace/documents.svelte.ts";
function setup() {
return new Documents({
read: async () => "original", write: async () => {}, image: async () => "data:image/png;base64,",
kind: () => "text", chrome: () => "Writing",
}, () => {});
}
const entry = (path: string) => ({ rel_path: path, name: path, kind: "file" as const });
test("group closes follow tab order and preserve pins without changing the active tab", async () => {
const docs = setup();
for (const name of ["a.md", "b.md", "c.md", "d.md"]) await docs.open(entry(name));
docs.togglePin("b.md");
docs.move("d.md", 1);
const paths = (scope: "one" | "others" | "after" | "all") => tabsToClose(docs.buffers, "d.md", scope).map(tab => tab.relPath);
assert.deepEqual(paths("one"), ["d.md"]);
assert.deepEqual(paths("others"), ["a.md", "c.md"]);
assert.deepEqual(paths("after"), ["c.md"]);
assert.deepEqual(paths("all"), ["a.md", "d.md", "c.md"]);
assert.equal(docs.activePath, "d.md");
assert.deepEqual(tabsToClose(docs.buffers, "missing.md", "all"), []);
assert.equal(tabsToClose(docs.buffers, "b.md", "one")[0].pinned, true);
});
test("pinning protects current and empty tabs from replacement, and survives rename", async () => {
const docs = setup();
await docs.open(entry("a.md"));
docs.togglePin("a.md");
await docs.open(entry("b.md"), "current");
assert.deepEqual(docs.buffers.map(tab => tab.relPath), ["a.md", "b.md"]);
docs.rename("a.md", "renamed.md");
assert.equal(docs.buffers[0].pinned, true);
docs.newTab();
const blank = docs.active!;
docs.togglePin(blank.relPath);
await docs.open(entry("c.md"));
assert.ok(docs.buffers.includes(blank));
docs.select("renamed.md");
docs.togglePin("renamed.md");
await docs.open(entry("d.md"), "current");
assert.ok(!docs.buffers.some(tab => tab.relPath === "renamed.md"));
});
+44
View File
@@ -0,0 +1,44 @@
import assert from "node:assert/strict";
import test from "node:test";
import { COMMAND_LABELS, commandShortcut, preferenceKeys, workbenchCommand, workbenchKeys } from "../../../src/lib/layout/workbenchKeys.ts";
import { shortcutLabel } from "../../../src/lib/ui/shortcuts.ts";
const press = (key: string, modifiers: { ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean } = {}, code?: string) =>
({ key, code, ctrlKey: !!modifiers.ctrl, metaKey: !!modifiers.meta, shiftKey: !!modifiers.shift, altKey: !!modifiers.alt, target: null });
test("main shortcuts accept Ctrl and Cmd and keep their shift rules", () => {
assert.equal(workbenchCommand(press("p", { ctrl: true })), "quick-open");
assert.equal(workbenchCommand(press("P", { meta: true, shift: true })), "command-palette");
assert.equal(workbenchCommand(press("P", { ctrl: true, shift: true })), "command-palette");
assert.equal(workbenchCommand(press("t", { ctrl: true })), "new-tab");
assert.equal(workbenchCommand(press("T", { ctrl: true, shift: true })), null);
assert.equal(workbenchCommand(press("F", { ctrl: true, shift: true })), "search-workspace");
assert.equal(workbenchCommand(press("f", { ctrl: true })), null, "Ctrl+F belongs to the document");
assert.equal(workbenchCommand(press("`", { ctrl: true })), "toggle-terminal");
});
test("Ctrl+B belongs to the editor, and Ctrl+\\ toggles the side pane on every layout", () => {
assert.equal(workbenchCommand(press("b", { ctrl: true })), null);
assert.equal(workbenchCommand(press("\\", { ctrl: true }, "Backslash")), "toggle-sidebar");
assert.equal(workbenchCommand(press("#", { ctrl: true }, "Backslash")), "toggle-sidebar", "The physical key matches on other layouts");
});
test("Each command has a label, and its shortcut label comes from the table", () => {
for (const binding of [...workbenchKeys, ...preferenceKeys]) assert.ok(COMMAND_LABELS[binding.command], binding.command);
assert.equal(commandShortcut("save"), shortcutLabel({ key: "s", mod: true }));
});
test("F2 renames outside text fields only", () => {
assert.equal(workbenchCommand(press("F2")), "rename");
assert.equal(workbenchCommand(press("F2", { alt: true })), null);
assert.equal(workbenchCommand(press("F2", { ctrl: true })), null);
});
test("preference shortcuts switch tabs with Ctrl only and open Settings and Help", () => {
assert.equal(workbenchCommand(press("Tab", { ctrl: true }), preferenceKeys), "next-tab");
assert.equal(workbenchCommand(press("Tab", { ctrl: true, shift: true }), preferenceKeys), "previous-tab");
assert.equal(workbenchCommand(press("Tab", { meta: true }), preferenceKeys), null);
assert.equal(workbenchCommand(press(",", { meta: true }), preferenceKeys), "settings");
assert.equal(workbenchCommand(press("F1"), preferenceKeys), "help");
assert.equal(workbenchCommand(press("F1", { shift: true }), preferenceKeys), null);
});
+32
View File
@@ -0,0 +1,32 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout } from "../../../src/lib/workspace/workbenchLayout.ts";
test("missing and damaged layouts use defaults", () => {
for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) {
assert.deepEqual(parseWorkbenchLayout(raw), DEFAULT_WORKBENCH_LAYOUT);
}
});
test("invalid layout fields do not discard valid collapsed states", () => {
for (const leftWidth of [0, -1, 159, 481, "260", null]) {
assert.deepEqual(parseWorkbenchLayout(JSON.stringify({ leftOpen: false, rightOpen: false, leftWidth, rightWidth: 320, leftView: "unknown", backlinksOpen: "false" })), {
...DEFAULT_WORKBENCH_LAYOUT, leftOpen: false, rightOpen: false, rightWidth: 320,
});
}
assert.deepEqual(parseWorkbenchLayout('{"leftOpen":"false","rightOpen":0}'), DEFAULT_WORKBENCH_LAYOUT);
// A layout from an older version has no backlinks field. The section starts expanded.
assert.equal(parseWorkbenchLayout('{"leftOpen":false}').backlinksOpen, true);
});
test("layout survives storage round trips with hidden panels, all navigation views, and collapsed backlinks", () => {
const store = new Map<string, string>();
for (const leftView of ["files", "search", "bookmarks"] as const) {
for (const [leftWidth, backlinksOpen] of [[160, false], [321.5, true], [480, false]] as const) {
const layout = { leftOpen: false, rightOpen: false, leftWidth, rightWidth: 400, leftView, backlinksOpen };
saveWorkbenchLayout({ setItem: (key, value) => { store.set(key, value); } }, layout);
assert.deepEqual(parseWorkbenchLayout(store.get(WORKBENCH_LAYOUT_KEY)!), layout);
}
}
assert.throws(() => saveWorkbenchLayout({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_WORKBENCH_LAYOUT }), /Storage unavailable/);
});
+38
View File
@@ -0,0 +1,38 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { orderWorkbenchTabs } from "../../../src/lib/workspace/workbenchTabs.ts";
import { tabsToClose } from "../../../src/lib/workspace/tabActions.ts";
import { Documents } from "../../../src/lib/workspace/documents.svelte.ts";
test("mixed tabs retain their positions through title changes, closes, and new tabs", () => {
const tabs = [
{ id: "a", relPath: "a.md", name: "a.md", pinned: true },
{ id: "b", relPath: "renamed.md", name: "renamed.md" },
{ id: "plugin-a", relPath: "plugin:a", name: "New page title" },
{ id: "plugin-b", relPath: "plugin:b", name: "Board" },
];
const ordered = orderWorkbenchTabs(tabs, ["plugin-a", "b", "a", "closed", "plugin-a"]);
assert.deepEqual(ordered.map(tab => tab.id), ["plugin-a", "b", "a", "plugin-b"]);
assert.equal(ordered[0].name, "New page title");
assert.deepEqual(tabsToClose(ordered, "plugin:a", "after").map(tab => tab.id), ["b", "plugin-b"]);
assert.deepEqual(tabsToClose(ordered, "renamed.md", "others").map(tab => tab.id), ["plugin-a", "plugin-b"]);
assert.deepEqual(tabsToClose(ordered, "plugin:b", "all").map(tab => tab.id), ["plugin-a", "b", "plugin-b"]);
});
test("replacing an empty or current document retains its tab position and creates a new buffer", async () => {
const docs = new Documents({
read: async path => path, write: async () => {}, image: async () => "",
kind: () => "text", chrome: () => "Writing",
}, () => {});
docs.newTab();
const emptyId = docs.active!.id;
const order = ["plugin-a", emptyId, "plugin-b"];
for (const rel_path of ["a.md", "b.md"]) {
const previousBuffer = docs.active!.id;
await docs.open({ rel_path, name: rel_path, kind: "file" }, "current");
assert.notEqual(docs.active!.id, previousBuffer);
assert.equal(docs.active!.tabId, emptyId);
const tabs = [{ id: "plugin-a" }, { id: "plugin-b" }, { id: docs.active!.tabId! }];
assert.deepEqual(orderWorkbenchTabs(tabs, order).map(tab => tab.id), order);
}
});
+33
View File
@@ -0,0 +1,33 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { documentLinks, documentLinkAt } from "../../../src/lib/editor/documentLinks.ts";
test("document links keep complete source ranges and decode Markdown destinations", () => {
const source = '[Local](<notes/two words.md> "Title") and [Web](https://example.com/a_(b)) and [[Another note|Alias]]';
const links = documentLinks(source);
assert.deepEqual(links.map(link => [link.kind, link.target]), [["md", "notes/two words.md"], ["md", "https://example.com/a_(b)"], ["wiki", "Another note"]]);
for (const link of links) {
assert.equal(documentLinkAt(source, link.from + 2)?.target, link.target);
assert.equal(documentLinkAt(source, link.to - 1)?.target, link.target);
}
});
test("literal code and images cannot become document links", () => {
const source = '![Image](image.png) `https://example.com`\n\n```md\n[Hidden](hidden.md)\n[[Hidden]]\n```\n\n[Open](open.md)';
assert.deepEqual(documentLinks(source).map(link => link.target), ["open.md"]);
});
test("bare and angle links omit prose punctuation and preserve balanced parentheses", () => {
const source = 'Go to https://example.com/a_(b). Next (<https://example.org>). Mail <mailto:[email protected]>.';
assert.deepEqual(documentLinks(source).map(link => link.target), ["https://example.com/a_(b)", "https://example.org", "mailto:[email protected]"]);
});
test("edit link selects only its destination, preserving labels, titles, brackets, and spacing", () => {
const source = '[Local](<notes/two words.md> "Title") and [Web](https://example.com/a_\\(b\\)) and [[ Another note#Heading |Alias]] and <https://example.org>.';
const links = documentLinks(source);
assert.deepEqual(links.map(link => source.slice(link.targetFrom, link.targetTo)), ["notes/two words.md", "https://example.com/a_\\(b\\)", "Another note#Heading", "https://example.org"]);
});
test("wiki image embeds do not expose document actions", () => {
assert.deepEqual(documentLinks('![[image.png]] [[note|label]]').map(link => link.target), ["note"]);
});
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import test from "node:test";
import { documentHeadings, headingLinkLine, linkFragment } from "../../../src/lib/workspace/headingLinks.ts";
test("section links decode fragments without changing the file path", () => {
assert.equal(linkFragment("notes/a%23b.md#Caf%C3%A9%20setup"), "Café setup");
assert.equal(linkFragment("#literal%"), "literal%");
assert.equal(linkFragment("a.md"), null);
assert.equal(headingLinkLine("# Title", ""), 1);
});
test("headings use rendered text, Unicode, and unique slugs", () => {
const source = "# **Windows** setup!\n\n## Café `setup`\n\n## Windows setup!\n\n## Windows setup-1\n\n## Windows setup!\n";
assert.deepEqual(documentHeadings(source).map(({ slug }) => slug),
["windows-setup", "café-setup", "windows-setup-1", "windows-setup-1-1", "windows-setup-2"]);
assert.equal(headingLinkLine(source, "windows-setup-2"), 9);
assert.equal(headingLinkLine(source, "Café setup"), 3);
assert.equal(headingLinkLine(source, "missing"), null);
});
test("section lines exclude properties and code, and include Setext headings", () => {
const source = "---\r\ntitle: Test\r\n---\r\n\r\n```md\r\n# Fake\r\n```\r\n\r\nInstall\r\n=======\r\n\r\n## Real ###\r\n";
assert.deepEqual(documentHeadings(source), [
{ level: 1, text: "Install", slug: "install", line: 9 },
{ level: 2, text: "Real", slug: "real", line: 12 },
]);
assert.equal(headingLinkLine(source, "fake"), null);
});
+31
View File
@@ -0,0 +1,31 @@
import assert from "node:assert/strict";
import test from "node:test";
import { externalLinkText, workspaceLinkText } from "../../../src/lib/editor/linkCommands.ts";
import { linkCandidates } from "../../../src/lib/workspace/markdownLinks.ts";
test("external links prepare editable syntax with the cursor in the missing field", () => {
const empty = externalLinkText("", { from: 0, to: 0 });
assert.equal(empty.insert, "[]()");
assert.equal(empty.anchor, 1);
assert.equal(empty.head, 1);
const selected = externalLinkText("before [label] after", { from: 7, to: 14 });
assert.equal(selected.insert, "[\\[label\\]]()");
assert.equal(selected.anchor - selected.from, selected.insert.length - 1);
assert.equal(selected.anchor, selected.head);
});
test("workspace links retain the selected label and the exact workspace path", () => {
assert.equal(workspaceLinkText("", { from: 0, to: 0 }, "notes/Same name.md").insert, "[[/notes/Same%20name.md]]");
const edit = workspaceLinkText("before visible\nlabel after", { from: 7, to: 20 }, "nested/target.md");
assert.equal(edit.insert, "[[/nested/target.md|visible label]]");
assert.equal(edit.anchor, 7);
assert.equal(edit.head, 7 + edit.insert.length);
});
test("workspace link paths preserve spaces, brackets, hashes and literal percent signs", () => {
const path = "notes/Nested/[A] #50%.md";
const edit = workspaceLinkText("", { from: 0, to: 0 }, path);
const target = edit.insert.slice(2, -2);
assert.equal(target, "/notes/Nested/%5BA%5D%20%2350%25.md");
assert.deepEqual(linkCandidates("notes/current.md", target, "wiki"), [path]);
});
+37
View File
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import test from "node:test";
import { findMarkdownLinks, wikiCandidates } from "../../../src/lib/workspace/markdownLinks.ts";
test("markdown links skip image embeds", () => {
const links = findMarkdownLinks("See [alpha](notes/a.md) and ![shot](pic.png)");
assert.deepEqual(links, [
{ kind: "md", from: 4, to: 23, label: "alpha", target: "notes/a.md" },
]);
});
test("wikilinks skip image embeds", () => {
const links = findMarkdownLinks("Go [[projects/alpha|Alpha]] and ![[screenshot.png]]");
assert.deepEqual(links, [
{
kind: "wiki",
from: 3,
to: 27,
label: "Alpha",
target: "projects/alpha",
},
]);
});
test("wikiCandidates add .md for a bare name", () => {
assert.deepEqual(wikiCandidates("alpha"), ["alpha.md", "notes/alpha.md", "alpha"]);
});
import { linkCandidates } from "../../../src/lib/workspace/markdownLinks.ts";
test("links resolve relative to notes, including parent paths and encoded spaces", () => {
assert.deepEqual(linkCandidates("notes/project/inbox.md", "../other%20note.md", "md"), ["notes/other note.md"]);
assert.deepEqual(linkCandidates("notes/inbox.md", "ideas", "wiki"), ["notes/ideas.md", "notes/ideas", "ideas.md", "ideas"]);
assert.deepEqual(linkCandidates("notes/inbox.md", "../../secret", "md"), []);
assert.deepEqual(linkCandidates("notes/inbox.md", "javascript:alert(1)", "md"), []);
});
+30
View File
@@ -0,0 +1,30 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { documentLinks } from "../../../src/lib/editor/documentLinks.ts";
import { tableLinkLabelPosition } from "../../../src/lib/editor/tableLinkSource.ts";
test("table link reveal retains the clicked character through Markdown label marks", () => {
for (const [source, offset, prefix] of [
["[Roadmap](docs/roadmap.md)", 5, "[Roadm"],
['**Prefix** [One](same.md) + [Sec**ond**](same.md "Title")', 4, '**Prefix** [One](same.md) + [Sec**o'],
["[A \\*star](note.md)", 3, "[A \\*"],
["[Use `code`](note.md)", 5, "[Use `c"],
["<https://example.org>", 8, "<https://"],
] as const) {
const link = documentLinks(source).at(-1)!;
assert.equal(source.slice(0, tableLinkLabelPosition(source, link, offset)), prefix);
}
});
test("table wiki links retain literal label text, aliases, spaces, and escaped pipes", () => {
for (const [source, offset, prefix] of [
["[[guide\\|Guide]]", 3, "[[guide\\|Gui"],
["[[guide\\|**Alias**]]", 2, "[[guide\\|**"],
["[[ Guide ]]", 3, "[[ G"],
["[[Guide\\|]]", 2, "[[Gu"],
["[[guide\\|A\\|B]]", 2, "[[guide\\|A\\|"],
] as const) {
const link = documentLinks(source)[0];
assert.equal(source.slice(0, tableLinkLabelPosition(source, link, offset)), prefix);
}
});
@@ -0,0 +1,16 @@
import test from "node:test";
import assert from "node:assert/strict";
import { workspaceFileLink } from "../../../src/lib/editor/workspaceFileLink.ts";
import { wordAt } from "../../../src/lib/editor/spellingWord.ts";
test("file links resolve across nested folders and escape Markdown punctuation", () => {
assert.equal(workspaceFileLink("notes/deep/source.md", "docs/a [draft](1).pdf"), "[a \\[draft\\](1).pdf](../../docs/a%20%5Bdraft%5D%281%29.pdf)");
assert.equal(workspaceFileLink("notes/source.md", "notes/target.md"), "[target.md](target.md)");
assert.equal(workspaceFileLink("notes/source.md", "assets/pic.png"), "![](../assets/pic.png)");
});
test("spelling finds Unicode words and apostrophes without including punctuation", () => {
assert.deepEqual(wordAt("A naïve word.", 5), { word: "naïve", from: 2, to: 7 });
assert.equal(wordAt("Don't stop", 3)?.word, "Don't");
assert.equal(wordAt("word next", 5), null);
});
+35
View File
@@ -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();
});
+138
View File
@@ -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/);
});
+85
View File
@@ -0,0 +1,85 @@
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.equal(pluginAccess("org.example.test", [], [view("settings")])[0].surface, "open");
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings", { settings: false })])[0].surface, "open");
});
test("the browser ID gets the same access rules as any other owner", () => {
// The built-in browser sets `category` and `launcher` itself. The old Browser package had no special rules left.
assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab")], [view("tab-123")]).map(({ id, surface }) => [id, surface]), [["new-tab", "commands"], ["tab-123", "open"]]);
assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab", { category: "open", icon: "globe" })], [view("tab-123", { launcher: false })]).map(({ id, surface, icon }) => [id, surface, icon]), [["new-tab", "open", "globe"]]);
});
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,44 @@
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("file access stops before plugin cleanup, and plugins get no Git API", async () => {
const calls: unknown[] = [];
let api!: PluginApi;
const session = new ExternalSession("test.files", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
openFile: async path => { calls.push(path); },
}, () => {}, () => {}, new ContributionRegistry());
await session.start({ activate(value) { api = value; } });
// Git is a native feature of RuneStone. The plugin API has no Git member.
assert.equal("git" in api, false);
await api.openFile!("notes.md");
assert.deepEqual(calls, ["notes.md"]);
await session.stop();
assert.throws(() => api.openFile!("notes.md"), /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,80 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts";
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
import { ServiceHub } from "../../../src/lib/plugins/services.ts";
import type { FilesTransport, PluginApi } from "../../../src/lib/plugins/sdk.ts";
const base: SessionServices = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
};
async function start(id: string, services: Partial<SessionServices>) {
let api!: PluginApi;
const session = new ExternalSession(id, { ...base, ...services }, () => {}, () => {}, new ContributionRegistry());
await session.start({ activate(value) { api = value; } });
return { api, session };
}
test("folder grant calls check shutdown before and after the native request", async () => {
const calls: unknown[][] = [];
let finish: ((value: unknown) => void) | undefined;
const grant = { id: "7f1b6f6e-3c39-4b55-9f3e-4a3a6d1d7c11", path: "C:/Pictures/RuneStone Backgrounds", name: "RuneStone Backgrounds" };
const files: FilesTransport = {
chooseFolder: async options => { calls.push(["choose", options]); return grant; },
pictureFolder: async name => { calls.push(["picture", name]); return grant; },
grants: async () => [grant],
revoke: async id => { calls.push(["revoke", id]); return true; },
list: () => new Promise(resolve => { finish = resolve as (value: unknown) => void; }),
readBytes: async (id, name) => { calls.push(["read", id, name]); return new Uint8Array([1, 2]); },
readSidecar: async () => null,
writeSidecar: async (id, name, contents, expected) => { calls.push(["write", id, name, contents, expected]); },
};
const { api, session } = await start("org.test.slides", { files });
assert.deepEqual(await api.files!.chooseFolder({ title: "Images" }), grant);
assert.deepEqual(await api.files!.pictureFolder("Backgrounds"), grant);
assert.deepEqual(await api.files!.readBytes(grant.id, "a.png"), new Uint8Array([1, 2]));
await api.files!.writeSidecar(grant.id, ".runestone-backgrounds.json", "{}", null);
assert.equal(await api.files!.revoke(grant.id), true);
assert.deepEqual(calls, [["choose", { title: "Images" }], ["picture", "Backgrounds"], ["read", grant.id, "a.png"], ["write", grant.id, ".runestone-backgrounds.json", "{}", null], ["revoke", grant.id]]);
assert.throws(() => api.files!.readBytes("", "a.png"), /grant ID/);
assert.throws(() => api.files!.writeSidecar(grant.id, ".runestone-a.json", "{}", undefined as never), /expected/);
const pending = api.files!.list(grant.id);
await session.stop();
finish!([{ name: "a.png", size: 2 }]);
await assert.rejects(pending, /disabled/);
assert.throws(() => api.files!.grants(), /disabled/);
});
test("plugin services copy data, stop with their provider, and stop for a stopped consumer", async () => {
const serviceHub = new ServiceHub();
const boards = [{ id: "b1", name: "Roadmap" }];
const provider = await start("org.test.boards", { serviceHub });
const consumer = await start("org.test.slides", { serviceHub });
const changes: string[] = [];
consumer.api.services!.subscribe((plugin, name) => changes.push(`${plugin}/${name}`));
assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null);
const handle = provider.api.services!.provide("boards", { list: () => boards });
assert.throws(() => provider.api.services!.provide("boards", { list: () => boards }), /already/);
assert.throws(() => provider.api.services!.provide("Bad Name", { list: () => boards }), /service name/);
const service = consumer.api.services!.get("org.test.boards", "boards")!;
const result = await service.list() as typeof boards;
assert.deepEqual(result, boards);
result[0].name = "Changed";
assert.equal(boards[0].name, "Roadmap", "the consumer receives a copy");
handle.notify();
assert.deepEqual(changes, ["org.test.boards/boards", "org.test.boards/boards"]);
await provider.session.stop();
assert.deepEqual(changes.at(-1), "org.test.boards/boards");
await assert.rejects(service.list(), /no longer available/);
assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null);
const again = await start("org.test.boards", { serviceHub });
again.api.services!.provide("boards", { list: () => boards });
const fresh = consumer.api.services!.get("org.test.boards", "boards")!;
await consumer.session.stop();
await assert.rejects(fresh.list(), /disabled/);
const count = changes.length;
await again.session.stop();
assert.equal(changes.length, count, "a stopped consumer receives no notifications");
});
@@ -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 });
}
});
+87
View File
@@ -0,0 +1,87 @@
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 type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
import type { Contributions } from "../../../src/lib/plugins/contracts.ts";
// A small test-only package. It contributes the browser, as the built-in browser module does.
const browser: Contributions["browser"] = { mountSettings: () => () => {}, mountBookmarks: () => () => {}, open: async () => false };
const activate = (api: PluginApi) => { api.contribute("browser", browser); };
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 package contributions end with their session", async () => {
assert.equal(pluginHost.get("browser"), undefined);
const registry = new ContributionRegistry();
const session = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
await session.start({ activate });
assert.equal(registry.get("browser"), browser);
await session.stop();
assert.equal(registry.get("browser"), undefined);
const next = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
await next.start({ activate });
assert.equal(registry.get("browser"), browser);
await next.stop();
assert.equal(registry.get("browser"), undefined);
});
test("unknown contribution keys are rejected", () => {
const registry = new ContributionRegistry();
// `terminal` was a contribution until the Terminal feature became native.
for (const key of ["tableFormulas", "git", "terminal"]) assert.throws(() => registry.register("old", key as keyof Contributions, browser as never), /Unknown plugin contribution/);
});
test("package contribution conflicts preserve the first owner and revoke access before cleanup", 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("browser");
await assert.rejects(second.start({ activate }), /already registered/);
await second.stop();
assert.equal(registry.get("browser"), contribution);
api.onDispose(() => {
assert.equal(registry.get("browser"), undefined);
assert.throws(() => api.contribute("browser", contribution!), /disabled/);
});
await first.stop();
});
test("partial activation and failed cleanup cannot retain feature contributions", 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("browser"), undefined);
});
@@ -0,0 +1,26 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
type Capability = { windows: string[]; permissions: string[] };
const read = (file: string): string => readFileSync(new URL(`../../../${file}`, import.meta.url), "utf8");
const capability = (name: string): Capability => JSON.parse(read(`src-tauri/capabilities/${name}.json`));
test("browser windows have their own capability, a subset of the main window commands", () => {
const browser = capability("browser"), main = capability("default"), settings = capability("settings");
assert.deepEqual(browser.windows, ["browser-*"]);
for (const other of [main, settings]) assert(!other.windows.some(pattern => pattern.startsWith("browser")), "Only browser.json matches browser windows.");
const extra = browser.permissions.filter(permission => !main.permissions.includes(permission));
assert.deepEqual(extra, [], "browser.json grants only permissions that default.json also grants.");
// Browser windows run no installed plugin, so they need no workspace, file, plugin package, terminal, or Git access.
const denied = browser.permissions.filter(permission => /^allow-(workspace|git|pty|backgrounds|tab-transfer|completion|theme|settings-open)-|^allow-plugins-(?!snapshot$)|^(opener|dialog):/.test(permission));
assert.deepEqual(denied, []);
});
test("browser windows start only the built-in browser", () => {
// The capability split depends on this: a browser window never loads an installed plugin.
assert.match(read("src/routes/+page.svelte"), /startExternalPlugins\(\{ browserWindow \}\)/);
assert.match(read("src/lib/plugins/external.ts"), /if \(builtInPackages\.includes\(id\) \|\| browserWindow\) continue;/);
assert.match(read("src/lib/plugins/external.ts"), /if \(browserWindow && !builtIn\.browserWindow\) continue;/);
assert.match(read("src-tauri/src/browser.rs"), /let label = format!\("browser-\{\}", uuid::Uuid::new_v4\(\)\);/);
});
@@ -0,0 +1,127 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm, access } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import zlib from 'node:zlib';
import { createHash } from 'node:crypto';
import { buildCommands, describePlan, engineFiles, parseArguments, planEngineBuild, platformKey, runEngineBuild, zipFolder } from '../../../scripts/buildBrowserEngine.mjs';
const repository = path.resolve('.');
const exists = (file: string) => access(file).then(() => true, () => false);
const releaseUrl = 'https://example.com/releases/download/browser-engine';
const windows = { platform: 'win32', arch: 'x64' };
// A copy of the files that the engine script reads.
async function withFixture(body: (root: string, before: string[]) => Promise<void>) {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-engine-build-'));
try {
for (const file of [...engineFiles, 'src-tauri/src/browser_engine.rs', 'browser-runtime/src/engine-main.mjs']) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await copyFile(path.join(repository, file), path.join(root, file));
}
await body(root, await Promise.all(engineFiles.map(file => readFile(path.join(root, file), 'utf8'))));
} finally { await rm(root, { recursive: true, force: true }); }
}
const contents = (root: string) => Promise.all(engineFiles.map(file => readFile(path.join(root, file), 'utf8')));
/** The names and contents of a ZIP, read from its central directory. */
function unzip(archive: Buffer) {
const end = archive.length - 22;
assert.equal(archive.readUInt32LE(end), 0x06054b50);
const count = archive.readUInt16LE(end + 10);
let at = archive.readUInt32LE(end + 16);
const entries: { name: string, data: Buffer, mode: number }[] = [];
for (let i = 0; i < count; i++) {
assert.equal(archive.readUInt32LE(at), 0x02014b50);
const method = archive.readUInt16LE(at + 10), crc = archive.readUInt32LE(at + 16), size = archive.readUInt32LE(at + 20);
const nameLength = archive.readUInt16LE(at + 28), mode = archive.readUInt32LE(at + 38) >>> 16, offset = archive.readUInt32LE(at + 42);
const name = archive.subarray(at + 46, at + 46 + nameLength).toString('utf8');
const start = offset + 30 + archive.readUInt16LE(offset + 26) + archive.readUInt16LE(offset + 28);
const body = archive.subarray(start, start + size);
const data = method === 8 ? zlib.inflateRawSync(body) : Buffer.from(body);
assert.equal(zlib.crc32(data), crc, name);
entries.push({ name, data, mode });
at += 46 + nameLength;
}
return entries;
}
test('the engine script reads its options and maps platform keys', () => {
assert.deepEqual(parseArguments(['--release-url', releaseUrl]), { version: undefined, releaseUrl, dryRun: false });
assert.deepEqual(parseArguments(['--dry-run', '--version', '0.1.8', '--release-url', releaseUrl]), { version: '0.1.8', releaseUrl, dryRun: true });
for (const args of [[], ['--version', '0.1.8'], ['--release-url'], ['--release-url', releaseUrl, '--release-url', releaseUrl], ['--force']]) assert.throws(() => parseArguments(args));
assert.equal(platformKey('win32', 'x64'), 'windows-x86_64');
assert.equal(platformKey('linux', 'arm64'), 'linux-aarch64');
assert.equal(platformKey('darwin', 'arm64'), 'macos-aarch64');
assert.throws(() => platformKey('aix', 'x64'));
});
test('planning checks the URL, the protocol, and existing releases, and changes no file', () => withFixture(async (root, before) => {
const plan = await planEngineBuild(root, { version: '0.1.8', releaseUrl }, windows);
assert.deepEqual(await contents(root), before);
assert.equal(plan.file, 'RuneStone-Browser_0.1.8_win32-x64.zip');
assert.equal(plan.url, `${releaseUrl}/RuneStone-Browser_0.1.8_win32-x64.zip`);
assert.equal(plan.key, 'windows-x86_64');
assert.match(describePlan(plan), /Pin https:\/\/example\.com\/.*0\.1\.8_win32-x64\.zip in src-tauri\/browser-engine\.json/);
assert.match(buildCommands(plan)[0].args.join(' '), /browser-runtime[\\/]scripts[\\/]package\.mjs --platform=win32 --arch=x64/);
for (const url of ['http://example.com/engine', 'https://user:[email protected]/engine', 'https://example.com/engine?token=1']) {
await assert.rejects(planEngineBuild(root, { version: '0.1.8', releaseUrl: url }, windows), /HTTPS/);
}
await assert.rejects(planEngineBuild(root, { version: '0.1', releaseUrl }, windows), /release version/);
await mkdir(path.dirname(plan.artifacts.archive), { recursive: true });
await writeFile(plan.artifacts.archive, 'old');
await assert.rejects(planEngineBuild(root, { version: '0.1.8', releaseUrl }, windows), /already exists/);
const main = path.join(root, 'browser-runtime/src/engine-main.mjs');
await writeFile(main, (await readFile(main, 'utf8')).replace("event: 'ready', protocol: 1", "event: 'ready', protocol: 2"));
await assert.rejects(planEngineBuild(root, { version: '0.1.9', releaseUrl }, windows), /protocol/);
}));
test('the engine ZIP holds the files at its root, in name order, with the same bytes each time', async () => {
const folder = await mkdtemp(path.join(tmpdir(), 'runestone-engine-zip-'));
try {
await mkdir(path.join(folder, 'locales'), { recursive: true });
await mkdir(path.join(folder, 'resources'), { recursive: true });
await writeFile(path.join(folder, 'RuneStone-Browser.exe'), Buffer.alloc(4096, 7));
await writeFile(path.join(folder, 'locales', 'en-US.pak'), 'strings '.repeat(200));
await writeFile(path.join(folder, 'resources', 'app.asar'), createHash('sha256').update('random').digest());
const first = await zipFolder(folder);
assert.deepEqual(first, await zipFolder(folder));
const entries = unzip(first);
assert.deepEqual(entries.map(entry => entry.name), ['RuneStone-Browser.exe', 'locales/en-US.pak', 'resources/app.asar']);
assert.deepEqual(entries[1].data, Buffer.from('strings '.repeat(200)));
assert.equal(entries[0].mode & 0o170000, 0o100000, 'Each entry is a regular file.');
} finally { await rm(folder, { recursive: true, force: true }); }
});
test('a completed build writes the ZIP, its record, and the pin', () => withFixture(async (root, before) => {
const plan = await planEngineBuild(root, { version: '0.1.8', releaseUrl }, windows);
const versions: string[] = [];
const result = await runEngineBuild(plan, async () => {
versions.push(JSON.parse(await readFile(path.join(root, engineFiles[0]), 'utf8')).version);
await mkdir(plan.dist, { recursive: true });
await writeFile(path.join(plan.dist, 'RuneStone-Browser.exe'), 'engine');
}, path.join(root, 'output/attempt'));
assert.deepEqual(versions, ['0.1.8'], 'The package step sees the new version.');
const archive = await readFile(plan.artifacts.archive);
const sha256 = createHash('sha256').update(archive).digest('hex');
assert.equal(result.sha256, sha256);
assert.deepEqual(JSON.parse(await readFile(plan.artifacts.metadata, 'utf8')), { version: '0.1.8', protocol: plan.protocol, platform: 'windows-x86_64', file: plan.file, url: plan.url, bytes: archive.length, sha256 });
assert.deepEqual(JSON.parse(await readFile(path.join(root, engineFiles[2]), 'utf8')), { version: '0.1.8', protocol: plan.protocol, platforms: { 'windows-x86_64': { url: plan.url, bytes: archive.length, sha256 } } });
const lock = JSON.parse(await readFile(path.join(root, engineFiles[1]), 'utf8'));
assert.equal(lock.version, '0.1.8');
assert.equal(lock.packages[''].version, '0.1.8');
assert.notDeepEqual(await contents(root), before);
}));
test('a failed build restores the version fields and the pin', () => withFixture(async (root, before) => {
const plan = await planEngineBuild(root, { version: '0.1.8', releaseUrl }, windows);
const staging = path.join(root, 'output/attempt');
await assert.rejects(runEngineBuild(plan, async () => { throw Error('packager failed'); }, staging), /packager failed/);
assert.deepEqual(await contents(root), before);
assert.equal(await exists(plan.artifacts.archive), false);
// The package step completes, but the program is missing.
await assert.rejects(runEngineBuild(plan, async () => { await mkdir(plan.dist, { recursive: true }); }, staging), /no engine program/);
assert.deepEqual(await contents(root), before);
assert.equal(await exists(plan.artifacts.metadata), false);
}));
+131
View File
@@ -0,0 +1,131 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, writeFile, copyFile, readdir, rm, access } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { buildCommands, describePlan, parseArguments, planInstallerBuild, runInstallerBuild, versionFiles } from '../../../scripts/buildInstaller.mjs';
import { nextHotfix, releaseVersion } from '../../../scripts/releaseVersion.mjs';
const repository = path.resolve('.');
const exists = (file: string) => access(file).then(() => true, () => false);
// A copy of the files that the installer script reads.
async function fixture() {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-build-'));
for (const file of [...versionFiles, 'src-tauri/tauri.windows.conf.json', 'src-tauri/windows/hooks.nsh']) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await copyFile(path.join(repository, file), path.join(root, file));
}
const before = await Promise.all(versionFiles.map(file => readFile(path.join(root, file), 'utf8')));
const current = releaseVersion(JSON.parse(before[0]).version);
return { root, before, current, next: releaseVersion(nextHotfix(current.version)) };
}
const contents = (root: string) => Promise.all(versionFiles.map(file => readFile(path.join(root, file), 'utf8')));
async function withFixture(body: (setup: Awaited<ReturnType<typeof fixture>>) => Promise<void>) {
const setup = await fixture();
try { await body(setup); } finally { await rm(setup.root, { recursive: true, force: true }); }
}
test('the installer script reads --version and --dry-run', () => {
assert.deepEqual(parseArguments([]), { version: undefined, dryRun: false });
assert.deepEqual(parseArguments(['--version', '0.1.44a', '--dry-run']), { version: '0.1.44a', dryRun: true });
assert.deepEqual(parseArguments(['--dry-run', '--version', '0.1.45']), { version: '0.1.45', dryRun: true });
for (const args of [['--version'], ['0.1.45'], ['--version', '0.1.45', '--version', '0.1.46'], ['--force']]) assert.throws(() => parseArguments(args));
});
test('a completed build sets the version fields only after the installer exists', () => withFixture(async ({ root, before, next }) => {
const plan = await planInstallerBuild(root, next.version);
assert.deepEqual(await contents(root), before, 'Planning must not change a file.');
assert.deepEqual(plan.override, { version: next.toolchain });
const plain = describePlan(plan);
assert.match(plain, new RegExp(`Configuration override: \\{"version":"${next.toolchain.replace('+', '\\+')}"\\}`));
assert.match(plain, /compile: .* build --no-bundle --config .* -- --locked/);
const staging = path.join(root, 'output/attempt');
const overridePath = path.join(staging, 'tauri.version.json');
const calls: { command: string, args: string[], files: string[] }[] = [];
const installer = await runInstallerBuild(plan, async (command: string, args: string[]) => {
calls.push({ command, args, files: await contents(root) });
if (args.includes('bundle')) {
assert.deepEqual(JSON.parse(await readFile(overridePath, 'utf8')), { version: next.toolchain });
await mkdir(path.dirname(plan.artifacts.bundled), { recursive: true });
await writeFile(plan.artifacts.bundled, 'setup');
}
}, staging);
assert.deepEqual(calls.map(({ command, args }) => ({ command, args })),
buildCommands(plan, overridePath).map(({ command, args }) => ({ command, args })));
for (const call of calls) {
// Tauri, Cargo, and the bundler get the version from the override. The front end gets it from plan.env.
assert.deepEqual(call.files, before, 'No version file changes during the build.');
assert.deepEqual(plan.env, { RUNESTONE_VERSION: next.version });
}
assert.equal(installer, path.join(root, 'releases', next.version, `RuneStone_${next.version}_x64-setup.exe`));
assert.equal(await readFile(installer, 'utf8'), 'setup');
assert.equal(await exists(plan.artifacts.bundled), false);
assert.equal(await exists(plan.artifacts.renamed), false);
const metadata = JSON.parse(await readFile(plan.artifacts.metadata, 'utf8'));
assert.deepEqual([metadata.version, metadata.toolchainVersion, metadata.windowsVersion, metadata.bytes], [next.version, next.toolchain, next.windows, 5]);
const after = await contents(root);
assert.deepEqual(after, plan.updated);
assert.equal(JSON.parse(after[0]).version, next.version);
assert.equal(JSON.parse(after[1]).version, next.toolchain);
assert.match(after[2], new RegExp(`^version = "${next.toolchain.replace('+', '\\+')}"`, 'm'));
assert.match(after[2], new RegExp(`\\[package\\.metadata\\.runestone\\]\\r?\\nversion = "${next.version}"`));
assert.match(after[3], new RegExp(`name = "runestone"\\r?\\nversion = "${next.toolchain.replace('+', '\\+')}"`));
}));
test('a failed build leaves the version fields unchanged', () => withFixture(async ({ root, before, next }) => {
for (const failure of ['compile', 'version-resource', 'bundle', 'missing setup file', 'oversized setup file']) {
const plan = await planInstallerBuild(root, next.version);
if (failure === 'oversized setup file') plan.maxSetupBytes = 4;
const staging = path.join(root, 'output', failure.replaceAll(' ', '-'));
const steps = buildCommands(plan, path.join(staging, 'tauri.version.json'));
let index = 0;
const attempt = runInstallerBuild(plan, async () => {
const step = steps[index++].step;
if (step === failure) throw Error('The build command failed with exit code 1');
// A setup file over the size limit, as with a bundled browser engine.
if (step === 'bundle' && failure === 'oversized setup file') {
await mkdir(path.dirname(plan.artifacts.bundled), { recursive: true });
await writeFile(plan.artifacts.bundled, 'setup');
}
}, staging);
await assert.rejects(attempt, failure === 'oversized setup file' ? /more than the limit/ : Error);
assert.deepEqual(await contents(root), before, 'A failure during ' + failure + ' must restore the version fields.');
assert.equal(await exists(plan.artifacts.release), false);
assert.equal(await exists(plan.artifacts.metadata), false);
assert.ok((await readdir(staging)).includes('package.json.before'));
}
}));
test('the plan stops before a build that breaks the release rules', () => withFixture(async ({ root, before, current, next }) => {
const tauriConfig = path.join(root, 'src-tauri/tauri.conf.json');
const windowsConfig = path.join(root, 'src-tauri/tauri.windows.conf.json');
const windowsBefore = await readFile(windowsConfig, 'utf8');
await assert.rejects(planInstallerBuild(root, '0.1.44-rc1'), /release version such as/);
await writeFile(tauriConfig, before[1].replace(`"version": "${current.toolchain}"`, '"version": "9.9.9"'));
await assert.rejects(planInstallerBuild(root, next.version), /do not match/);
await writeFile(tauriConfig, before[1]);
const windows = JSON.parse(windowsBefore);
windows.bundle.windows.allowDowngrades = true;
await writeFile(windowsConfig, JSON.stringify(windows));
await assert.rejects(planInstallerBuild(root, next.version), /Downgrade protection/);
windows.bundle.windows.allowDowngrades = false;
delete windows.bundle.windows.nsis.installerHooks;
await writeFile(windowsConfig, JSON.stringify(windows));
await assert.rejects(planInstallerBuild(root, next.version), /installer hooks/);
await writeFile(windowsConfig, windowsBefore);
const plan = await planInstallerBuild(root, next.version);
await mkdir(plan.releaseDir, { recursive: true });
await writeFile(plan.artifacts.release, 'existing');
await assert.rejects(planInstallerBuild(root, next.version), /already exists/);
await rm(plan.releaseDir, { recursive: true });
// The browser engine is a separate download. The installer must not bundle it.
const config = JSON.parse(before[1]);
config.bundle.resources = { 'browser-engine/': 'browser-engine/' };
await writeFile(tauriConfig, JSON.stringify(config));
await assert.rejects(planInstallerBuild(root, next.version), /must not bundle the browser engine/);
await writeFile(tauriConfig, before[1]);
assert.deepEqual(await contents(root), before);
}));
+41
View File
@@ -0,0 +1,41 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { checkChunks, featureModule, staticClosure } from "../../../scripts/featureChunks.mjs";
const root = "D:/RuneStone/";
const chunk = (fileName: string, fields: Record<string, unknown> = {}) => ({ fileName, isEntry: false, isDynamicEntry: false, facadeModuleId: null, imports: [], moduleIds: [], size: 10, ...fields });
test("the static closure follows imports from each entry, and not dynamic imports", () => {
const chunks = [
chunk("app.js", { isEntry: true, imports: ["shared.js"] }),
chunk("node.js", { isEntry: true }),
chunk("shared.js", { imports: ["deep.js"] }),
chunk("deep.js"),
chunk("git.js", { isDynamicEntry: true, imports: ["shared.js"] }),
];
assert.deepEqual([...staticClosure(chunks)].sort(), ["app.js", "deep.js", "node.js", "shared.js"]);
});
test("feature folders and feature libraries count as feature modules, and the runtime does not", () => {
assert.equal(featureModule(`${root}src/lib/features/git/index.ts`), true);
assert.equal(featureModule("D:\\RuneStone\\src\\lib\\features\\git\\model.ts"), true);
assert.equal(featureModule(`${root}src/lib/features/catalog.ts`), false);
assert.equal(featureModule(`${root}node_modules/.pnpm/@[email protected]/node_modules/@xterm/xterm/lib/xterm.mjs`), true);
assert.equal(featureModule(`${root}node_modules/pdfjs-dist/build/pdf.mjs`), true);
assert.equal(featureModule(`${root}node_modules/svelte/src/index.js`), false);
});
test("a feature module in a start chunk fails, and a separate dynamic chunk passes", () => {
const good = [
chunk("app.js", { isEntry: true, moduleIds: [`${root}src/lib/features/catalog.ts`] }),
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts`, moduleIds: [`${root}src/lib/features/git/index.ts`], size: 2048 }),
];
assert.deepEqual(checkChunks(good, ["git"]), { problems: [], sizes: { git: 2048 } });
const bad = [
chunk("app.js", { isEntry: true, imports: ["shared.js"] }),
chunk("shared.js", { moduleIds: [`${root}src/lib/features/git/model.ts`] }),
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts` }),
];
assert.deepEqual(checkChunks(bad, ["git"]).problems, ["shared.js loads at start and contains src/lib/features/git/model.ts"]);
assert.deepEqual(checkChunks([chunk("app.js", { isEntry: true })], ["git"]).problems, ["No chunk starts at src/lib/features/git/index.ts."]);
});
+309
View File
@@ -0,0 +1,309 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm } from 'node:fs/promises';
import { existsSync, readFileSync, realpathSync } from 'node:fs';
import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { releaseVersion, nextHotfix, compareReleases } from '../../../scripts/releaseVersion.mjs';
const ordering = ['0.1.22z', '0.1.23', '0.1.23a', '0.1.23b', '0.1.23c', '0.1.23z', '0.1.23aa', '0.1.23ab', '0.1.23zz', '0.1.23aaa', '0.1.24'];
const hooks = path.resolve('src-tauri/windows/hooks.nsh');
test('hotfix versions retain their release identity and advance in letter order', () => {
assert.deepEqual(releaseVersion('0.1.23a'), { version: '0.1.23a', base: '0.1.23', suffix: 'a', revision: 1, toolchain: '0.1.23+1', windows: '0.1.23.1' });
for (const [before, after] of [['0.1.23', '0.1.23a'], ['0.1.23a', '0.1.23b'], ['0.1.23b', '0.1.23c'], ['0.1.23z', '0.1.23aa'], ['0.1.23aa', '0.1.23ab'], ['0.1.23zz', '0.1.23aaa']]) assert.equal(nextHotfix(before), after);
for (const version of ['0.1.23A', '0.1.23a1', '0.1.23-a', '0.1.23+1', '0.1', '0.1.23aaaaa', '0.1.65536']) assert.throws(() => releaseVersion(version));
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) assert.equal(compareReleases(ordering[i], ordering[j]), Math.sign(i - j));
});
test('the Windows configuration uses the RuneStone hooks with the stock template', async () => {
const config = JSON.parse(await readFile('src-tauri/tauri.conf.json', 'utf8'));
const windows = JSON.parse(await readFile('src-tauri/tauri.windows.conf.json', 'utf8')).bundle.windows;
assert.equal(windows.allowDowngrades, false);
assert.equal(windows.nsis.template, undefined, 'Use the stock Tauri template. Put RuneStone behavior in the hooks.');
assert.equal(path.resolve('src-tauri', windows.nsis.installerHooks), hooks);
// The hooks read SHCTX as HKCU and use the uninstall key of the product name.
assert.equal(windows.nsis.installMode, 'currentUser');
const source = await readFile(hooks, 'utf8');
assert.ok(source.includes(`!define /ifndef RUNESTONE_UNINSTKEY "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${config.productName}"`));
});
// The Tauri CLI embeds its NSIS template. These checks fail when a Tauri update changes what the hooks rely on.
function stockTemplate() {
const cli = createRequire(realpathSync('node_modules/@tauri-apps/cli/package.json'));
let binary: string;
try { binary = cli.resolve('@tauri-apps/cli-win32-x64-msvc'); } catch { return null; }
const bytes = readFileSync(binary);
const start = bytes.indexOf('Unicode true\r\nManifestDPIAware true');
assert.ok(start >= 0, 'The Tauri CLI no longer contains the expected NSIS template.');
let end = start;
while (end < bytes.length && (bytes[end] === 9 || bytes[end] === 10 || bytes[end] === 13 || (bytes[end] >= 32 && bytes[end] < 127))) end++;
return bytes.subarray(start, end).toString('latin1').replaceAll('\r\n', '\n');
}
const template = process.platform === 'win32' ? stockTemplate() : null;
test('the stock Tauri template still provides what the hooks rely on', { skip: template ? false : 'needs the Windows Tauri CLI' }, () => {
const text = template!;
const at = (fragment: string) => {
const index = text.indexOf(fragment);
assert.ok(index >= 0, 'The stock template no longer contains: ' + fragment);
return index;
};
// NSIS_HOOK_POSTUNINSTALL removes the downloaded engine. It needs ${BUNDLEID}, $UpdateMode, and its place after the app data step.
const removal = at('RmDir /r "$LOCALAPPDATA\\${BUNDLEID}"');
assert.ok(text.indexOf('${AndIf} $UpdateMode <> 1') < removal);
assert.ok(removal < at('!insertmacro NSIS_HOOK_POSTUNINSTALL'), 'The uninstall hook must run after the app data step.');
const include = at('!include "{{installer_hooks}}"');
assert.ok(include < at('!insertmacro MUI_PAGE_WELCOME'), 'Tauri must include the hooks before the first page.');
assert.ok(include < at('\nSection EarlyChecks'), 'Tauri must include the hooks before its first section.');
assert.ok(include < at('\nVar '), 'The hooks file cannot use the template variables.');
at('!define UNINSTKEY "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${PRODUCTNAME}"');
// RuneStoneInstallerVersion reads the version resource.
at('VIProductVersion "${VERSIONWITHBUILD}"');
assert.ok(!text.includes('VIFileVersion'));
assert.ok(!text.includes('MUI_CUSTOMFUNCTION_GUIINIT') && !text.includes('.onGUIInit'), 'The hooks define the GUI initialization function.');
// RuneStoneGuiInit makes the maintenance page skip itself. That page must look for the installation in SHCTX.
const page = text.slice(at('Function PageReinstall\n'), at('Function PageReinstallUpdateSelection'));
for (const line of ['ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""', 'ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"', '${IfThen} "$R0$R1" == "" ${|} Abort ${|}']) {
assert.ok(page.includes(line), 'PageReinstall no longer contains: ' + line);
}
// No installer code may change the context between RuneStoneGuiInit and the RuneStoneVersionCheck section.
const install = text.slice(0, at('Function un.onInit'));
assert.ok(!install.includes('SetShellVarContext'), 'The installer part of the template now changes the shell context.');
assert.ok(text.slice(at('Function .onInit'), at('Section EarlyChecks')).includes('!insertmacro SetContext'));
const section = text.slice(at('Section Install\n'), at('Function .onInstSuccess'));
assert.ok(section.indexOf('"DisplayVersion" "${VERSION}"') >= 0);
assert.ok(section.indexOf('"DisplayVersion" "${VERSION}"') < section.indexOf('!insertmacro NSIS_HOOK_POSTINSTALL'), 'The hook must write DisplayVersion after the template.');
});
const makensis = path.join(process.env.LOCALAPPDATA ?? '', 'tauri/NSIS/makensis.exe');
const nsisSkip = process.platform !== 'win32' ? 'Windows only' : existsSync(makensis) ? false : 'the NSIS compiler is missing; Tauri downloads it during the first installer build';
function compile(script: string, source: string) {
const built = spawnSync(makensis, ['/V2', script], { input: undefined, encoding: 'utf8', windowsHide: true });
assert.equal(built.status, 0, source + '\n' + built.stdout + built.stderr);
}
test('the hook functions convert versions in release order', { skip: nsisSkip }, async () => {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-version-'));
try {
const results = path.join(root, 'results.txt');
const valid = new Map<string, string>([['65535.0.0.65535', '65535.0.0.65535'], ['0.1.23', '0.1.23.0']]);
for (const version of ordering) {
const { toolchain, windows } = releaseVersion(version);
valid.set(toolchain, windows);
valid.set(windows, windows);
}
const invalid = ['', '0.1.23a', '0.1.23A', '0.1.23-rc', '0.1', '0.1.', '.1.2', '1..2.3', '0.1.23+', '0.1.23+1.2', '1.2+3',
'0.1.23.1.0', '0.1.65536', '0.1.23+65536', '0.1.23.65536', 'garbage', ' 0.1.23', '0.1.23 ', '0x1.2.3'];
const lines = ['FileOpen $9 "' + results + '" w'];
for (const input of [...valid.keys(), ...invalid]) lines.push(`Push "${input}"`, 'Call RuneStoneNumericVersion', 'Pop $0', `FileWrite $9 "numeric|${input}|$0$\\n"`);
for (const version of ordering) lines.push(`Push "${releaseVersion(version).windows}"`, 'Call RuneStoneReleaseName', 'Pop $0', `FileWrite $9 "release|${version}|$0$\\n"`);
for (const left of ordering) for (const right of ordering) {
lines.push(`\${VersionCompare} "${releaseVersion(left).windows}" "${releaseVersion(right).windows}" $0`, `FileWrite $9 "compare|${left}|${right}|$0$\\n"`);
}
lines.push('FileClose $9');
const executable = path.join(root, 'functions.exe');
const script = path.join(root, 'functions.nsi');
const source = `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone hook functions"\nOutFile "${executable}"\n` +
`!define RUNESTONE_UNINSTKEY "Software\\RuneStoneInstallerTest-${path.basename(root)}"\n!include "${hooks}"\nSection\n${lines.join('\n')}\nSectionEnd\n`;
await writeFile(script, source);
compile(script, source);
const checked = spawnSync(executable, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
assert.equal(checked.status, 0);
const output = (await readFile(results, 'utf8')).trim().split('\n').map(line => line.split('|'));
const numeric = new Map(output.filter(row => row[0] === 'numeric').map(row => [row[1], row[2]]));
for (const [input, expected] of valid) assert.equal(numeric.get(input), expected, 'RuneStoneNumericVersion ' + input);
for (const input of invalid) assert.equal(numeric.get(input), '', 'RuneStoneNumericVersion must reject ' + JSON.stringify(input));
for (const row of output.filter(row => row[0] === 'release')) assert.equal(row[2], row[1], 'RuneStoneReleaseName ' + row[1]);
for (const [, left, right, result] of output.filter(row => row[0] === 'compare')) {
// VersionCompare returns 0 for equal versions, 1 when the first is newer, and 2 when the second is newer.
assert.equal(result, String([0, 1, 2].at(compareReleases(left, right))), `VersionCompare ${left} ${right}`);
}
assert.equal(output.filter(row => row[0] === 'compare').length, ordering.length ** 2);
// Tauri cannot write a letter suffix into the version strings of the app executable.
const patchedExe = path.join(root, 'patched.exe');
await copyFile(executable, patchedExe);
const patched = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.resolve('scripts/setWindowsVersion.ps1'), '-Path', patchedExe, '-Version', '0.1.23a', '-NumericVersion', '0.1.23.1'], { encoding: 'utf8', windowsHide: true });
assert.equal(patched.status, 0, patched.stdout + patched.stderr);
assert.match(patched.stdout, /0\.1\.23a/);
} finally {
assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-version-')), true);
await rm(root, { recursive: true, force: true });
}
});
// Each test installer has the version resource that Tauri writes for its version, and the stock template
// layout: Modern UI, then the hooks, then the pages and an Install section that ends with NSIS_HOOK_POSTINSTALL.
// The installed version comes from a test-only registry key. Nothing forces an internal variable.
test('the hooks block downgrades in every installer mode', { skip: nsisSkip }, async () => {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-hooks-'));
const key = 'Software\\RuneStoneInstallerTest-' + path.basename(root);
const reg = (...args: string[]) => spawnSync('reg', args, { encoding: 'utf8', windowsHide: true });
const installed = () => {
const result = reg('query', 'HKCU\\' + key);
const values: Record<string, string> = {};
if (result.status === 0) for (const match of result.stdout.matchAll(/^\s+(\S+)\s+REG_SZ\s+(.*?)\s*$/gm)) values[match[1]] = match[2];
return values;
};
const setInstalled = (values: Record<string, string>) => {
reg('delete', 'HKCU\\' + key, '/f');
for (const [name, value] of Object.entries(values)) assert.equal(reg('add', 'HKCU\\' + key, '/v', name, '/d', value, '/f').status, 0);
};
const installers = new Map<string, string>();
const installer = async (version: string) => {
if (installers.has(version)) return installers.get(version)!;
const { toolchain, windows } = releaseVersion(version);
const executable = path.join(root, `setup-${version}.exe`);
const script = path.join(root, `setup-${version}.nsi`);
const source = `Unicode true
RequestExecutionLevel user
Name "RuneStone hook test"
OutFile "${executable}"
InstallDir "${path.join(root, 'install')}"
AutoCloseWindow true
VIProductVersion "${windows}"
VIAddVersionKey "ProductName" "RuneStone hook test"
VIAddVersionKey "FileDescription" "RuneStone hook test"
VIAddVersionKey "LegalCopyright" "Test"
VIAddVersionKey "FileVersion" "${toolchain}"
VIAddVersionKey "ProductVersion" "${toolchain}"
!define RUNESTONE_UNINSTKEY "${key}"
; Record the notice instead of opening a message box.
!macro RUNESTONE_DOWNGRADE_NOTICE
\${IfNot} \${Silent}
WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestNotice" "shown"
\${EndIf}
!macroend
!include MUI2.nsh
!include "${hooks}"
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipPage
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
; In the stock template, the maintenance page that can start the uninstaller follows the first page.
; That page skips itself when it cannot find the installation in SHCTX.
Function SkipPage
WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestFirstPage" "shown"
ReadRegStr $0 SHCTX "\${RUNESTONE_UNINSTKEY}" "RuneStoneWindowsVersion"
WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestPageFound" "[$0]"
Abort
FunctionEnd
Section Install
WriteRegStr SHCTX "\${RUNESTONE_UNINSTKEY}" "DisplayVersion" "${toolchain}"
WriteRegStr SHCTX "\${RUNESTONE_UNINSTKEY}" "TestLocalAppData" "$LOCALAPPDATA"
!insertmacro NSIS_HOOK_POSTINSTALL
SectionEnd
`;
await writeFile(script, source);
compile(script, source);
installers.set(version, executable);
return executable;
};
const install = async (version: string, flags: string[]) =>
spawnSync(await installer(version), flags, { encoding: 'utf8', windowsHide: true, timeout: 60000 }).status;
const silent = (flags: readonly string[]) => flags.includes('/S');
try {
// Installer 0.1.23a over 0.1.23b. Without /S, the check runs before the first page.
for (const flags of [['/S'], ['/S', '/UPDATE'], ['/S', '/P'], ['/P'], ['/P', '/UPDATE'], []]) {
setInstalled({ RuneStoneWindowsVersion: '0.1.23.2', DisplayVersion: '0.1.23b' });
assert.equal(await install('0.1.23a', flags), 2, 'A downgrade must stop with exit code 2: ' + (flags.join(' ') || 'interactive'));
const values = installed();
assert.equal(values.DisplayVersion, '0.1.23b', 'A blocked setup must not install.');
assert.equal(values.TestNotice, silent(flags) ? undefined : 'shown');
assert.equal(values.TestFirstPage, undefined, 'Setup must stop before the first page.');
}
// Earlier installers wrote only the toolchain version to DisplayVersion.
for (const [previous, version, code] of [['0.1.24', '0.1.23z', 2], ['0.1.23+1', '0.1.23', 2], ['0.1.23+1', '0.1.23a', 0], ['0.1.23+1', '0.1.23b', 0]] as const) {
setInstalled({ DisplayVersion: previous });
assert.equal(await install(version, ['/S']), code, `${version} over ${previous}`);
}
// An unknown installed version blocks setup.
for (const values of [{ RuneStoneWindowsVersion: '0.1.23b' }, { DisplayVersion: '0.1.23b' }, { DisplayVersion: '0.1.23-beta' }, { DisplayVersion: 'garbage' }] as Record<string, string>[]) {
setInstalled(values);
assert.equal(await install('0.1.24', ['/S']), 2, 'Unknown installed version ' + JSON.stringify(values));
}
// Same version, upgrade, and first installation. Each writes the literal release version.
for (const [previous, version, flags] of [['0.1.23.1', '0.1.23a', ['/S']], ['0.1.23.1', '0.1.23a', []], ['0.1.23.26', '0.1.23aa', ['/P', '/UPDATE']], [null, '0.1.24', ['/S']]] as const) {
setInstalled(previous ? { RuneStoneWindowsVersion: previous } : {});
assert.equal(await install(version, [...flags]), 0, `${version} over ${previous ?? 'no installation'} with ${flags.join(' ') || 'interactive'}`);
const values = installed();
assert.equal(values.DisplayVersion, version, 'Installed apps must show the release version.');
assert.equal(values.RuneStoneReleaseVersion, version);
assert.equal(values.RuneStoneWindowsVersion, releaseVersion(version).windows);
assert.equal(values.TestNotice, undefined);
// Without /S, the pages must not find the installation, so that setup replaces it in place.
assert.equal(values.TestPageFound, silent(flags) ? undefined : '[]');
// RuneStoneGuiInit switches to the "all" context. The sections must run in the current-user context again.
assert.equal(values.TestLocalAppData?.toLowerCase(), process.env.LOCALAPPDATA!.toLowerCase());
}
} finally {
reg('delete', 'HKCU\\' + key, '/f');
assert.equal(reg('query', 'HKCU\\' + key).status, 1, 'The test registry key must be removed.');
assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-hooks-')), true);
await rm(root, { recursive: true, force: true });
}
});
// NSIS_HOOK_POSTINSTALL removes the engine folder that releases up to 0.1.48 put in the installation folder.
// NSIS_HOOK_POSTUNINSTALL removes the downloaded engine, keeps the browser profiles, and keeps everything during an update.
test('the hooks remove old and downloaded browser engines but keep the profiles', { skip: nsisSkip }, async () => {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-engine-'));
const bundle = 'com.runestone.hook-test-' + path.basename(root);
const local = path.join(process.env.LOCALAPPDATA!, bundle);
const install = path.join(root, 'install');
const key = 'Software\\RuneStoneInstallerTest-' + path.basename(root);
const program = async (name: string, updateMode: number) => {
const executable = path.join(root, name + '.exe'), script = path.join(root, name + '.nsi');
const source = `Unicode true
SilentInstall silent
RequestExecutionLevel user
Name "RuneStone engine hook test"
OutFile "${executable}"
InstallDir "${install}"
VIProductVersion "0.1.49.0"
VIAddVersionKey "ProductName" "RuneStone engine hook test"
VIAddVersionKey "FileVersion" "0.1.49"
VIAddVersionKey "ProductVersion" "0.1.49"
!define RUNESTONE_UNINSTKEY "${key}"
!define BUNDLEID "${bundle}"
!include "${hooks}"
Var UpdateMode
Section Install
StrCpy $UpdateMode ${updateMode}
!insertmacro NSIS_HOOK_POSTINSTALL
!insertmacro NSIS_HOOK_POSTUNINSTALL
SectionEnd
`;
await writeFile(script, source);
compile(script, source);
return executable;
};
const seed = async () => {
await mkdir(path.join(install, 'browser-engine', 'locales'), { recursive: true });
await writeFile(path.join(install, 'browser-engine', 'RuneStone-Browser.exe'), 'old engine');
await writeFile(path.join(install, 'runestone.exe'), 'app');
await mkdir(path.join(local, 'browser-engine', '0.1.8'), { recursive: true });
await writeFile(path.join(local, 'browser-engine', '0.1.8', 'RuneStone-Browser.exe'), 'engine');
await mkdir(path.join(local, 'browser'), { recursive: true });
await writeFile(path.join(local, 'browser', 'browser.json'), '{}');
};
try {
await seed();
assert.equal(spawnSync(await program('remove', 0), ['/S'], { windowsHide: true, timeout: 30000 }).status, 0);
assert.equal(existsSync(path.join(install, 'browser-engine')), false, 'Setup removes the old engine folder.');
assert.equal(existsSync(path.join(install, 'runestone.exe')), true);
assert.equal(existsSync(path.join(local, 'browser-engine')), false, 'Uninstall removes the downloaded engine.');
assert.equal(existsSync(path.join(local, 'browser', 'browser.json')), true, 'The profiles stay.');
await seed();
assert.equal(spawnSync(await program('update', 1), ['/S'], { windowsHide: true, timeout: 30000 }).status, 0);
assert.equal(existsSync(path.join(local, 'browser-engine', '0.1.8', 'RuneStone-Browser.exe')), true, 'An update keeps the downloaded engine.');
} finally {
spawnSync('reg', ['delete', 'HKCU\\' + key, '/f'], { windowsHide: true });
assert.equal(local.startsWith(process.env.LOCALAPPDATA!) && path.basename(local).startsWith('com.runestone.hook-test-'), true);
await rm(local, { recursive: true, force: true });
await rm(root, { recursive: true, force: true });
}
});
+167
View File
@@ -0,0 +1,167 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { inflateSync } from 'node:zlib';
import { checkTarget, INSTALLED_EXE, markdownTable, median, parseArguments, processTree, summarize } from '../../../scripts/measure/core.mjs';
import { crc32, encodePng, gradientPixel, PNG_SIGNATURE, readPngChunks } from '../../../scripts/measure/png.mjs';
import { readPdfXref, writePdf } from '../../../scripts/measure/pdf.mjs';
import { cardFileName, pmFiles, seededUuid } from '../../../scripts/measure/fixture.mjs';
const required = ['--exe', 'build/runestone.exe', '--identifier', 'com.runestone.phase7-ram', '--stage', 'reference', '--mode', 'plugin', '--features', 'git,pdf'];
const env = { APPDATA: 'C:\\Users\\Test\\AppData\\Roaming', LOCALAPPDATA: 'C:\\Users\\Test\\AppData\\Local' };
test('the measurement tool reads its arguments and their defaults', () => {
const options = parseArguments(required);
assert.equal(options.exe, 'build/runestone.exe');
assert.equal(options.identifier, 'com.runestone.phase7-ram');
assert.deepEqual(options.features, ['git', 'pdf']);
assert.equal(options.runs, 3);
assert.equal(options.port, 9241);
assert.equal(options.freshFixture, false);
const custom = parseArguments([...required, '--runs', '5', '--port', '9300', '--fresh-fixture', '--only', 'base,git:in-use']);
assert.equal(custom.runs, 5);
assert.equal(custom.port, 9300);
assert.equal(custom.freshFixture, true);
assert.deepEqual(custom.only, ['base', 'git:in-use']);
assert.deepEqual(parseArguments([...required.slice(0, 8), '--features', 'git,git, pm']).features, ['git', 'pm']);
});
test('the measurement tool rejects missing, repeated, and unknown arguments', () => {
for (const args of [
[],
required.slice(0, -2),
[...required, '--runs'],
[...required, '--runs', 'three'],
[...required, '--runs', '0'],
[...required, '--port', '80'],
[...required, '--mode', 'native'],
[...required, '--force'],
[...required.slice(0, 6), '--mode', 'hybrid', '--features', 'git'],
[...required.slice(0, 8), '--features', 'git,editor'],
[...required.slice(0, 4), '--stage', '../escape', '--mode', 'plugin', '--features', 'git'],
[...required, '--only', 'pm:in-use'],
[...required, '--only', 'git:busy'],
]) assert.throws(() => parseArguments(args), Error, args.join(' '));
});
test('the measurement tool refuses the installed app and its identifier', () => {
assert.throws(() => checkTarget({ exe: INSTALLED_EXE, identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/);
assert.throws(() => checkTarget({ exe: INSTALLED_EXE.toUpperCase(), identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/);
assert.throws(() => checkTarget({ exe: 'C:\\Users\\Test\\AppData\\Local\\RuneStone\\runestone.exe', identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/);
assert.throws(() => checkTarget({ exe: 'C:\\Users\\Test\\AppData\\Local\\RuneStone\\other.exe', identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/);
for (const identifier of ['com.runestone.app', 'COM.RUNESTONE.APP', 'com.example.test', 'com.runestone.', 'com.runestone.../x', 'com.runestone.Test', undefined])
assert.throws(() => checkTarget({ exe: 'D:\\build\\runestone.exe', identifier }, env), /Refusing the identifier/, String(identifier));
assert.deepEqual(checkTarget({ exe: 'D:\\build\\runestone.exe', identifier: 'com.runestone.phase7-ram' }, env), {
roaming: 'C:\\Users\\Test\\AppData\\Roaming\\com.runestone.phase7-ram',
local: 'C:\\Users\\Test\\AppData\\Local\\com.runestone.phase7-ram',
});
});
test('the median ignores missing values and averages the two middle values', () => {
assert.equal(median([]), null);
assert.equal(median([null, undefined, Number.NaN]), null);
assert.equal(median([3, 1, 2]), 2);
assert.equal(median([4, 1, 3, 2]), 2.5);
assert.equal(median([5, null, 1]), 3);
const summary: Record<string, number | null> = summarize([{ privateMB: 100, startMs: 900 }, { privateMB: 120, startMs: 1100 }, { error: 'failed', privateMB: 999 }]);
assert.equal(summary.runs, 3);
assert.equal(summary.failed, 1);
assert.equal(summary.privateMB, 110);
assert.equal(summary.startMs, 1000);
});
test('the process tree walk sums only the descendants of the started process', () => {
const list = [
{ ProcessId: 4, ParentProcessId: 0, Name: 'System', PrivatePageCount: 1, WorkingSetSize: 1, Created: 1 },
{ ProcessId: 100, ParentProcessId: 4, Name: 'runestone.exe', PrivatePageCount: 10, WorkingSetSize: 20, Created: 10 },
{ ProcessId: 101, ParentProcessId: 100, Name: 'msedgewebview2.exe', PrivatePageCount: 30, WorkingSetSize: 40, Created: 11 },
{ ProcessId: 102, ParentProcessId: 101, Name: 'msedgewebview2.exe', PrivatePageCount: 50, WorkingSetSize: 60, Created: 12 },
{ ProcessId: 103, ParentProcessId: 100, Name: 'pwsh.exe', PrivatePageCount: 5, WorkingSetSize: 6, Created: 13 },
// The installed app, a sibling tree that the walk must not count.
{ ProcessId: 200, ParentProcessId: 4, Name: 'runestone.exe', PrivatePageCount: 1000, WorkingSetSize: 1000, Created: 9 },
{ ProcessId: 201, ParentProcessId: 200, Name: 'msedgewebview2.exe', PrivatePageCount: 1000, WorkingSetSize: 1000, Created: 9 },
// A process whose parent ID was reused: it started before the process with that ID.
{ ProcessId: 104, ParentProcessId: 100, Name: 'stale.exe', PrivatePageCount: 7, WorkingSetSize: 7, Created: 5 },
];
const tree = processTree(list, 100);
assert.deepEqual(tree.processes.map(item => item.ProcessId), [100, 101, 103, 102]);
assert.equal(tree.privateBytes, 95);
assert.equal(tree.workingSet, 126);
assert.equal(tree.count, 4);
assert.deepEqual(tree.names, { 'runestone.exe': 1, 'msedgewebview2.exe': 2, 'pwsh.exe': 1 });
assert.equal(processTree(list, 999).count, 0);
// A cycle in a stale process list does not loop.
assert.equal(processTree([{ ProcessId: 1, ParentProcessId: 2, Name: 'a' }, { ProcessId: 2, ParentProcessId: 1, Name: 'b' }], 1).count, 2);
});
test('the PNG writer gives a valid signature, chunk CRCs, and pixel data', () => {
assert.equal(crc32(Buffer.from('123456789')), 0xcbf43926);
const png = encodePng(4, 3, gradientPixel(4, 3, [0, 0, 0], [255, 255, 255], 0));
assert.ok(png.subarray(0, 8).equals(PNG_SIGNATURE));
const chunks = readPngChunks(png);
assert.deepEqual(chunks.map(chunk => chunk.type), ['IHDR', 'IDAT', 'IEND']);
for (const chunk of chunks) assert.equal(chunk.stored, chunk.computed, chunk.type);
assert.equal(chunks[0].data.readUInt32BE(0), 4);
assert.equal(chunks[0].data.readUInt32BE(4), 3);
assert.equal(chunks[0].data[8], 8);
assert.equal(chunks[0].data[9], 2);
const raw = inflateSync(chunks[1].data);
assert.equal(raw.length, 3 * (1 + 4 * 3));
assert.equal(raw[0], 0);
assert.deepEqual([...raw.subarray(1, 4)], [0, 0, 0]);
assert.deepEqual([...raw.subarray(10, 13)], [191, 191, 191]);
assert.throws(() => encodePng(0, 1, () => [0, 0, 0]));
});
test('the PDF writer gives a header, a trailer, and xref offsets that point to their objects', () => {
const pdf = writePdf(Array.from({ length: 50 }, (_, index) => `Page ${index + 1}`));
const text = pdf.toString('latin1');
assert.ok(text.startsWith('%PDF-1.4\n'));
assert.ok(text.endsWith('%%EOF\n'));
const xref = readPdfXref(pdf);
assert.equal(xref.count, 3 + 50 * 2 + 1);
assert.equal(xref.entries[0].line, '0000000000 65535 f ');
for (const [index, entry] of xref.entries.slice(1).entries()) {
assert.equal(entry.line.length + 1, 20, 'Each xref entry is 20 bytes.');
assert.ok(entry.used);
assert.ok(text.startsWith(`${index + 1} 0 obj\n`, entry.offset), `Object ${index + 1} is at ${entry.offset}.`);
}
assert.match(text, /\/Type \/Pages \/Kids \[[^\]]+\] \/Count 50 >>/);
assert.match(text, /\(Page 25\) Tj/);
assert.match(text, new RegExp(`/Size ${xref.count} /Root 1 0 R`));
// Stream lengths match the stream bytes.
for (const match of text.matchAll(/<< \/Length (\d+) >>\nstream\n/g)) {
const start = match.index + match[0].length;
assert.ok(text.startsWith('endstream', start + Number(match[1])));
}
assert.match(writePdf(['A (b) \\ c']).toString('latin1'), /\(A \\\(b\\\) \\\\ c\) Tj/);
});
test('the Project Management fixture uses the card file names and ignore files of the real store', () => {
const files = pmFiles();
assert.equal(files.get('.runestone/pm/cards/.gitignore'), '*\n');
assert.match(files.get('.runestone/pm/.gitignore')!, /^\*$/m);
const catalog = JSON.parse(files.get('.runestone/pm/workspace.json')!);
assert.equal(catalog.schema, 1);
assert.equal(catalog.boards.length, 8);
const cards = [...files.keys()].filter(name => name.startsWith('.runestone/pm/cards/') && name.endsWith('.md'));
assert.equal(cards.length, 400);
const id = seededUuid('card-0-0');
assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
assert.equal(cardFileName(id), `${Buffer.from(id).toString('hex')}.md`);
assert.match(files.get(`.runestone/pm/cards/${cardFileName(id)}`)!, new RegExp(`^---\\nrunestone_pm:\\n schema: 1\\n id: ${id}\\n kind: task\\n`));
});
test('the report table has one row for each scenario and marks failures', () => {
const report = {
stage: 'reference', build: 'x.exe', identifier: 'com.runestone.phase7-ram', mode: 'plugin', runs: 3, date: '2026-10-29',
machine: { cpu: 'CPU', ramGB: 32, windows: 'Windows 11' },
rows: [
{ feature: 'base', scenario: 'base', median: { runs: 3, failed: 0, privateMB: 200.04, workingSetMB: 300, heapMB: 20, startMs: 1500.4, firstNeedMs: null, longTaskCount: 1, longTaskMaxMs: 80 } },
{ feature: 'pdf', scenario: 'in-use', median: { runs: 3, failed: 3 }, reason: 'timeout | x' },
],
};
const table = markdownTable(report);
assert.match(table, /\| base \| base \| 200\.0 \| 300\.0 \| 20\.0 \| 1500 \| – \| 1 \/ 80 \|/);
assert.match(table, /\| pdf \| in-use \| failed \|/);
assert.doesNotMatch(table, /timeout \| x/);
});
+189
View File
@@ -0,0 +1,189 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm, access, readdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import zlib from "node:zlib";
import { createHash } from "node:crypto";
import { describePlan, git, integrity, packEntries, packageFileName, packageTime, parseArguments, planSdkRelease, releasePackageJson, runSdkRelease } from "../../../scripts/releaseSdk.mjs";
// These tests use a temporary Git repository. They need no network and upload nothing.
const repository = path.resolve(".");
const sdk = "packages/plugin-sdk";
const releaseUrl = "https://example.com/releases/download/plugin-sdk-v0.1.0";
const exists = (file: string) => access(file).then(() => true, () => false);
type Setup = { base: string; root: string };
// A host repository with the SDK package files at version 0.0.0.
async function fixture(): Promise<Setup> {
const base = await mkdtemp(path.join(tmpdir(), "runestone-sdk-release-"));
const root = path.join(base, "RuneStone");
await mkdir(path.join(root, sdk), { recursive: true });
for (const file of ["package.json", "README.md", "LICENSE", "NOTICE"]) await copyFile(path.join(repository, sdk, file), path.join(root, sdk, file));
const source = JSON.parse(await readFile(path.join(root, sdk, "package.json"), "utf8"));
await writeFile(path.join(root, sdk, "package.json"), JSON.stringify({ ...source, version: "0.0.0", scripts: { build: "tsc" }, devDependencies: { typescript: "6" } }, null, 2) + "\n");
await writeFile(path.join(root, ".gitignore"), "dist/\nreleases/\n");
await git(root, ["init", "-q", "-b", "master"]);
await git(root, ["config", "user.name", "SDK test"]);
await git(root, ["config", "user.email", "[email protected]"]);
await git(root, ["add", "-A"]);
await git(root, ["commit", "-q", "-m", "host"]);
return { base, root };
}
async function withFixture(body: (setup: Setup) => Promise<void>) {
const setup = await fixture();
try { await body(setup); } finally { await rm(setup.base, { recursive: true, force: true }); }
}
// A build that writes a small dist/ folder in place of the TypeScript compiler.
const fakeBuild = async (root: string) => {
const dist = path.join(root, sdk, "dist");
await mkdir(path.join(dist, "nested"), { recursive: true });
await writeFile(path.join(dist, "index.js"), "export const API_VERSION = 1;\n");
await writeFile(path.join(dist, "index.d.ts"), "export declare const API_VERSION = 1;\n");
await writeFile(path.join(dist, "nested", "extra.js"), "export {};\n");
return dist;
};
const failingBuild = async () => { throw Error("The compiler failed."); };
// Reads the files of a gzip tar: the name, mode, time, and contents of each entry.
function unpack(archive: Buffer) {
const tar = zlib.gunzipSync(archive);
const entries: { name: string; mode: number; time: number; type: string; data: string }[] = [];
for (let offset = 0; offset + 512 <= tar.length; ) {
const header = tar.subarray(offset, offset + 512);
if (header.every(byte => byte === 0)) break;
const field = (start: number, size: number) => header.subarray(start, start + size).toString("ascii").replace(/\0.*$/s, "").trim();
let sum = 0;
for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : header[i];
assert.equal(parseInt(field(148, 8), 8), sum, "The header checksum must match.");
assert.equal(field(257, 6), "ustar");
const size = parseInt(field(124, 12), 8);
entries.push({ name: field(0, 100), mode: parseInt(field(100, 8), 8), time: parseInt(field(136, 12), 8), type: field(156, 1),
data: tar.subarray(offset + 512, offset + 512 + size).toString("utf8") });
offset += 512 + Math.ceil(size / 512) * 512;
}
return entries;
}
const quiet = async <T>(work: () => Promise<T>) => {
const error = console.error;
console.error = () => {};
try { return await work(); } finally { console.error = error; }
};
test("the SDK release script reads --release-url, --version, and --dry-run", () => {
assert.deepEqual(parseArguments(["--release-url", releaseUrl, "--version", "0.1.0"]), { version: "0.1.0", releaseUrl, dryRun: false });
assert.deepEqual(parseArguments(["--dry-run", "--version", "0.1.0a", "--release-url", releaseUrl]), { version: "0.1.0a", releaseUrl, dryRun: true });
for (const args of [[], ["--version", "0.1.0"], ["--release-url", releaseUrl], ["--version"], ["0.1.0"], ["--release-url", releaseUrl, "--version", "0.1.0", "--version", "0.1.1"], ["--push"]]) {
assert.throws(() => parseArguments(args));
}
});
test("the release package.json has the version and no build scripts or development dependencies", () => {
const source = { name: "@runestone/plugin-sdk", version: "0.0.0", types: "./dist/index.d.ts", exports: {}, files: ["dist"], license: "Apache-2.0", scripts: { build: "tsc" }, devDependencies: { typescript: "6" } };
assert.deepEqual(releasePackageJson(source, "0.1.0"), { name: "@runestone/plugin-sdk", version: "0.1.0", types: "./dist/index.d.ts", exports: {}, files: ["dist"], license: "Apache-2.0" });
assert.throws(() => releasePackageJson({ ...source, license: undefined }, "0.1.0"), /license/);
});
test("the package file has the npm pack name", () => {
assert.equal(packageFileName("@runestone/plugin-sdk", "0.1.0"), "runestone-plugin-sdk-0.1.0.tgz");
assert.equal(packageFileName("plain", "1.0.0a"), "plain-1.0.0a.tgz");
});
test("the package is a tar under package/ in name order, with a fixed time, and the same entries give the same bytes", () => {
const entries = [
{ name: "package.json", data: Buffer.from('{"name":"x"}\n') },
{ name: "dist/index.js", data: Buffer.alloc(700, 97) },
{ name: "README.md", data: Buffer.from("") },
];
const archive = packEntries(entries);
assert.deepEqual(archive, packEntries([...entries].reverse()));
const files = unpack(archive);
assert.deepEqual(files.map(file => file.name), ["package/README.md", "package/dist/index.js", "package/package.json"]);
for (const file of files) {
assert.equal(file.mode, 0o644);
assert.equal(file.time, packageTime);
assert.equal(file.type, "0");
}
assert.equal(files[1].data, "a".repeat(700));
assert.equal(integrity(archive), "sha512-" + createHash("sha512").update(archive).digest("base64"));
assert.throws(() => packEntries([{ name: "x".repeat(93), data: Buffer.from("") }]), /too long/);
assert.throws(() => packEntries([{ name: "a", data: Buffer.from("1") }, { name: "a", data: Buffer.from("2") }]), /two files/);
});
test("a dry run plans the release, gives the plugin dependency line, and changes no file", () => withFixture(async setup => {
const before = await readFile(path.join(setup.root, sdk, "package.json"), "utf8");
const plan = await planSdkRelease(setup.root, { version: "0.1.0", releaseUrl });
const text = describePlan(plan);
assert.match(text, /SDK version: 0\.1\.0 \(current 0\.0\.0\)/);
assert.match(text, /with dist, package\.json, README\.md, LICENSE, NOTICE, and/);
assert.equal(plan.url, `${releaseUrl}/runestone-plugin-sdk-0.1.0.tgz`);
assert.match(text, /Plugins then use: "@runestone\/plugin-sdk": "https:\/\/example\.com\/releases\/download\/plugin-sdk-v0\.1\.0\/runestone-plugin-sdk-0\.1\.0\.tgz"/);
assert.equal(plan.packageJson.version, "0.1.0");
assert.equal(plan.packageJson.scripts, undefined);
assert.equal(await readFile(path.join(setup.root, sdk, "package.json"), "utf8"), before);
assert.equal(await exists(path.join(setup.root, "releases")), false);
}));
test("the release refuses an HTTP URL, a URL with credentials, an earlier version, and an existing release file", () => withFixture(async setup => {
for (const url of ["http://example.com/r", "https://user:[email protected]/r", "https://example.com/r?x=1", "https://example.com/r#x"]) {
await assert.rejects(planSdkRelease(setup.root, { version: "0.1.0", releaseUrl: url }), /HTTPS release URL/);
}
await assert.rejects(planSdkRelease(setup.root, { version: "0.0.0", releaseUrl }), /greater than the current version 0\.0\.0/);
await assert.rejects(planSdkRelease(setup.root, { version: "1.0", releaseUrl }), /release version/);
await mkdir(path.join(setup.root, "releases/plugin-sdk/0.1.0"), { recursive: true });
await writeFile(path.join(setup.root, "releases/plugin-sdk/0.1.0/sdk.json"), "{}");
await assert.rejects(planSdkRelease(setup.root, { version: "0.1.0", releaseUrl }), /already exists/);
}));
test("the release refuses a package without a license file or with source changes that are not committed", () => withFixture(async setup => {
await rm(path.join(setup.root, sdk, "LICENSE"));
await assert.rejects(planSdkRelease(setup.root, { version: "0.1.0", releaseUrl }), /no LICENSE file/);
await git(setup.root, ["checkout", "-q", "--", sdk]);
await writeFile(path.join(setup.root, sdk, "README.md"), "changed");
await assert.rejects(planSdkRelease(setup.root, { version: "0.1.0", releaseUrl }), /not committed/);
}));
test("a completed release writes the package and its record, then sets the source version", () => withFixture(async setup => {
const plan = await planSdkRelease(setup.root, { version: "0.1.0", releaseUrl });
const result = await runSdkRelease(plan, fakeBuild);
const folder = path.join(setup.root, "releases/plugin-sdk/0.1.0");
assert.deepEqual((await readdir(folder)).sort(), ["runestone-plugin-sdk-0.1.0.tgz", "sdk.json"]);
const archive = await readFile(path.join(folder, "runestone-plugin-sdk-0.1.0.tgz"));
const files = unpack(archive);
assert.deepEqual(files.map(file => file.name), ["package/LICENSE", "package/NOTICE", "package/README.md", "package/dist/index.d.ts", "package/dist/index.js", "package/dist/nested/extra.js", "package/package.json"]);
const packed = JSON.parse(files.find(file => file.name === "package/package.json")!.data);
assert.equal(packed.version, "0.1.0");
assert.equal(packed.scripts, undefined);
assert.equal(files.find(file => file.name === "package/LICENSE")!.data, await readFile(path.join(setup.root, sdk, "LICENSE"), "utf8"));
const record = JSON.parse(await readFile(path.join(folder, "sdk.json"), "utf8"));
assert.deepEqual(record, {
name: "@runestone/plugin-sdk", version: "0.1.0", file: "runestone-plugin-sdk-0.1.0.tgz", url: plan.url, bytes: archive.length,
sha256: createHash("sha256").update(archive).digest("hex"), integrity: integrity(archive), source: plan.hostCommit,
});
assert.equal(result.sha256, record.sha256);
assert.equal(JSON.parse(await readFile(path.join(setup.root, sdk, "package.json"), "utf8")).version, "0.1.0");
}));
test("a failed build restores the version and writes no release file", () => withFixture(async setup => {
const before = await readFile(path.join(setup.root, sdk, "package.json"), "utf8");
const plan = await planSdkRelease(setup.root, { version: "0.1.0", releaseUrl });
await quiet(() => assert.rejects(runSdkRelease(plan, failingBuild), /compiler failed/));
assert.equal(await readFile(path.join(setup.root, sdk, "package.json"), "utf8"), before);
assert.equal(await exists(path.join(setup.root, "releases/plugin-sdk/0.1.0")), false);
}));
test("a failure after the package is written removes the files of that attempt only", () => withFixture(async setup => {
const before = await readFile(path.join(setup.root, sdk, "package.json"), "utf8");
const plan = await planSdkRelease(setup.root, { version: "0.1.0", releaseUrl });
// A record that appears after the plan makes the record write fail.
await mkdir(plan.releaseDir, { recursive: true });
await writeFile(plan.artifacts.metadata, "kept");
await quiet(() => assert.rejects(runSdkRelease(plan, fakeBuild), /EEXIST/));
assert.equal(await readFile(path.join(setup.root, sdk, "package.json"), "utf8"), before);
assert.equal(await exists(plan.artifacts.archive), false);
assert.equal(await readFile(plan.artifacts.metadata, "utf8"), "kept");
}));
+119
View File
@@ -0,0 +1,119 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFile, access } from "node:fs/promises";
import path from "node:path";
import { API_VERSION, describeFeature, hasFeature, missingFeatures, MissingFeatureError, pluginFeatures, requireFeature, requireFeatures, type PluginApi } from "../../../packages/plugin-sdk/src/index.ts";
import * as sdkIcons from "../../../packages/plugin-sdk/src/icons.ts";
import * as sdkTooltip from "../../../packages/plugin-sdk/src/tooltip.ts";
import * as hostIcons from "../../../src/lib/ui/actionIcons.ts";
import * as hostTooltip from "../../../src/lib/ui/tooltip.ts";
import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts";
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
import { ServiceHub } from "../../../src/lib/plugins/services.ts";
import { declarationImports } from "../../../scripts/buildSdk.mjs";
import type { ActionMenuItem as HostMenuItem } from "../../../src/lib/ui/actionMenu.ts";
import type { MenuOptions as HostMenuOptions } from "../../../src/lib/ui/managedActionMenu.ts";
import type { ActionMenuItem, ActionMenuOptions } from "../../../packages/plugin-sdk/src/index.ts";
// The host menu files keep their own menu types. `pnpm check` fails when those types and the SDK types differ.
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const sameMenuTypes: [Same<HostMenuItem, ActionMenuItem>, Same<HostMenuOptions, ActionMenuOptions>] = [true, true];
const base: SessionServices = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
};
async function hostApi(services: Partial<SessionServices>, views = false) {
let api!: PluginApi;
const session = views
? new ExternalSession("org.test.sdk", { ...base, ...services }, () => {}, () => {}, new ContributionRegistry(), async () => {}, async () => "", () => {}, () => {}, () => {})
: new ExternalSession("org.test.sdk", { ...base, ...services }, () => {}, () => {}, new ContributionRegistry());
await session.start({ activate(value) { api = value; } });
return { api, session };
}
test("feature checks find optional members, and missing members give an update message", () => {
const read = async () => new Uint8Array([1]);
const api = { workspace: { readBytes: read }, services: { get: () => null } } as unknown as PluginApi;
assert.equal(hasFeature(api, "workspace.readBytes"), true);
assert.equal(hasFeature(api, "services"), true);
assert.equal(hasFeature(api, "workspace.subscribe"), false);
assert.equal(hasFeature(api, "files"), false);
assert.deepEqual(missingFeatures(api, ["files", "workspace.readBytes", "settings.subscribe"]), ["files", "settings.subscribe"]);
assert.equal(requireFeature(api, "services"), (api as unknown as { services: unknown }).services);
assert.throws(() => requireFeature(api, "files"), (error: unknown) => error instanceof MissingFeatureError
&& error.name === "MissingFeatureError" && error.features.length === 1 && error.features[0] === "files"
&& error.message === "This plugin needs the folder grant API (api.files). Update RuneStone to a version that has this feature.");
assert.throws(() => requireFeatures(api, ["files", "workspace.readBytes", "openFile"]), {
message: "This plugin needs the folder grant API (api.files) and opening files in the RuneStone editor (api.openFile). Update RuneStone to a version that has these features.",
});
// The terminal API (api.pty) left the SDK when Terminal became a native feature, and the background API
// (api.backgrounds) when Project Management became one.
assert.throws(() => hasFeature(api, "pty" as never), TypeError);
assert.throws(() => hasFeature(api, "backgrounds" as never), TypeError);
assert.doesNotThrow(() => requireFeatures(api, ["services", "workspace.readBytes"]));
assert.throws(() => hasFeature(api, "workspace.read" as never), TypeError);
assert.equal(describeFeature("ui.showActionMenu"), "the shared action menu (api.ui.showActionMenu)");
assert.equal(API_VERSION, 1);
});
test("a required function stays bound to its parent object", async () => {
const workspace = { prefix: "ws:", async readOptional(this: { prefix: string }, file: string) { return this.prefix + file; } };
const api = { workspace } as unknown as PluginApi;
const readOptional = requireFeature(api, "workspace.readOptional");
assert.equal(await readOptional("a.md"), "ws:a.md");
});
test("the current host gives every SDK feature when all services are present", async () => {
const files = { chooseFolder: async () => null, pictureFolder: async () => ({ id: "g", path: "p", name: "n" }), grants: async () => [], revoke: async () => false, list: async () => [], readBytes: async () => new Uint8Array(), readSidecar: async () => null, writeSidecar: async () => {} };
const { api, session } = await hostApi({
files, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} },
settings: { ...base.settings, subscribe: () => () => {} },
}, true);
assert.deepEqual(missingFeatures(api, pluginFeatures), []);
await session.stop();
});
test("the host without optional services lacks only the features that depend on them", async () => {
const { api, session } = await hostApi({});
assert.deepEqual(missingFeatures(api, pluginFeatures).sort(), [
"closeView", "completion.transport", "files",
"openFile", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe",
"workspace.create", "workspace.listMarkdown", "workspace.readBytes", "workspace.readMany", "workspace.readOptional", "workspace.subscribe",
]);
await session.stop();
});
test("the host uses the SDK icons and tooltip, so plugins get the same artwork and behavior", () => {
assert.equal(hostIcons.actionIcons, sdkIcons.actionIcons);
assert.equal(hostIcons.actionIcon, sdkIcons.actionIcon);
assert.equal(hostTooltip.attachTooltip, sdkTooltip.attachTooltip);
for (const [name, markup] of Object.entries(sdkIcons.actionIcons)) assert.match(markup, /^<(path|circle|rect|ellipse)\b/, name);
});
test("the host menu types are the SDK menu types", () => {
assert.deepEqual(sameMenuTypes, [true, true]);
});
test("the SDK build gives declaration imports with .js paths", () => {
assert.equal(declarationImports('export type * from "./api.ts";\nimport type { A } from \'../b.ts\';\ntype C = import("./c.ts").C;\nimport x from "node:fs";'),
'export type * from "./api.js";\nimport type { A } from \'../b.js\';\ntype C = import("./c.js").C;\nimport x from "node:fs";');
});
test("each SDK export has a source module, and the package is not for npm", async () => {
const folder = path.resolve("packages/plugin-sdk");
const manifest = JSON.parse(await readFile(path.join(folder, "package.json"), "utf8"));
assert.equal(manifest.name, "@runestone/plugin-sdk");
assert.equal(manifest.private, true);
assert.equal(manifest.license, "Apache-2.0");
assert.equal(manifest.dependencies, undefined);
assert.deepEqual(manifest.files, ["dist", "README.md", "LICENSE", "NOTICE"]);
for (const file of ["README.md", "LICENSE", "NOTICE"]) await access(path.join(folder, file));
for (const [entry, target] of Object.entries(manifest.exports as Record<string, string | { types: string; default: string }>)) {
if (typeof target === "string") continue;
assert.equal(target.types.replace(/\.d\.ts$/, ""), target.default.replace(/\.js$/, ""), entry);
await access(path.join(folder, target.default.replace(/^\.\/dist\//, "src/").replace(/\.js$/, ".ts")));
}
});
+72
View File
@@ -0,0 +1,72 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { migrateLegacyPreferences } from '../../../src/lib/settings/migration.ts';
import { LEGACY_KEYS } from '../../../src/lib/settings/store.ts';
const palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' };
const reader = (values: Record<string, string>) => (key: string) => Object.hasOwn(values, key) ? values[key] : null;
test('Migration reads the four old keys and the theme backup, and normalizes each value', () => {
const custom = { schema: 2, id: 'night', name: 'Night', colors: { ...palette, bg: '#000000' } };
const sections = migrateLegacyPreferences(reader({
'runestone.settings': JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 900, extra: true }),
'runestone.appearance': JSON.stringify({ theme: 'custom:night', mode: 'light', transparency: { amount: 140 } }),
'runestone.custom-themes': JSON.stringify([custom, { schema: 2, id: '../bad' }]),
'runestone.custom-themes.legacy': JSON.stringify([{ schema: 1, id: 'kept' }]),
'runestone.language': 'fr',
}));
assert.deepEqual(sections, {
general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false },
language: 'fr',
customThemes: [{ ...custom, schema: 3, mode: 'dark' }],
customThemesLegacy: [{ schema: 1, id: 'kept' }],
// The mode comes from the migrated custom theme, not from a store that is still empty.
appearance: { theme: 'custom:night', mode: 'dark', transparency: { enabled: true, amount: 100 } },
});
});
test('Migration of version 1 themes keeps the saved palette and adds the originals to the backup once', () => {
const legacy = { schema: 1, id: 'old', name: 'Old', light: { ...palette, bg: '#fff' }, dark: palette };
const sections = migrateLegacyPreferences(reader({
'runestone.appearance': JSON.stringify({ theme: 'custom:old', mode: 'light' }),
'runestone.custom-themes': JSON.stringify([legacy]),
'runestone.custom-themes.legacy': JSON.stringify([legacy]),
}));
assert.deepEqual(sections.customThemes, [{ schema: 3, id: 'old', name: 'Old', mode: 'light', colors: legacy.light }]);
assert.deepEqual(sections.customThemesLegacy, [legacy]);
assert.deepEqual(sections.appearance, { theme: 'custom:old', mode: 'light' });
});
test('Missing keys give no sections, so the defaults apply', () => {
assert.deepEqual(migrateLegacyPreferences(() => null), {});
assert.deepEqual(migrateLegacyPreferences(() => { throw new Error('Storage unavailable'); }), {});
});
test('Damaged old values become defaults and unknown languages become English', () => {
const sections = migrateLegacyPreferences(reader({
'runestone.settings': '{broken',
'runestone.appearance': '[1, 2]',
'runestone.custom-themes': '{"not":"a list"}',
'runestone.language': 'de',
}));
assert.deepEqual(sections, {
general: { autosaveEnabled: true, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false },
language: 'en',
appearance: { theme: 'default', mode: 'dark' },
});
});
test('Migration keeps renamed theme IDs and a background image data URL', () => {
const image = 'data:image/png;base64,' + 'A'.repeat(40);
const sections = migrateLegacyPreferences(reader({
'runestone.appearance': JSON.stringify({ theme: 'holo', mode: 'dark', newTabBackground: { image, overlay: 0.4 } }),
}));
assert.deepEqual(sections.appearance, { theme: 'harvest-moon', mode: 'dark', newTabBackground: { image, overlay: 0.4, position: 'center', size: 'cover' } });
});
test('Every section has one old key', () => {
// `runestone.features` and `runestone.background` came after the settings file. Only the browser preview uses them.
// `runestone.terminal` is the key of the Terminal plugin. The first start of the Terminal feature copies it into the file.
// `runestone.project-management` came with the Project Management feature. Only the browser preview uses it.
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.background', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.project-management', 'runestone.settings', 'runestone.terminal']);
});
+118
View File
@@ -0,0 +1,118 @@
// The settings store with a mock desktop host. Each test file runs in its own process,
// so the mock is installed before the first import of the store.
import { test } from 'node:test';
import assert from 'node:assert/strict';
type Handler = (args: Record<string, unknown>) => unknown;
const calls: { command: string; args: Record<string, unknown> }[] = [];
const callbacks = new Map<number, (event: unknown) => void>();
const listeners = new Map<string, number[]>();
const handlers = new Map<string, Handler>();
let sequence = 0;
const host = globalThis as unknown as Record<string, unknown>;
host.isTauri = true;
host.window = globalThis;
host.__TAURI_INTERNALS__ = {
transformCallback: (callback: (event: unknown) => void) => { callbacks.set(++sequence, callback); return sequence; },
invoke: async (command: string, args: Record<string, unknown> = {}) => {
calls.push({ command, args });
if (command === 'plugin:event|listen') {
listeners.set(args.event as string, [...listeners.get(args.event as string) ?? [], args.handler as number]);
return args.handler;
}
const handler = handlers.get(command);
if (!handler) throw new Error(`Unhandled IPC: ${command}`);
return handler(args);
},
};
function emit(event: string, payload: unknown) {
for (const id of listeners.get(event) ?? []) callbacks.get(id)?.({ event, id, payload });
}
const legacy = new Map<string, string>();
host.localStorage = { getItem: (key: string) => legacy.get(key) ?? null, setItem: (key: string, value: string) => legacy.set(key, value) };
const store = await import('../../../src/lib/settings/store.ts');
const { migrateLegacyPreferences } = await import('../../../src/lib/settings/migration.ts');
let file: Record<string, unknown> | null = null;
let revision = 0;
// While `gate` is set, the host holds each write until the gate opens.
let gate: Promise<void> | undefined;
function closeGate() {
let open!: () => void;
gate = new Promise<void>(resolve => { open = resolve; });
return () => { gate = undefined; open(); };
}
handlers.set('settings_read', () => ({ exists: file !== null, revision, sections: { ...file } }));
handlers.set('settings_migrate', args => {
if (file === null) { file = { ...(args.sections as Record<string, unknown>) }; revision = 1; }
return { exists: true, revision, sections: { ...file }, notice: 'Notice once' };
});
handlers.set('settings_write', async args => {
if (gate) await gate;
const section = args.section as string;
file![section] = args.value;
revision += 1;
return { section, revision, value: args.value };
});
test('The first start migrates the old localStorage values, and later reads come from memory', async () => {
legacy.set('runestone.language', 'ja');
legacy.set('runestone.settings', JSON.stringify({ autosaveSeconds: 12 }));
await store.initSettings(migrateLegacyPreferences);
await store.initSettings(() => { throw new Error('Migrates once'); });
assert.deepEqual(calls.filter(call => !call.command.startsWith('plugin:')).map(call => call.command), ['settings_read', 'settings_migrate']);
assert.equal(calls[0].command, 'plugin:event|listen', 'The listener starts before the read');
assert.equal(store.readSection('language'), 'ja');
assert.deepEqual(store.readSection('general'), { autosaveEnabled: true, autosaveSeconds: 12, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false });
assert.equal(legacy.get('runestone.language'), 'ja', 'The old value stays in place');
assert.equal(store.takeSettingsNotice(), 'Notice once');
assert.equal(store.takeSettingsNotice(), null);
});
test('A write shows at once, merges quick writes, and runs subscribers', async () => {
let changes = 0;
const stop = store.onSettingsChange('language', () => { changes++; });
const open = closeGate();
const first = store.writeSection('language', 'fr');
const second = store.writeSection('language', 'zh-CN');
const third = store.writeSection('language', 'en');
assert.equal(store.readSection('language'), 'en');
assert.equal(changes, 3);
open();
await Promise.all([first, second, third]);
const writes = calls.filter(call => call.command === 'settings_write').map(call => call.args.value);
assert.deepEqual(writes, ['fr', 'en'], 'The writes during the first one merge into the last value');
assert.equal(file!.language, 'en');
stop();
});
test('Changes from other windows apply in revision order, and old changes do not', () => {
let changes = 0;
const stop = store.onSettingsChange('appearance', () => { changes++; });
emit('settings-changed', { section: 'appearance', revision: 50, value: { theme: 'claude', mode: 'light' } });
assert.deepEqual(store.readSection('appearance'), { theme: 'claude', mode: 'light' });
emit('settings-changed', { section: 'appearance', revision: 40, value: { theme: 'sakura', mode: 'light' } });
assert.deepEqual(store.readSection('appearance'), { theme: 'claude', mode: 'light' });
emit('settings-changed', { section: 'unknown', revision: 60, value: 1 });
assert.equal(changes, 1);
stop();
emit('settings-changed', { section: 'appearance', revision: 70, value: null });
assert.equal(store.readSection('appearance'), undefined, 'null removes the section');
assert.equal(changes, 1, 'A stopped subscriber does not run');
});
test('A change from another window during a local write applies after the write when it is newer', async () => {
const open = closeGate();
const pending = store.writeSection('general', { autosaveSeconds: 30 });
emit('settings-changed', { section: 'general', revision: 1000, value: { autosaveSeconds: 60 } });
assert.deepEqual(store.readSection('general'), { autosaveSeconds: 30 }, 'No old value appears during the write');
open();
await pending;
assert.deepEqual(store.readSection('general'), { autosaveSeconds: 60 }, 'The host saved the other window last');
});
test('A failed write reaches the caller', async () => {
handlers.set('settings_write', () => { throw 'Disk full'; });
await assert.rejects(store.writeSection('customThemes', []), /Disk full/);
});
+68
View File
@@ -0,0 +1,68 @@
// Ported from the Table Formulas plugin (tests/formulas.test.ts). The engine is now part of the host.
import assert from "node:assert/strict";
import test from "node:test";
import { cellAddress, evaluateTableFormulas } from "../../../src/lib/formulas/engine.ts";
const calculate = (formula: string) => evaluateTableFormulas([[formula]])[0][0]!.text;
test("aggregates distinguish separate cells and ranges from an arithmetic argument", () => {
const evaluate = (formula: string) => evaluateTableFormulas([["Name", "B", "C", "Result"], ["First", "9", "10", formula]])[1][3]!;
for (const [name, separate, combined] of [["SUM", "19", "19"], ["AVERAGE", "9.5", "19"], ["MIN", "9", "19"], ["MAX", "10", "19"], ["COUNT", "2", "1"]]) {
for (const separator of [",", ":"]) {
const result = evaluate(`=${name}(B2${separator}C2)`);
assert.equal(result.text, separate);
}
const result = evaluate(`=${name}(B2+C2)`);
assert.equal(result.text, combined);
}
assert.equal(evaluate("=(B2+C2)/2").text, "9.5");
assert.equal(evaluate("=ROUND(AVERAGE(B2,C2),0)").text, "10");
assert.equal(evaluate("=ABS(B2-C2)").text, "1");
assert.equal(evaluate("=AVERAGE((B2+C2))").text, "19");
});
test("arithmetic, precedence, parentheses, percentages and rounding", () => {
for (const [formula, result] of [
["=SUM(2+3)", "5"], ["=2+3*4", "14"], ["=(2+3)*4", "20"],
["=2^3^2", "512"], ["=-2^2", "-4"], ["=2^-2", "0.25"],
["=200*10%", "20"], ["=0.1+0.2", "0.3"], ["=1e2 + .5", "100.5"],
["=ROUND(-1.25,1)", "-1.3"], ["=ROUND(1.005,2)", "1.01"],
["=ROUND(125,-1)", "130"], ["=ABS(-4)", "4"], ["=sum(1,2,3)", "6"],
]) assert.equal(calculate(formula), result, formula);
});
test("same-table references, ranges, chained dependencies, and empty/text cells", () => {
const results = evaluateTableFormulas([
["Name", "Appearance", "Cha", "Combined"],
["First", "9", "10", "=AVERAGE(B2:C2)"],
["Second", "7", "9", "=SUM(B3,C3)/2"],
["Total", "", "=B4+1", "=SUM(D2:D3)"],
["Count", "=COUNT(A1:C4)", "=MAX(B2:C3)-MIN(B2:C3)", "=ROUND(D4/3,2)"],
["", "=SUM($B$2:$C$3)", "=AVERAGE(B1:B4)", "=SUM(C3:B2)"],
]);
assert.equal(results[1][3]?.text, "9.5");
assert.equal(results[2][3]?.text, "8");
assert.equal(results[3][3]?.text, "17.5");
assert.equal(results[3][2]?.text, "1");
assert.equal(results[4][1]?.text, "5");
assert.equal(results[4][2]?.text, "3");
assert.equal(results[4][3]?.text, "5.83");
assert.equal(results[5][1]?.text, "35");
assert.equal(results[5][2]?.text, "8");
assert.equal(results[5][3]?.text, "35");
assert.equal(results[0][0], null);
assert.equal(cellAddress(1, 26), "AA2");
assert.equal(evaluateTableFormulas([Array.from({ length: 27 }, (_, c) => c === 0 ? "=AA1" : "3")])[0][0]?.text, "3");
});
test("errors are visible, propagated, bounded, and never executed", () => {
for (const [formula, result] of [
["=1/0", "#DIV/0!"], ["=AVERAGE()", "#DIV/0!"], ["=A2", "#REF!"],
["=B1:B999999999", "#REF!"], ["=A0", "#REF!"], ["=1+", "#ERROR!"],
["=1 2", "#ERROR!"], ["=ROUND(1,2,3)", "#ERROR!"], ["=BOGUS(1)", "#NAME?"],
["=A1", "#CYCLE!"], ["=1e999", "#NUM!"], ["=9^9999", "#NUM!"],
["=globalThis.alert(1)", "#ERROR!"], ["=" + "(".repeat(100) + "1" + ")".repeat(100), "#LIMIT!"],
]) assert.equal(calculate(formula), result, formula);
const cycle = evaluateTableFormulas([["=B1", "=A1", "=SUM(A1:B1)", "=2+3"]]);
assert.deepEqual(cycle[0].map(cell => cell?.text), ["#CYCLE!", "#CYCLE!", "#CYCLE!", "5"]);
assert.equal(evaluateTableFormulas([["text", "=A1+1"]])[0][1]?.text, "#VALUE!");
});
+70
View File
@@ -0,0 +1,70 @@
import assert from "node:assert/strict";
import test, { afterEach } from "node:test";
import { get } from "svelte/store";
import MarkdownIt from "markdown-it";
import { activeTableFormulas, renderTableFormulas, setTableFormulasEnabled, tableFormulaHtml, tableFormulas, tableFormulasEnabled } from "../../../src/lib/formulas/index.ts";
import { tableCellMarkdown } from "../../../src/lib/editor/tableCellMarkdown.ts";
import { renderMarkdownHtml, renderMarkdownSections } from "../../../src/lib/workspace/noteHtml.ts";
afterEach(() => setTableFormulasEnabled(true));
test("Markdown rendering isolates tables and preserves literal, formatted, and non-table text", () => {
const source = "| X | Y | Result |\r\n| --- | --- | --- |\r\n| 9 | 10 | =AVERAGE(A2:B2) |\r\n\r\n| X | Y | Result |\r\n| --- | --- | --- |\r\n| 1 | 3 | =A2*B2 |\r\n";
const html = renderMarkdownHtml(source, new Map());
assert.match(html, /aria-label="=AVERAGE\(A2:B2\) → 9.5">9.5<\/span>/);
assert.match(html, /aria-label="=A2\*B2 → 3">3<\/span>/);
const sections = renderMarkdownSections(source, new Map());
assert.equal(sections.map(s => source.slice(s.start, s.end)).join(""), source);
assert.equal(sections.map(s => s.html).join(""), html);
const literal = renderMarkdownHtml("=1+2\n\n| A | B | C |\n| --- | --- | --- |\n| `=1+2` | \\=1+2 | ==highlight== |", new Map());
assert.doesNotMatch(literal, /md-table-formula/);
assert.match(literal, /<mark>highlight<\/mark>/);
const hostile = renderMarkdownHtml('| A |\n| --- |\n| ="<img src=x onerror=alert(1)>" |', new Map());
assert.doesNotMatch(hostile, /<img/);
assert.match(hostile, /#ERROR!/);
});
test("editing keeps formulas readable and code or explicit escapes literal", () => {
const doc = (text: string, marks?: { type: string }[]) => ({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text, marks }] }] });
assert.equal(tableCellMarkdown(doc("=SUM($B$2:C2)*50%")), "=SUM($B$2:C2)*50%");
assert.equal(tableCellMarkdown(doc("\\=1+2")), "\\=1+2");
assert.equal(tableCellMarkdown(doc("=1+2", [{ type: "code" }])), "`=1+2`");
});
test("the setting turns formulas off and back on without a change to the source", () => {
const source = "| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n";
assert.equal(get(tableFormulasEnabled), true, "Formulas are on by default");
assert.equal(activeTableFormulas(), tableFormulas);
const enabled = renderMarkdownHtml(source, new Map());
assert.match(enabled, />6<\/span>/);
setTableFormulasEnabled(false);
assert.equal(activeTableFormulas(), undefined);
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>/);
}
setTableFormulasEnabled(true);
assert.equal(renderMarkdownHtml(source, new Map()), enabled);
});
// Ported from the Table Formulas plugin (tests/render.test.ts).
test("rendering separates tables and preserves literal expressions", () => {
const markdown = new MarkdownIt();
const source = "| A | B |\n| --- | --- |\n| 3 | =A2*2 |\n\n| A | B |\n| --- | --- |\n| 4 | =A2+1 |\n\n| Literal |\n| --- |\n| `=1+2` |\n| \\=1+2 |\n";
const tokens = markdown.parse(source, {});
renderTableFormulas(tokens);
const html = markdown.renderer.render(tokens, markdown.options, {});
assert.match(html, /aria-label="=A2\*2 → 6">6<\/span>/);
assert.match(html, /aria-label="=A2\+1 → 5">5<\/span>/);
assert.match(html, /<code>=1\+2<\/code>/);
assert.equal((html.match(/class="md-table-formula"/g) || []).length, 2);
});
test("formula labels escape markup and report errors", () => {
const html = tableFormulaHtml({ formula: '=SUM("<img>")', text: "#ERROR!", error: "#ERROR!" });
assert.doesNotMatch(html, /<img>/);
assert.match(html, /&quot;&lt;img&gt;&quot;/);
assert.match(html, /md-table-formula is-error/);
assert.match(html, /Invalid formula syntax or function arguments/);
});
+120
View File
@@ -0,0 +1,120 @@
import assert from "node:assert/strict";
import test from "node:test";
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "../../../src/lib/editor/markdownTable.ts";
import { tableCellMarkdown, extractedCellMarkdown } from "../../../src/lib/editor/tableCellMarkdown.ts";
import { renderMarkdownHtml, renderMarkdownSections } from "../../../src/lib/workspace/noteHtml.ts";
const table = "| Ticker | Notes |\n| :--- | ---: |\n| IBKR.US | First<br>Second |";
test("prose directly after a table stays outside the table and its edit range", () => {
for (const eol of ["\n", "\r\n"]) {
const body = table.replaceAll("\n", eol);
const tail = `${eol}Plain text${eol}More text with an escaped \\| pipe${eol}# Heading`;
const source = body + tail;
assert.equal(parseMarkdownTable(source)?.end, body.length);
assert.equal(parseMarkdownTable(source)?.rows.length, 3);
assert.equal(appendTableRow(source), body + `${eol}| | |` + tail);
assert.equal(appendTableColumn(source), appendTableColumn(body) + tail);
assert.equal(replaceTableCell(source, 3, 0, "changed"), source);
const html = renderMarkdownHtml(source, new Map());
assert.equal((html.match(/<tr>/g) || []).length, 2);
assert.match(html, /<\/table>[\s\S]*<p>Plain text/);
const sections = renderMarkdownSections(source, new Map());
assert.equal(sections[0].end, body.length + eol.length);
assert.equal(source.slice(sections[1].start).startsWith("Plain text"), true);
}
});
test("table boundaries distinguish escaped pipes from delimiters and work in nested blocks", () => {
const body = "| A | B |\n| --- | --- |\nOne | Two\n| short |\n| escaped \\| pipe | value |\n| even \\\\| delimiter |";
assert.equal(parseMarkdownTable(body + "\nProse \\| literal")?.rows.length, 6);
assert.equal((renderMarkdownHtml(body + "\nProse \\| literal", new Map()).match(/<tr>/g) || []).length, 5);
assert.match(renderMarkdownHtml("> | A |\n> | --- |\n> | B |\n> Paragraph", new Map()), /<\/table>[\s\S]*<p>Paragraph<\/p>/);
assert.match(renderMarkdownHtml("- Item\n\n | A |\n | --- |\n | B |\n Paragraph", new Map()), /<\/table>[\s\S]*<p>Paragraph<\/p>/);
});
test("extracted cell text keeps formatting and literal code while converting actual line breaks", () => {
assert.equal(extractedCellMarkdown([
{ type: "text", text: "Title", marks: [{ type: "bold" }] },
{ type: "hardBreak" },
{ type: "text", text: "<br>", marks: [{ type: "code" }] },
]), "**Title**\n`<br>`");
});
test("table column insertion retains alignment and existing cell contents", () => {
assert.equal(appendTableColumn(table), "| Ticker | Notes | |\n| :--- | ---: | --- |\n| IBKR.US | First<br>Second | |");
});
test("table row insertion keeps existing source byte-for-byte", () => {
assert.equal(appendTableRow(table + "\n\n"), table + "\n| | |\n\n");
});
test("table edits preserve CRLF and optional outer pipes", () => {
const source = "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n";
assert.equal(appendTableRow(source), "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n| | |\r\n");
assert.equal(appendTableColumn(source), "| Name | Link | |\r\n| --- | :---: | --- |\r\n| One | [note](note.md) | |\r\n");
});
test("escaped pipes in text, wiki aliases, and inline code stay inside cells", () => {
const source = "| One | Two |\n| --- | --- |\n| [[note\\|Alias]] | `a\\|b` and text\\|value |";
const parsed = parseMarkdownTable(source)!;
assert.equal(parsed.rows[2].cells.length, 2);
const changed = appendTableColumn(source);
assert.ok(changed.includes("| [[note\\|Alias]] | `a\\|b` and text\\|value | |"));
for (const row of parsed.rows) for (const cell of row.cells) assert.equal(source.slice(cell.from, cell.to), cell.text);
});
test("adding columns pads short rows without losing extra source cells", () => {
const source = "| A | B |\n| --- | --- |\n| short |\n| a | b | extra |";
assert.equal(appendTableColumn(source), "| A | B | |\n| --- | --- | --- |\n| short | | |\n| a | b | | extra |");
});
test("table controls handle header-only and single-column tables", () => {
assert.equal(appendTableRow("| Header |\n| --- |"), "| Header |\n| --- |\n| |");
assert.equal(parseMarkdownTable(appendTableColumn("| Header |\n| --- |"))?.columns, 2);
});
test("invalid tables are unchanged", () => {
for (const source of ["Just text", "| A | B |\n| --- |", "| A |\n| not a delimiter |"] ) {
assert.equal(parseMarkdownTable(source), null);
assert.equal(appendTableColumn(source), source);
assert.equal(appendTableRow(source), source);
}
});
test("editing one cell preserves padding, alignment, other cells and CRLF", () => {
const source = " | Name | Notes |\r\n | :--- | ---: |\r\n | One | first<br />~~old~~ |\r\n\r\nTail";
assert.equal(replaceTableCell(source, 2, 1, "next<br>line\\|pipe"), source.replace("first<br />~~old~~", "next<br>line\\|pipe"));
assert.equal(replaceTableCell(source, 0, 0, "Title"), source.replace("Name", "Title"));
assert.equal(replaceTableCell(source, 1, 0, "bad"), source);
assert.equal(replaceTableCell(source, 2, 1, "break\nrow"), source);
});
test("editing an empty or omitted cell does not overwrite its neighbor", () => {
assert.equal(replaceTableCell("| A | B |\n| --- | --- |\n| short |", 2, 1, "new"), "| A | B |\n| --- | --- |\n| short | new |");
const source = "| A | B |\n| --- | --- |\n| | value |";
assert.equal(replaceTableCell(source, 2, 0, "new"), source.replace("| | value", "| new| value"));
});
test("rich cell serialization retains breaks, formatting, links and literal punctuation", () => {
const text = tableCellMarkdown({ type: "doc", content: [{ type: "paragraph", content: [
{ type: "text", text: "old", marks: [{ type: "strike" }] },
{ type: "hardBreak" },
{ type: "text", text: "bold", marks: [{ type: "bold" }] },
{ type: "text", text: " | *literal* <br> & value" },
{ type: "hardBreak" },
{ type: "text", text: "a|`b", marks: [{ type: "code" }] },
{ type: "text", text: "note", marks: [{ type: "link", attrs: { href: "note.md", "data-kind": "wiki" } }] },
{ type: "text", text: "web", marks: [{ type: "link", attrs: { href: "https://example.com/a(b)" } }] },
] }, { type: "paragraph", content: [{ type: "text", text: "Pasted paragraph" }] }] });
const source = `| A |\n| --- |\n| ${text} |`;
assert.equal(parseMarkdownTable(source)?.rows[2].cells.length, 1);
const html = renderMarkdownHtml(source, new Map());
assert.ok(html.includes("<s>old</s>"));
assert.ok(html.includes("<strong>bold</strong>"));
assert.ok(html.includes("| *literal* &lt;br&gt; &amp; value"));
assert.ok(html.includes("<code>a|`b</code>"));
assert.ok(html.includes('href="note.md" data-kind="wiki"'));
assert.ok(html.includes('href="https://example.com/a(b)"'));
assert.equal((html.match(/<br>/g) || []).length, 3);
});
+83
View File
@@ -0,0 +1,83 @@
import assert from "node:assert/strict";
import test from "node:test";
import { alignTableCells, clipboardCells, copyTableCells, copyTableMarkdown, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells } from "../../../src/lib/editor/tableSelection.ts";
import { htmlToMarkdown } from "../../../src/lib/workspace/htmlToMarkdown.ts";
import { parseMarkdownTable } from "../../../src/lib/editor/markdownTable.ts";
import { renderMarkdownHtml, plainInlineMarkdown } from "../../../src/lib/workspace/noteHtml.ts";
import { tableCellMarkdown } from "../../../src/lib/editor/tableCellMarkdown.ts";
const source = "| A | B | C |\r\n| --- | :---: | ---: |\r\n| one | two | three |\r\n| four | five | six |\r\n\r\nTail";
const range = { anchor: { row: 2, column: 1 }, head: { row: 1, column: 0 } };
test("selected cells retain table structure and line breaks through HTML clipboard", () => {
const source = "| Name | Notes |\n| --- | --- |\n| **Alpha** | First<br>Second |";
const range = { anchor: { row: 0, column: 0 }, head: { row: 1, column: 1 } };
const copied = copyTableMarkdown(source, range);
const pasted = htmlToMarkdown(renderMarkdownHtml(copied, new Map()));
const table = parseMarkdownTable(pasted)!;
assert.equal(table.columns, 2);
assert.equal(table.rows.length, 3);
assert.equal(table.rows[2].cells[0].text, "**Alpha**");
assert.equal(table.rows[2].cells[1].text, "First<br>Second");
});
test("reversed rectangular selections only change selected cells and preserve CRLF", () => {
const changed = formatTableCells(source, range, "bold");
assert.equal(changed, source.replace("one", "**one**").replace("two", "**two**").replace("four", "**four**").replace("five", "**five**"));
assert.equal(formatTableCells(changed, range, "bold"), source);
assert.equal(formatTableCells(source.replace("one", "**one**"), range, "bold"), changed);
assert.equal(copyTableCells(source, range), "one\ttwo\nfour\tfive");
assert.equal(alignTableCells(source, range, "left"), source.replace("| --- | :---: | ---: |", "| :--- | :--- | ---: |"));
});
test("all formats render and clear without interpreting escaped punctuation", () => {
const cell = { anchor: { row: 1, column: 0 }, head: { row: 1, column: 0 } };
for (const [format, html] of [["bold", "<strong>one</strong>"], ["italic", "<em>one</em>"], ["strike", "<s>one</s>"], ["highlight", "<mark>one</mark>"], ["code", "<code>one</code>"], ["math", 'class="md-inline-math">one</span>'], ["comment", 'class="md-inline-comment">one</span>']] as const) {
const changed = formatTableCells(source, cell, format);
assert.ok(renderMarkdownHtml(changed, new Map()).includes(html), format);
assert.equal(formatTableCells(changed, cell, "clear"), source);
}
assert.equal(plainInlineMarkdown("**bold** ==*highlight*== ~~strike~~ `a|b`<br>\\*literal\\*"), "bold highlight strike a\\|b<br>\\*literal\\*");
assert.equal(plainInlineMarkdown("**Photo** ![alt](image.png)"), "Photo ![alt](<image.png>)");
assert.ok(renderMarkdownHtml("`==not highlighted==` \\==literal\\==", new Map()).includes("<code>==not highlighted==</code>"));
for (const type of ["highlight", "math", "comment"]) {
const text = tableCellMarkdown({ type: "text", text: "a|b", marks: [{ type }] });
assert.equal(parseMarkdownTable(`| H |\n| --- |\n| ${text} |`)?.rows[2].cells.length, 1);
}
});
test("clipboard accepts Markdown and quoted TSV without splitting escaped pipes", () => {
assert.deepEqual(clipboardCells('"a\tb"\t"line 1\nline 2"\r\n"say ""hi"""\tx|y\r\n'), [["a\tb", "line 1<br>line 2"], ['say "hi"', "x\\|y"]]);
assert.deepEqual(clipboardCells("| A | B |\n| --- | --- |\n| a\\|b | `code` |"), [["A", "B"], ["a\\|b", "`code`"]]);
const pasted = pasteTableCells(source, range, "value");
assert.equal(copyTableCells(pasted, range), "value\tvalue\nvalue\tvalue");
const large = pasteTableCells(source, { anchor: { row: 2, column: 2 }, head: { row: 2, column: 2 } }, "a\tb\nc\td");
assert.equal(parseMarkdownTable(large)?.columns, 4);
assert.equal(parseMarkdownTable(large)?.rows.length, 5);
assert.ok(large.endsWith("\r\n\r\nTail"));
assert.equal(copyTableCells(large, { anchor: { row: 2, column: 2 }, head: { row: 3, column: 3 } }), "a\tb\nc\td");
});
test("clear preserves structure; delete removes whole rows/columns or shifts partial cells", () => {
assert.equal(copyTableCells(mapTableCells(source, range, () => ""), range), "\t\n\t");
assert.equal(copyTableCells(deleteTableCells(source, range), range), "three\t\nsix\t");
const rows = deleteTableCells(source, { anchor: { row: 1, column: 0 }, head: { row: 1, column: 2 } });
assert.equal(parseMarkdownTable(rows)?.rows.length, 3);
assert.ok(rows.includes("four")); assert.ok(!rows.includes("one"));
const columns = deleteTableCells(source, { anchor: { row: 0, column: 1 }, head: { row: 2, column: 1 } });
assert.equal(parseMarkdownTable(columns)?.columns, 2);
assert.ok(columns.includes("| one | three |"));
const header = deleteTableCells(source, { anchor: { row: 0, column: 0 }, head: { row: 0, column: 2 } });
assert.ok(header.startsWith("| one | two | three |\r\n| --- | :---: | ---: |"));
assert.equal(deleteTableCells(source, { anchor: { row: 0, column: 0 }, head: { row: 2, column: 2 } }), "\r\n\r\nTail");
});
test("deleting the empty columns shown on the card removes their structure", () => {
const emptyColumns = "| Column 2 | Column 1 | | | | |\n| --- | --- | --- | --- | --- | --- |\n| 2cm | Value | | | | |\n| text | 123 | | | | |\n| | | | | | |\n| | | | | | |\n\nAfter.";
const result = deleteTableCells(emptyColumns, { anchor: { row: 4, column: 5 }, head: { row: 0, column: 3 } });
assert.equal(parseMarkdownTable(result)?.columns, 3);
assert.equal(parseMarkdownTable(result)?.rows.length, 6);
assert.ok(result.includes("| 2cm | Value | |"));
assert.ok(result.endsWith("\n\nAfter."));
});
test("deleting the last body rows retains a valid header and alignment", () => {
const result = deleteTableCells(source, { anchor: { row: 2, column: 2 }, head: { row: 1, column: 0 } });
assert.equal(result, "| A | B | C |\r\n| --- | :---: | ---: |\r\n\r\nTail");
assert.equal(parseMarkdownTable(result)?.rows.length, 2);
});
+69
View File
@@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import test from "node:test";
import { changeTableStructure, moveTableAxis, sortTableColumn } from "../../../src/lib/editor/tableStructure.ts";
import { parseMarkdownTable } from "../../../src/lib/editor/markdownTable.ts";
const source = "| Name | Value |\r\n| :--- | ---: |\r\n| Zebra | `2` |\r\n| **Apple** | 10 |\r\n| apple | 3 |\r\n| | 1 |\r\n\r\nTail";
const values = (text: string) => parseMarkdownTable(text)!.rows.map(row => row.cells.map(cell => cell.text));
test("dragging rows across multiple positions preserves raw Markdown, header, CRLF and suffix", () => {
const moved = moveTableAxis(source, "row", 1, 4);
assert.deepEqual(values(moved).slice(2).map(row => row[0]), ["**Apple**", "apple", "", "Zebra"]);
assert.ok(moved.includes("| Zebra | `2` |\r\n\r\nTail"));
assert.equal(moveTableAxis(moved, "row", 4, 1), source);
for (const [from, to] of [[0, 2], [2, 0], [1, 5], [-1, 2], [1, 1], [1.5, 2], [1, NaN]]) {
assert.equal(moveTableAxis(source, "row", from, to), source);
}
});
test("dragging columns carries alignment and rich contents across ragged rows", () => {
const text = " | A | B | C |\r\n | :--- | :---: | ---: |\r\n | a\\|b | **bold**<br>line | [[note]] | extra |\r\n | short |\r\n\r\nTail";
const moved = moveTableAxis(text, "column", 0, 2);
assert.deepEqual(values(moved), [["B", "C", "A"], [":---:", "---:", ":---"], ["**bold**<br>line", "[[note]]", "a\\|b", "extra"], ["", "", "short"]]);
assert.ok(moved.endsWith("\r\n\r\nTail"));
assert.deepEqual(values(moveTableAxis(moved, "column", 2, 0)).slice(0, 3), values(text).slice(0, 3));
assert.equal(moveTableAxis(text, "column", 0, 3), text);
assert.equal(moveTableAxis("| H |\n| --- |", "column", 0, 0), "| H |\n| --- |");
assert.equal(moveTableAxis("invalid", "row", 1, 2), "invalid");
});
test("row insertion, movement and duplication preserve header, raw cells and CRLF", () => {
const inserted = changeTableStructure(source, "row", 1, "before");
assert.equal(inserted, source.replace("| Zebra", "| | |\r\n| Zebra"));
assert.equal(changeTableStructure(source, "row", 0, "after"), inserted);
assert.equal(changeTableStructure(source, "row", 0, "before"), source);
const moved = changeTableStructure(source, "row", 2, "previous");
assert.equal(moved, source.replace("| Zebra | `2` |\r\n| **Apple** | 10 |", "| **Apple** | 10 |\r\n| Zebra | `2` |"));
assert.equal(changeTableStructure(moved, "row", 1, "next"), source);
assert.equal(changeTableStructure(source, "row", 1, "previous"), source);
assert.equal(changeTableStructure(source, "row", 0, "next"), source);
assert.equal(changeTableStructure(source, "row", 4, "next"), source);
assert.equal(changeTableStructure(source, "row", 1, "duplicate"), source.replace("| Zebra | `2` |", "| Zebra | `2` |\r\n| Zebra | `2` |"));
assert.ok(changeTableStructure(source, "row", 1, "delete").endsWith("\r\n\r\nTail"));
});
test("column movement and duplication carry header, contents and alignment together", () => {
const moved = changeTableStructure(source, "column", 1, "previous");
assert.deepEqual(values(moved), values(source).map(row => row.toReversed()));
assert.deepEqual(values(changeTableStructure(moved, "column", 0, "next")), values(source));
assert.deepEqual(values(changeTableStructure(source, "column", 0, "duplicate")), values(source).map(row => [row[0], ...row]));
assert.deepEqual(values(changeTableStructure(source, "column", 1, "before")), values(source).map((row, i) => [row[0], i === 1 ? "---" : "", row[1]]));
assert.deepEqual(values(changeTableStructure(source, "column", 1, "delete")), values(source).map(row => [row[0]]));
assert.equal(changeTableStructure(source, "column", 0, "previous"), source);
assert.equal(changeTableStructure(source, "column", 1, "next"), source);
});
test("sort uses visible text and natural numbers, is stable, leaves blanks last and header intact", () => {
assert.deepEqual(values(sortTableColumn(source, 0)).slice(2).map(row => row[0]), ["**Apple**", "apple", "Zebra", ""]);
assert.deepEqual(values(sortTableColumn(source, 0, true)).slice(2).map(row => row[0]), ["Zebra", "**Apple**", "apple", ""]);
assert.deepEqual(values(sortTableColumn(source, 1)).slice(2).map(row => row[1]), ["1", "`2`", "3", "10"]);
const sorted = sortTableColumn(source, 1, true);
assert.ok(sorted.startsWith("| Name | Value |\r\n| :--- | ---: |"));
assert.ok(sorted.includes("| Zebra | `2` |"));
assert.ok(sorted.endsWith("\r\n\r\nTail"));
});
test("header-only, ragged and single-column tables remain valid through operations", () => {
const header = "| H |\n| --- |";
assert.equal(changeTableStructure(header, "row", 0, "duplicate"), header + "\n| H |");
assert.equal(changeTableStructure(header, "column", 0, "delete"), "");
assert.equal(changeTableStructure(header, "row", 0, "delete"), "");
assert.equal(sortTableColumn(header, 0), header);
const ragged = "| A | B |\n| --- | --- |\n| short |\n| a\\|b | two | extra |";
assert.deepEqual(values(changeTableStructure(ragged, "column", 1, "previous"))[3], ["two", "a\\|b", "extra"]);
assert.equal(changeTableStructure("invalid", "row", 0, "after"), "invalid");
});
+86
View File
@@ -0,0 +1,86 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { SYNTAX_ROLES } from '../../../src/lib/theme/roles.ts';
import { parseAppearance, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, THEMES, themeModes } from '../../../src/lib/theme/appearance.ts';
test('Removed palettes preserve the saved mode with the default palette', () => {
for (const theme of ['gpt', 'terminal', 'unknown', 'renamon', 'asuka-school']) {
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme: 'default', mode });
}
}
assert.deepEqual(THEMES, ['default', 'claude', 'sakura', 'harvest-moon', 'crimson-pilot', 'silver-serpent']);
assert.deepEqual(BUILTIN_THEMES.map(theme => theme.id), THEMES);
});
test('Renamed palettes preserve saved choices and backgrounds', () => {
const newTabBackground = { imageId: '01234567-89ab-cdef-0123-456789abcdef', position: 'top left', size: 'auto', overlay: -0.4 };
for (const [previous, theme] of [['holo', 'harvest-moon'], ['asuka', 'crimson-pilot'], ['malfoid', 'silver-serpent']]) {
for (const mode of ['light', 'dark']) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme: previous, mode, newTabBackground })), { theme, mode: 'dark', newTabBackground });
}
}
for (const theme of ['constructor', '__proto__', 'toString']) {
assert.deepEqual(normalizeAppearance({ theme, mode: 'light' }), { theme: 'default', mode: 'light' });
}
});
test('Removed character themes retain the saved background', () => {
const newTabBackground = { imageId: '01234567-89ab-cdef-0123-456789abcdef', position: 'top left', size: 'auto', overlay: -0.4 };
for (const theme of ['renamon', 'asuka-school']) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode: 'light', newTabBackground })), { theme: 'default', mode: 'light', newTabBackground });
}
});
// tests/unit/theme/contrast.spec.ts checks the readability of every palette.
test('Single-mode palettes restore their one appearance and export a valid theme', () => {
for (const { id } of BUILTIN_THEMES.filter(item => themeModes(item.id).length === 1)) {
const [only] = themeModes(id);
const exported = exportAppearanceTheme(id);
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme: id, mode })), { theme: id, mode: only });
}
assert.equal(exported.schema, 3);
assert.deepEqual(parseCustomTheme(exported), exported);
for (const role of SYNTAX_ROLES) assert.match(exported.colors[`syntax-${role}`] ?? '', /^#[0-9a-f]{6}$/);
assert.notDeepEqual(exported.colors, exportAppearanceTheme('default').colors);
}
});
test('Sakura cannot restore or save a dark appearance', () => {
assert.deepEqual(parseAppearance('{"theme":"sakura","mode":"dark"}'), { theme: 'sakura', mode: 'light' });
assert.deepEqual(normalizeAppearance({ theme: 'sakura', mode: 'dark' }), { theme: 'sakura', mode: 'light' });
});
test('Malformed storage returns a valid default appearance', () => {
for (const raw of [null, '', '{', 'null', '42', '[]']) {
assert.deepEqual(parseAppearance(raw), { theme: 'default', mode: 'dark' });
}
});
test('Saved image layout restores valid choices and rejects CSS injection', () => {
const imageId = '01234567-89ab-cdef-0123-456789abcdef';
const restored = parseAppearance(JSON.stringify({ newTabBackground: { imageId, position: 'top left', size: 'auto', overlay: -0.4 } }));
assert.deepEqual(restored.newTabBackground, { imageId, position: 'top left', size: 'auto', overlay: -0.4 });
const invalid = normalizeAppearance({ newTabBackground: { imageId, position: 'url(https://example.com)', size: '100000px', overlay: Infinity } });
assert.deepEqual(invalid.newTabBackground, { imageId, position: 'center', size: 'cover', overlay: 0 });
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId } }).newTabBackground, { imageId, overlay: 0, position: 'center', size: 'cover' });
});
test('New tab backgrounds keep supported image data and reject active or remote content', () => {
const value = { theme: 'claude', mode: 'light', newTabBackground: { image: 'data:image/png;base64,YQ==', overlay: 0, position: 'center', size: 'cover' } };
assert.deepEqual(parseAppearance(JSON.stringify(value)), value);
for (const image of ['https://example.com/photo.png', 'javascript:alert(1)', 'data:image/svg+xml;base64,YQ==', 'data:image/png;base64,' + 'A'.repeat(3_000_000)]) {
assert.equal(normalizeAppearance({ ...value, newTabBackground: { color: '#224466', image } }).newTabBackground, undefined);
}
assert.equal(normalizeAppearance({ ...value, newTabBackground: { color: 'red' } }).newTabBackground, undefined);
assert.equal(normalizeAppearance({ ...value, newTabBackground: undefined }).newTabBackground, undefined);
});
test('Background image references clamp the overlay and discard obsolete colors', () => {
const imageId = 'd10adda6-a2ec-4d73-a0a6-2cb1ed43bebc';
const layout = { position: 'center', size: 'cover' };
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, color: '#224466', overlay: 3 } }).newTabBackground, { imageId, overlay: 1, ...layout });
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: -3 } }).newTabBackground, { imageId, overlay: -1, ...layout });
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: NaN } }).newTabBackground, { imageId, overlay: 0, ...layout });
assert.equal(normalizeAppearance({ newTabBackground: { imageId: 'invalid' } }).newTabBackground, undefined);
});
+159
View File
@@ -0,0 +1,159 @@
import test from 'node:test';
import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
import { BackgroundHub, backgroundHub } from '../../../src/lib/plugins/backgrounds.ts';
import { ExternalSession } from '../../../src/lib/plugins/externalSession.ts';
import type { PluginApi } from '../../../src/lib/plugins/sdk.ts';
import type { BackgroundFrame } from '../../../src/lib/plugins/backgroundContracts.ts';
const frame: BackgroundFrame = { url: 'blob:http://localhost/example', overlay: 0.3, position: 'center', size: 'cover' };
test('frames retain ownership, reveal earlier owners, and cannot mutate hub state', () => {
const hub = new BackgroundHub(() => undefined);
const first = Symbol(), second = Symbol();
const events: string[] = [];
hub.subscribe(target => events.push(target));
hub.set(first, 'pm-all', frame);
const received = hub.get('pm-all')!;
received.url = 'blob:changed';
assert.equal(hub.get('pm-all')!.url, frame.url);
hub.set(second, 'pm-all', { ...frame, overlay: -0.4 });
hub.set(first, 'app', frame);
assert.equal(hub.get('pm-all')!.overlay, -0.4);
hub.removeOwner(second);
assert.equal(hub.get('pm-all')!.overlay, 0.3);
hub.removeOwner(first);
assert.equal(hub.get('pm-all'), null);
assert.equal(hub.get('app'), null);
assert.deepEqual(events, ['pm-all', 'pm-all', 'app', 'pm-all', 'pm-all', 'app']);
});
test('app override uses body properties and removes them without changing current root appearance', () => {
const root = new Map([['--rs-background-image', 'saved image']]);
const properties = new Map<string, string>();
const style = {
getPropertyValue: (key: string) => properties.get(key) ?? '',
getPropertyPriority: () => '',
setProperty: (key: string, value: string) => properties.set(key, value),
removeProperty: (key: string) => { properties.delete(key); },
};
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement);
const owner = Symbol();
hub.set(owner, 'app', frame);
assert.match(properties.get('--rs-background-image')!, /blob:http/);
assert.equal(properties.get('--rs-workarea-surface-opacity'), 'var(--rs-surface-opacity, 82%)');
assert.equal(properties.get('--rs-workarea-plugin-bg'), 'var(--rs-transparent-plugin-bg, transparent)');
root.set('--rs-background-image', 'new saved image');
hub.set(owner, 'app', { ...frame, overlay: -0.5, size: 'contain' });
assert.match(properties.get('--rs-background-image')!, /255,255,255,0.5/);
hub.removeOwner(owner);
assert.equal(properties.size, 0);
assert.equal(root.get('--rs-background-image'), 'new saved image');
});
test('invalid frames and targets do not enter the hub', () => {
const hub = new BackgroundHub(() => undefined), owner = Symbol();
for (const target of ['pm-board:../../x', 'unknown', 'pm-board:']) assert.throws(() => hub.set(owner, target, frame), /target/);
for (const invalid of [{ ...frame, url: 'https://example.com/image.png' }, { ...frame, blurredUrl: 'https://example.com/image.png' }, { ...frame, blurredUrl: 'blob:bad")' }, { ...frame, overlay: NaN }, { ...frame, overlay: 2 }, { ...frame, url: 'blob:bad")' }]) {
assert.throws(() => hub.set(owner, 'app', invalid), /frame/);
}
hub.set(owner, 'pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1', frame);
hub.removeOwner(owner);
});
test('portrait frames retain a contained foreground and cover underlay through transitions and cleanup', () => {
const properties = new Map<string, string>();
const style = { getPropertyValue: (key: string) => properties.get(key) ?? '', getPropertyPriority: () => '',
setProperty: (key: string, value: string) => properties.set(key, value), removeProperty: (key: string) => properties.delete(key) };
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement), owner = Symbol();
hub.set(owner, 'app', { ...frame, size: 'contain', blurredUrl: 'blob:blurred', previous: frame, transitionMs: 2000 });
assert.equal(properties.get('--rs-background-layer-sizes'), '100% 100%, contain, cover');
assert.equal(properties.get('--rs-background-layer-positions'), 'center, center, center');
assert.equal(properties.get('--rs-background-previous-layer-sizes'), '100% 100%, cover');
assert.match(properties.get('--rs-background-image')!, /blob:blurred/);
const received = hub.get('app')!;
received.blurredUrl = 'blob:changed';
assert.equal(hub.get('app')!.blurredUrl, 'blob:blurred');
hub.removeOwner(owner);
assert.equal(properties.size, 0);
});
test('fade frames validate previous images and keep nested data private', () => {
const hub = new BackgroundHub(() => undefined), owner = Symbol();
const fading = { ...frame, previous: { ...frame, url: 'blob:previous' }, transitionMs: 800 };
hub.set(owner, 'pm-all', fading);
fading.previous.url = 'blob:mutated';
const received = hub.get('pm-all')!;
assert.equal(received.previous!.url, 'blob:previous');
received.previous!.url = 'blob:changed';
assert.equal(hub.get('pm-all')!.previous!.url, 'blob:previous');
for (const invalid of [
{ ...frame, previous: { ...frame, url: 'https://example.com/image.png' } },
{ ...frame, transitionMs: NaN }, { ...frame, transitionMs: -1 }, { ...frame, transitionMs: 5001 },
]) assert.throws(() => hub.set(owner, 'pm-all', invalid), /frame/);
});
test('subscriber errors do not prevent frame cleanup or remaining notifications', () => {
const hub = new BackgroundHub(() => undefined), owner = Symbol();
let events = 0;
hub.subscribe(() => { throw new Error('Subscriber failure'); });
hub.subscribe(() => { events++; });
hub.set(owner, 'pm-all', frame);
hub.removeOwner(owner);
assert.equal(events, 2);
assert.equal(hub.get('pm-all'), null);
});
test('plugins get no background API, and the frames stay with the host', async () => {
let api!: PluginApi;
const session = new ExternalSession('org.test.backgrounds', {
workspace: { list: async () => [], read: async () => '', write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
// Project Management was the last plugin user of `api.backgrounds`. It reads `backgroundHub` as a native feature.
assert.equal('backgrounds' in api, false);
const owner = Symbol();
backgroundHub.set(owner, 'pm-all', frame);
await session.stop();
assert.deepEqual(backgroundHub.get('pm-all'), frame);
backgroundHub.removeOwner(owner);
});
test('the Background commands are allowed in the windows that use them, and the old plugin commands are gone', () => {
const build = readFileSync(new URL('../../../src-tauri/build.rs', import.meta.url), 'utf8');
const all = ['background_choose_folder', 'background_folder', 'background_clear_folder', 'background_list', 'background_read', 'background_read_sidecar', 'background_write_sidecar', 'background_migrate'];
const scopes: Record<string, string[]> = { default: all, settings: all, browser: ['background_folder', 'background_list', 'background_read', 'background_read_sidecar'] };
for (const [scope, commands] of Object.entries(scopes)) {
const capability = JSON.parse(readFileSync(new URL(`../../../src-tauri/capabilities/${scope}.json`, import.meta.url), 'utf8'));
for (const command of all) {
assert(build.includes(`"${command}"`), `${command} needs a generated desktop permission`);
assert.equal(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), commands.includes(command), `${scope} and ${command}`);
}
assert.equal(capability.permissions.some((permission: string) => permission.startsWith('allow-backgrounds-')), false, `${scope} has no old plugin command`);
}
assert.equal(/"backgrounds_/.test(build), false);
});
test('a new app frame changes only the custom properties with a new value', () => {
const writes: string[] = [];
const properties = new Map<string, string>();
const style = { getPropertyValue: (key: string) => properties.get(key) ?? '', getPropertyPriority: () => '',
setProperty: (key: string, value: string) => { writes.push(key); properties.set(key, value); }, removeProperty: (key: string) => { properties.delete(key); } };
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement), owner = Symbol();
hub.set(owner, 'app', frame);
assert.equal(writes.length, 20);
writes.length = 0;
hub.set(owner, 'app', { ...frame, url: 'blob:http://localhost/second' });
assert.deepEqual(writes, ['--rs-background-image']);
writes.length = 0;
hub.set(owner, 'app', { ...frame, url: 'blob:http://localhost/second' });
assert.deepEqual(writes, [], 'The same frame writes nothing');
hub.removeOwner(owner);
assert.equal(properties.size, 0);
writes.length = 0;
hub.set(owner, 'app', frame);
assert.equal(writes.length, 20, 'After a removal, the next frame writes every property again');
hub.removeOwner(owner);
});
+101
View File
@@ -0,0 +1,101 @@
// Character palettes: WCAG contrast of text and syntax colors on opaque and image-tinted surfaces, plus per-theme palette rules.
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts';
import { SYNTAX_ROLES, resolveColors } from '../../../src/lib/theme/roles.ts';
import { SURFACES, appliedColors } from '../../../src/lib/theme/contrast.ts';
/** Every role of a dark character palette, with the derived roles. */
function characterTheme(theme: string) {
const palette = BUILTIN_THEMES.find(item => item.id === theme);
return palette && 'dark' in palette.variants ? resolveColors(palette.variants.dark, 'dark') : undefined;
}
const rgb = (color: string) => color.slice(1).match(/../g)!.map(value => parseInt(value, 16));
const mix = (foreground: string, background: string, opacity: number) => '#' + rgb(foreground)
.map((value, index) => Math.round(value * opacity + rgb(background)[index] * (1 - opacity)).toString(16).padStart(2, '0')).join('');
function luminance(color: string) {
return rgb(color).map(value => value / 255)
.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4)
.reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);
}
function contrast(foreground: string, background: string) {
const [high, low] = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (high + 0.05) / (low + 0.05);
}
/** Named foreground groups and surfaces of a palette. Image surfaces are tinted over a white image. */
function roles(theme: string) {
const palette = characterTheme(theme)!;
const { bg, 'bg-elevated': elevated, 'bg-active': active, 'text-dim': dim, text, 'text-strong': strong, accent } = palette;
// The app draws text selection at most 65% opaque over the page (UI-029).
const selection = SURFACES.selection(appliedColors(palette));
const editorOnWhite = mix(bg, '#ffffff', 0.9);
const panelOnWhite = mix(elevated, '#ffffff', 0.82);
const foregrounds = {
ui: { dim, text, strong },
accents: { accent, secondary: palette['accent-2'] },
// A menu or pane row shows interface text and the main accent. Syntax and the second accent show only in documents.
rows: { dim, text, strong, accent },
syntax: Object.fromEntries(SYNTAX_ROLES.map(role => [`syntax-${role}`, palette[`syntax-${role}`]])),
};
const surfaces = {
bg, elevated, active, selection, editorOnWhite, panelOnWhite,
codeBlockOnWhite: mix(elevated, editorOnWhite, 0.82),
// Over an image, a hovered menu or pane row is a 6% veil of text-strong on the tinted panel (UI-061).
hoverOnWhite: mix(strong, panelOnWhite, 0.06),
controlHoverOnWhite: mix(active, '#ffffff', 0.92),
};
return { foregrounds, surfaces };
}
type Roles = ReturnType<typeof roles>;
type Check = [foregrounds: (keyof Roles['foregrounds'])[], surfaces: (keyof Roles['surfaces'])[]];
// Every listed foreground needs 4.5:1 contrast on every listed surface.
const readable: { theme: string; name: string; checks: Check[] }[] = [
{ theme: 'harvest-moon', name: 'Harvest Moon', checks: [
[['ui', 'accents'], ['bg', 'elevated', 'active', 'selection']],
[['syntax'], ['bg', 'elevated', 'selection']],
] },
{ theme: 'crimson-pilot', name: 'Crimson Pilot', checks: [
[['ui', 'accents', 'syntax'], ['bg', 'elevated', 'active', 'selection']],
[['syntax'], ['editorOnWhite', 'codeBlockOnWhite']],
[['ui'], ['panelOnWhite']],
] },
{ theme: 'silver-serpent', name: 'Silver Serpent', checks: [
[['ui', 'accents', 'syntax'], ['bg', 'elevated', 'active', 'selection', 'panelOnWhite', 'editorOnWhite', 'controlHoverOnWhite', 'codeBlockOnWhite']],
[['rows'], ['hoverOnWhite']],
] },
];
for (const { theme, name, checks } of readable) {
test(`${name} text and syntax remain readable on opaque and image surfaces`, () => {
const { foregrounds, surfaces } = roles(theme);
for (const [groups, surfaceNames] of checks) {
for (const [role, foreground] of groups.flatMap(group => Object.entries(foregrounds[group]))) {
for (const surface of surfaceNames) {
assert(contrast(foreground, surfaces[surface]) >= 4.5, `${role} ${foreground} on ${surface} ${surfaces[surface]} needs 4.5:1 contrast`);
}
}
}
});
}
test('Harvest Moon uses the warm character colors for all palette roles', () => {
const palette = characterTheme('harvest-moon')!;
const identity = ['bg', 'bg-elevated', 'bg-active', 'border', 'text', 'text-dim', 'text-strong', 'accent', 'accent-2', 'selection', ...SYNTAX_ROLES.map(role => `syntax-${role}` as const)] as const;
for (const role of identity) {
const color = palette[role];
assert.match(color, /^#[0-9a-f]{6}$/i);
const [red, green, blue] = rgb(color);
assert(red >= green && green >= blue, `${role} ${color} must follow the copper, amber, red, or cream palette`);
}
assert.deepEqual(Object.keys(BUILTIN_THEMES.find(item => item.id === 'harvest-moon')!.variants), ['dark']);
});
test('Silver Serpent selection has a readable perimeter and a separate fill', () => {
const { surfaces: { bg, elevated, selection }, foregrounds: { accents: { accent } } } = roles('silver-serpent');
assert(contrast(accent, selection) >= 3, 'selection perimeter');
assert(contrast(selection, bg) >= 1.5, 'selection against the editor');
assert(contrast(selection, elevated) >= 1.5, 'selection against a panel');
});
+56
View File
@@ -0,0 +1,56 @@
// Readability rules for every built-in theme (src/lib/theme/contrast.ts), and the rule that only theme data names a theme.
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts';
import { BASE_ROLES, resolveColors, type Mode } from '../../../src/lib/theme/roles.ts';
import { RULES, checkTheme } from '../../../src/lib/theme/contrast.ts';
import { composite, contrast, distance, formatHex, mix, parseHex } from '../../../src/lib/theme/color.ts';
const variants = BUILTIN_THEMES.flatMap(theme => Object.entries(theme.variants).map(([mode, colors]) => ({ key: `${theme.id}/${mode}`, mode: mode as Mode, colors: colors! })));
for (const variant of variants) {
const findings = checkTheme(resolveColors(variant.colors, variant.mode), variant.mode);
for (const rule of RULES) {
const results = findings.filter(finding => finding.rule === rule.id);
if (!results.length) continue;
const failures = results.filter(finding => !finding.pass).map(finding => `${finding.subject}: ${finding.value.toFixed(2)} (minimum ${finding.min})`);
test(`${variant.key} passes the ${rule.id} rule`, () => {
assert.deepEqual(failures, []);
});
}
}
test('Every built-in variant gives all base roles as hex colors', () => {
for (const variant of variants) {
for (const role of BASE_ROLES) assert.match(variant.colors[role] ?? '', /^#[0-9a-f]{6}$/, `${variant.key}: ${role}`);
}
});
test('Color arithmetic matches CSS and WCAG', () => {
assert.deepEqual(parseHex('#0f08'), [0, 255, 0, 136 / 255]);
assert.equal(formatHex([255, 0, 0, 1]), '#ff0000');
assert.equal(mix('#82aaff', '#141414', 0.8), '#6c8cd0');
assert.equal(mix('#82aaff', '#0000', 0.2), '#82aaff33');
assert.equal(composite('#ffffff80', '#000000'), '#808080');
assert.equal(contrast('#000000', '#ffffff').toFixed(1), '21.0');
assert(distance('#ff0000', '#ff0000') === 0 && distance('#000000', '#ffffff') > 0.99);
});
test('Only theme data names a theme ID', () => {
const root = fileURLToPath(new URL('../../../src', import.meta.url));
const ids = BUILTIN_THEMES.flatMap(theme => [theme.id, ...('legacyIds' in theme ? theme.legacyIds : [])]).filter(id => id !== 'default');
const pattern = new RegExp(`(['"\`])(?:${ids.join('|')})\\1|data-palette=`);
const files = (function walk(folder: string): string[] {
return readdirSync(folder).flatMap(name => {
const path = join(folder, name);
return statSync(path).isDirectory() ? walk(path) : /\.(ts|svelte|css)$/.test(name) ? [path] : [];
});
})(root);
const found = files.filter(file => !relative(root, file).startsWith(join('lib', 'theme', 'themes')) && !file.endsWith('messages.ts'))
.filter(file => pattern.test(readFileSync(file, 'utf8')))
.map(file => relative(root, file));
assert.deepEqual(found, []);
});
+149
View File
@@ -0,0 +1,149 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { ROLES } from '../../../src/lib/theme/roles.ts';
import { BUILTIN_THEMES as THEME_DATA } from '../../../src/lib/theme/themes/index.ts';
import { applyTransparency, normalizeAppearance, exportAppearanceTheme, resolveTheme, BUILTIN_THEMES, themeModes } from '../../../src/lib/theme/appearance.ts';
const palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' };
const theme = { schema: 2, id: 'my-theme', name: 'My theme', colors: palette };
test('Schema 2 palettes convert to schema 3 and retain all supplied colors', () => {
assert.deepEqual(parseCustomTheme(theme), { ...theme, schema: 3, mode: 'dark' });
assert.equal(parseCustomTheme({ ...theme, colors: { ...palette, bg: '#fafafa' } }).mode, 'light');
});
test('Old syntax names convert to the schema 3 roles', () => {
const colors = { ...palette, 'syntax-local': '#111111', 'syntax-instance': '#222222', 'syntax-global': '#333333', 'syntax-parameter': '#444444', 'syntax-static': '#555555', 'syntax-keyword': '#666666' };
assert.deepEqual(parseCustomTheme({ ...theme, colors }).colors, {
...palette, 'syntax-variable': '#111111', 'syntax-property': '#222222', 'syntax-constant': '#333333', 'syntax-punctuation': '#333333', 'syntax-keyword': '#666666',
});
assert.throws(() => parseCustomTheme({ ...theme, colors: { ...palette, 'syntax-variable': '#111111' } }), /Unknown theme color/);
});
test('Schema 3 files name their mode and can take missing colors from a built-in base', () => {
const file = { schema: 3, id: 'amber', name: 'Amber', mode: 'dark', base: 'holo', colors: { accent: '#00ff00', 'ansi-blue': '#0000ff' } };
assert.deepEqual(parseCustomTheme(file), { ...file, base: 'harvest-moon' });
assert.deepEqual(parseCustomTheme({ ...file, base: undefined, colors: {} }), { schema: 3, id: 'amber', name: 'Amber', mode: 'dark', colors: {} });
for (const invalid of [{ mode: 'dim' }, { mode: undefined }, { base: 'sakura' }, { base: 'unknown' }, { base: 4 }, { colors: [] }, { colors: { 'accent-x': '#000' } }, { colors: { accent: 'red' } }]) {
assert.throws(() => parseCustomTheme({ ...file, ...invalid }), JSON.stringify(invalid));
}
const previous = globalThis.localStorage;
try {
const stored = new Map([['runestone.custom-themes', JSON.stringify([file])]]);
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage;
const resolved = resolveTheme('custom:amber', 'light');
const harvest = THEME_DATA.find(item => item.id === 'harvest-moon')!;
assert.equal(resolved.mode, 'dark');
assert.equal(resolved.colors.bg, harvest.variants.dark.bg);
assert.equal(resolved.colors.accent, '#00ff00');
assert.equal(resolved.colors['syntax-keyword'], harvest.variants.dark['syntax-keyword']);
assert.equal(resolved.colors.link, '#00ff00', 'A derived role follows the colors of the file');
assert.equal(resolved.colors['ansi-blue'], '#0000ff');
assert.match(resolved.fonts.ui, /Candara/);
assert.deepEqual(themeModes('custom:amber'), ['dark']);
} finally { globalThis.localStorage = previous; }
});
test('Legacy import selects the current appearance and validates both palettes', () => {
const light = { ...palette, bg: '#fff' };
const legacy = { schema: 1, id: theme.id, name: theme.name, light, dark: palette };
assert.deepEqual(parseCustomTheme(legacy).colors, palette);
assert.deepEqual(parseCustomTheme(legacy, 'light').colors, light);
assert.throws(() => parseCustomTheme({ ...legacy, light: {} }));
});
test('Theme files reject CSS injection, unknown tokens, and incomplete palettes', () => {
for (const colors of [{ ...palette, bg: 'url(https://invalid.test)' }, { ...palette, position: 'fixed' }, { bg: '#000' }, []]) {
assert.throws(() => parseCustomTheme({ ...theme, colors }));
}
assert.throws(() => parseCustomTheme({ ...theme, id: '../unsafe' }));
});
test('Every built-in template contains every role and one palette', () => {
for (const item of BUILTIN_THEMES) for (const mode of themeModes(item.id)) {
const exported = exportAppearanceTheme(item.id, mode);
assert.deepEqual(Object.keys(exported.colors), [...ROLES]);
assert.equal(exported.mode, mode);
assert.deepEqual(parseCustomTheme(exported), exported);
assert.equal('light' in exported, false);
assert.equal('dark' in exported, false);
}
assert.notDeepEqual(exportAppearanceTheme('default', 'light').colors, exportAppearanceTheme('default', 'dark').colors);
});
test('Transparency normalizes old, invalid, and extreme saved values', () => {
assert.equal(normalizeAppearance(null).transparency, undefined);
assert.deepEqual(normalizeAppearance({ transparency: { enabled: false, amount: 27 } }).transparency, { enabled: false, amount: 27 });
for (const [amount, expected] of [[-10, 0], [55, 55], [100, 100], [120, 100], [NaN, 18], [Infinity, 18], [12.8, 13]]) {
assert.equal(normalizeAppearance({ transparency: { amount } }).transparency?.amount, expected);
}
});
test('Theme font roles round-trip and reject CSS injection', () => {
const fonts = { ui: 'Arial, sans-serif', prose: '"Times New Roman", serif', heading: 'Georgia, serif', mono: 'Consolas, monospace' };
assert.deepEqual(parseCustomTheme({ ...theme, fonts }).fonts, fonts);
for (const fonts of [{ ui: 'url(https://example.test)' }, { ui: 'Arial; color: red' }, { unknown: 'Arial' }, { ui: '' }, { ui: 'Arial,,serif' }, { ui: '"Arial' }, []]) {
assert.throws(() => parseCustomTheme({ ...theme, fonts }));
}
for (const item of BUILTIN_THEMES) {
const exported = exportAppearanceTheme(item.id);
assert.deepEqual(Object.keys(exported.fonts!).sort(), ['heading', 'mono', 'prose', 'ui']);
assert.deepEqual(parseCustomTheme(exported), exported);
}
assert.match(exportAppearanceTheme('claude').fonts!.heading!, /Poppins/);
assert.match(exportAppearanceTheme('harvest-moon').fonts!.ui!, /Candara/);
});
test('Full transparency range produces valid surface opacity values', () => {
const values = new Map<string, string>();
const root = { dataset: {}, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement;
for (const amount of [0, 18, 40, 55, 99, 100]) {
applyTransparency({ enabled: true, amount }, root);
assert.equal(values.get('--rs-surface-opacity'), `${100 - amount}%`);
for (const key of ['--rs-surface-opacity', '--rs-editor-surface-opacity', '--rs-hover-surface-opacity']) {
const opacity = parseFloat(values.get(key)!);
assert(opacity >= 0 && opacity <= 100);
}
}
});
test('Opaque mode retains background ownership and the amount for re-enabling', () => {
const values = new Map<string, string>();
const root = { dataset: {} as Record<string, string>, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement;
applyTransparency({ enabled: false, amount: 32 }, root);
assert.equal(values.get('--rs-surface-opacity'), '100%');
assert.equal(values.get('--rs-editor-surface-opacity'), '100%');
assert.equal(values.get('--rs-transparent-plugin-bg'), 'transparent');
assert.equal(root.dataset.transparency, 'off');
applyTransparency({ enabled: true, amount: 18 }, root);
assert.equal(values.get('--rs-surface-opacity'), '82%');
assert.equal(values.get('--rs-editor-surface-opacity'), '90%');
assert.equal(root.dataset.transparency, 'on');
});
test('Saved legacy light themes migrate once and preserve both original palettes', async () => {
const { customThemes, CUSTOM_THEMES_KEY } = await import('../../../src/lib/theme/customThemes.ts');
const { migrateLegacyPreferences } = await import('../../../src/lib/settings/migration.ts');
const { LEGACY_KEYS } = await import('../../../src/lib/settings/store.ts');
const legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } };
const old = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]);
const sections = migrateLegacyPreferences(key => old.get(key) ?? null);
assert.equal((sections.customThemes as { schema: number }[])[0].schema, 3);
assert.deepEqual(sections.customThemesLegacy, [legacy]);
assert.deepEqual(sections.appearance, { theme: 'custom:saved-light', mode: 'light' });
// The browser preview store reads the sections from their old keys.
const stored = new Map(Object.entries(sections).map(([section, value]) => [LEGACY_KEYS[section as keyof typeof LEGACY_KEYS], JSON.stringify(value)]));
const previous = globalThis.localStorage;
try {
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage;
assert.deepEqual(customThemes()[0].colors, legacy.light);
assert.deepEqual(themeModes('custom:saved-light'), ['light']);
assert.equal(normalizeAppearance({ theme: 'custom:saved-light', mode: 'dark' }).mode, 'light');
assert.deepEqual(exportAppearanceTheme('custom:saved-light').colors.bg, '#fff');
assert.deepEqual(customThemes('dark')[0].colors, legacy.light, 'The converted theme keeps its palette in both modes');
} finally { globalThis.localStorage = previous; }
});
test('Reading custom themes never writes, and an unconverted version 1 theme uses the requested palette', async () => {
const { customThemes, CUSTOM_THEMES_KEY } = await import('../../../src/lib/theme/customThemes.ts');
const legacy = { schema: 1, id: 'quota-light', name: 'Quota light', light: { ...palette, bg: '#fefefe' }, dark: palette };
const previous = globalThis.localStorage;
try {
globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? JSON.stringify([legacy]) : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage;
assert.deepEqual(customThemes('light')[0].colors, legacy.light);
assert.deepEqual(customThemes('dark')[0].colors, palette);
assert.deepEqual(customThemes()[0].colors, palette, 'Without a saved appearance, the dark palette applies');
} finally { globalThis.localStorage = previous; }
});
+47
View File
@@ -0,0 +1,47 @@
// The theme editor model (src/lib/theme/themeEditor.ts): role groups, drafts, saved files, and the results of each role.
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { ROLE_GROUPS, builtinDraft, customDraft, draftColors, draftFindings, draftTheme, roleStatus, uniqueThemeId } from '../../../src/lib/theme/themeEditor.ts';
import { ROLES, resolveColors } from '../../../src/lib/theme/roles.ts';
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts';
test('The editor groups show every role once', () => {
const shown = ROLE_GROUPS.flatMap(group => group.roles);
assert.equal(new Set(shown).size, shown.length);
assert.deepEqual([...shown].sort(), [...ROLES].sort());
});
test('A built-in draft has the colors of its theme', () => {
for (const theme of BUILTIN_THEMES) for (const [mode, colors] of Object.entries(theme.variants)) {
const draft = builtinDraft(theme.id, mode as 'light' | 'dark', theme.name);
assert.deepEqual(draftColors(draft), resolveColors(colors!, mode as 'light' | 'dark'));
}
});
test('A saved draft is a short schema 3 theme that the parser accepts and that keeps its colors', () => {
const draft = { ...builtinDraft('harvest-moon', 'dark', 'Harvest Moon copy'), overrides: { accent: '#00c8ff', selection: '#20406080' } };
const theme = draftTheme(draft, 'harvest-moon-copy', 'Harvest Moon copy');
assert.deepEqual(theme, { schema: 3, id: 'harvest-moon-copy', name: 'Harvest Moon copy', mode: 'dark', base: 'harvest-moon', colors: { accent: '#00c8ff', selection: '#20406080' } });
const parsed = parseCustomTheme(theme);
assert.deepEqual(draftColors(customDraft(parsed)), draftColors(draft));
});
test('Theme IDs from names are valid and unique', () => {
assert.equal(uniqueThemeId('RuneStone Dark copy', []), 'runestone-dark-copy');
assert.equal(uniqueThemeId('RuneStone Dark copy', ['runestone-dark-copy', 'runestone-dark-copy-2']), 'runestone-dark-copy-3');
assert.equal(uniqueThemeId('2026 theme', []), 't-2026-theme');
assert.equal(uniqueThemeId('桜', []), 'theme');
for (const name of ['RuneStone Dark copy', '2026 theme', '桜', 'x'.repeat(100), '--Ünïcode--']) assert.match(uniqueThemeId(name, []), /^[a-z][a-z0-9-]{0,63}$/);
});
test('A role shows the results where it is the color, the surface, or one of a pair', () => {
const draft = { ...builtinDraft('default', 'dark', 'Test'), overrides: { 'text-dim': '#3a3a3a', ok: '#55dcf5' } };
const findings = draftFindings(draft);
const dim = roleStatus('text-dim', findings);
assert(dim.failures.length > 0 && dim.failures.every(finding => finding.subject.startsWith('text-dim on ')));
assert(dim.lowest && dim.lowest.value < 4.5);
assert(roleStatus('bg', findings).failures.some(finding => finding.subject === 'text-dim on bg'), 'A surface shows the text that fails on it');
assert(roleStatus('ok', findings).failures.some(finding => finding.subject === 'accent and ok'), 'A status color shows a pair that is too close');
assert.deepEqual(roleStatus('syntax-keyword', findings).failures, []);
});
+50
View File
@@ -0,0 +1,50 @@
import assert from "node:assert/strict";
import test from "node:test";
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "../../../src/lib/workspace/treeActions.ts";
import { planDrop } from "../../../src/lib/workspace/treeDrop.ts";
import type { TreeEntry } from "../../../src/lib/workspace/types.ts";
const entry = (rel_path: string, kind: "file" | "folder" = "file"): TreeEntry => ({ rel_path, name: rel_path.split("/").pop()!, kind });
const entries = [entry("notes", "folder"), entry("notes/a.md"), entry("notes/sub", "folder"), entry("notes/sub/b.md"), entry("notes-old/c.md"), entry("z.md")];
const visible = entries.map(item => item.rel_path);
const find = (path: string) => entries.find(item => item.rel_path === path) ?? null;
test("context actions use all selected visible rows in display order", () => {
assert.deepEqual(actionEntries(entries[1], new Set(["z.md", "missing", "notes/a.md"]), visible, find), [entries[1], entries[5]]);
assert.deepEqual(actionEntries(entries[0], new Set(["z.md", "notes/a.md"]), visible, find), [entries[0]]);
});
test("recursive actions process each selected folder once without including similar names", () => {
assert.deepEqual(selectionRoots([...entries].reverse()), [entries[5], entries[4], entries[0]]);
assert.deepEqual(selectionRoots(entries.slice(1)), [entries[1], entries[2], entries[4], entries[5]]);
});
test("mixed marks become uniformly enabled or disabled and preserve other marks", () => {
const current = ["outside.md", "notes/a.md"];
const selection = [entries[1], entries[5]];
assert.deepEqual(setSelectedMarks(current, selection, true), ["outside.md", "notes/a.md", "z.md"]);
assert.deepEqual(setSelectedMarks(current, selection, false), ["outside.md"]);
assert.deepEqual(current, ["outside.md", "notes/a.md"]);
});
test("a failed action does not skip later items or lose successful results", async () => {
const visited: string[] = [];
const result = await runTreeActions(entries, async item => {
visited.push(item.rel_path);
if (item === entries[1]) throw new Error("Access denied");
return item.name;
});
assert.deepEqual(visited, visible);
assert.deepEqual(result.completed.map(item => item.entry), entries.filter(item => item !== entries[1]));
assert.deepEqual(result.failures, ["notes/a.md: Access denied"]);
});
test("moving beside an existing same-name file preserves both files in the destination order", () => {
const plan = planDrop("notes/a.md", entry("a.md"), "after", parent => parent === "notes" ? ["a.md"] : ["a.md", "z.md"]);
assert.equal(plan.action, "move");
if (plan.action === "move") {
assert.equal(plan.to, "a 2.md");
assert.deepEqual(plan.orderTo, ["a.md", "a 2.md", "z.md"]);
}
assert.deepEqual(planDrop("notes", entries[1], "before", () => []), { action: "noop" });
});
+120
View File
@@ -0,0 +1,120 @@
import assert from "node:assert/strict";
import test from "node:test";
import { dropHint, dropPlaceAt, planDrop, uniqueName } from "../../../src/lib/workspace/treeDrop.ts";
function kids(map: Record<string, string[]>) {
return (parent: string) => map[parent] ?? [];
}
test("same-folder drop before a sibling reorders and keeps the name", () => {
const plan = planDrop(
"notes/b.md",
{ name: "a.md", rel_path: "notes/a.md", kind: "file" },
"before",
kids({ notes: ["a.md", "b.md"] }),
);
assert.deepEqual(plan, {
action: "reorder",
parent: "notes",
names: ["b.md", "a.md"],
});
});
test("same-folder drop after a sibling inserts after that sibling", () => {
const plan = planDrop(
"notes/a.md",
{ name: "b.md", rel_path: "notes/b.md", kind: "file" },
"after",
kids({ notes: ["a.md", "b.md"] }),
);
assert.deepEqual(plan, {
action: "reorder",
parent: "notes",
names: ["b.md", "a.md"],
});
});
test("drop inside the parent folder is a no-op", () => {
const plan = planDrop(
"notes/a.md",
{ name: "notes", rel_path: "notes", kind: "folder" },
"inside",
kids({ notes: ["a.md", "b.md"], "": ["notes"] }),
);
assert.deepEqual(plan, { action: "noop" });
});
test("drop before a sibling folder reorders instead of moving inside", () => {
const plan = planDrop(
"inbox.md",
{ name: "notes", rel_path: "notes", kind: "folder" },
"before",
kids({ "": ["inbox.md", "notes"] }),
);
assert.deepEqual(plan, {
action: "reorder",
parent: "",
names: ["inbox.md", "notes"],
});
});
test("drop onto self is a no-op", () => {
const plan = planDrop(
"notes/a.md",
{ name: "a.md", rel_path: "notes/a.md", kind: "file" },
"before",
kids({ notes: ["a.md"] }),
);
assert.deepEqual(plan, { action: "noop" });
});
test("drop inside another folder moves under that folder", () => {
const plan = planDrop(
"inbox.md",
{ name: "notes", rel_path: "notes", kind: "folder" },
"inside",
kids({ "": ["inbox.md", "notes"], notes: ["a.md"] }),
);
assert.deepEqual(plan, {
action: "move",
from: "inbox.md",
to: "notes/inbox.md",
fromParent: "",
toParent: "notes",
destName: "inbox.md",
orderFrom: ["notes"],
orderTo: ["a.md", "inbox.md"],
});
});
test("drop into a folder that already has the name picks a unique name", () => {
const plan = planDrop(
"inbox.md",
{ name: "notes", rel_path: "notes", kind: "folder" },
"inside",
kids({ "": ["inbox.md", "notes"], notes: ["inbox.md"] }),
);
assert.equal(plan.action, "move");
if (plan.action === "move") {
assert.equal(plan.to, "notes/inbox 2.md");
assert.equal(plan.destName, "inbox 2.md");
}
});
test("uniqueName skips taken numbered suffixes", () => {
assert.equal(uniqueName(["alpha.md", "alpha 2.md"], "alpha.md"), "alpha 3.md");
});
test("dropPlaceAt splits a file row in half and a folder row into three bands", () => {
assert.equal(dropPlaceAt("file", 0.2), "before");
assert.equal(dropPlaceAt("file", 0.8), "after");
assert.equal(dropPlaceAt("folder", 0.1), "before");
assert.equal(dropPlaceAt("folder", 0.5), "inside");
assert.equal(dropPlaceAt("folder", 0.9), "after");
});
test("dropHint names the landing", () => {
assert.equal(dropHint("notes", "inside"), "Into notes");
assert.equal(dropHint("inbox.md", "before"), "Before inbox.md");
assert.equal(dropHint("inbox.md", "after"), "After inbox.md");
});
+20
View File
@@ -0,0 +1,20 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { moveMarks, replayMoveMarks } from "../../../src/lib/workspace/treeMoveHistory.ts";
test("move undo preserves later bookmarks, pins, and new files", () => {
const before = { pins: ["notes/a.md"], bookmarks: [], order: { notes: ["a.md", "b.md"], archive: [] as string[] } };
const after = moveMarks(before, "notes/a.md", "archive/a.md");
const current = { ...after, bookmarks: ["other.md"], pins: [...after.pins, "b.md"], order: { ...after.order, notes: [...after.order.notes, "new.md"] } };
const undo = replayMoveMarks(current, before, after, [{ from: "notes/a.md", to: "archive/a.md" }], false);
assert.deepEqual(undo.pins, ["notes/a.md", "b.md"]);
assert.deepEqual(undo.bookmarks, ["other.md"]);
assert.deepEqual(undo.order.notes, ["a.md", "b.md", "new.md"]);
assert.deepEqual(undo.order.archive, []);
});
test("folder moves retain nested marks and custom order", () => {
const marks = { pins: ["old/child.md"], bookmarks: ["old/deep/file.md"], order: { old: ["child.md"], "old/deep": ["file.md"] } };
const next = moveMarks(marks, "old", "new/old");
assert.deepEqual(next.pins, ["new/old/child.md"]);
assert.deepEqual(next.bookmarks, ["new/old/deep/file.md"]);
assert.deepEqual(next.order["new/old/deep"], ["file.md"]);
});
+87
View File
@@ -0,0 +1,87 @@
import assert from "node:assert/strict";
import test from "node:test";
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type TreeSelection } from "../../../src/lib/workspace/treeSelection.ts";
import type { TreeEntry } from "../../../src/lib/workspace/types.ts";
const entry = (rel_path: string, kind: "file" | "folder" = "file"): TreeEntry => ({ rel_path, name: rel_path.split("/").pop()!, kind });
const children = {
"": [entry("notes", "folder"), entry("src", "folder"), entry("z.md")],
notes: [entry("notes/b.md"), entry("notes/a.md"), entry("notes/nested", "folder")],
"notes/nested": [entry("notes/nested/c.md")],
src: [entry("src/main.ts")],
};
const visible = visibleTreePaths(children, new Set(["notes", "notes/nested"]));
const empty = (): TreeSelection => ({ paths: new Set(), anchor: null });
test("selection outlines omit shared edges and close around gaps and single rows", () => {
const rows = ["a.md", "b.md", "c.md", "d.md", "e.md"];
assert.deepEqual([...treeSelectionEdges(rows, new Set(["a.md", "b.md", "c.md", "e.md"]))], [
["a.md", { top: null, bottom: 0 }],
["b.md", { top: 0, bottom: 0 }],
["c.md", { top: 0, bottom: null }],
["e.md", { top: null, bottom: null }],
]);
assert.deepEqual([...treeSelectionEdges(rows, new Set(["a.md", "c.md", "e.md"]))].map(([, edges]) => edges),
Array.from({ length: 3 }, () => ({ top: null, bottom: null })));
});
test("nested selection outlines retain only exposed indentation steps in visible order", () => {
const edges = treeSelectionEdges(visible, new Set(visible));
assert.deepEqual(edges.get("notes"), { top: null, bottom: 1 });
assert.deepEqual(edges.get("notes/b.md"), { top: 0, bottom: 0 });
assert.deepEqual(edges.get("notes/nested"), { top: 0, bottom: 1 });
assert.deepEqual(edges.get("notes/nested/c.md"), { top: 0, bottom: 0 });
assert.deepEqual(edges.get("src"), { top: 2, bottom: 0 });
assert.deepEqual(edges.get("z.md"), { top: 0, bottom: null });
const collapsed = visibleTreePaths(children, new Set());
assert.deepEqual([...treeSelectionEdges(collapsed, new Set(visible))], [
["notes", { top: null, bottom: 0 }], ["src", { top: 0, bottom: 0 }], ["z.md", { top: 0, bottom: null }],
]);
});
test("visible order preserves custom sorting and only visits expanded folders", () => {
assert.deepEqual(visible, ["notes", "notes/b.md", "notes/a.md", "notes/nested", "notes/nested/c.md", "src", "z.md"]);
assert.deepEqual(visibleTreePaths(children, new Set()), ["notes", "src", "z.md"]);
});
test("Ctrl-click toggles files and folders independently; plain click replaces the selection", () => {
const first = selectTreePath(empty(), "notes", visible);
const added = selectTreePath(first, "z.md", visible, { ctrlKey: true });
assert.deepEqual([...added.paths], ["notes", "z.md"]);
assert.deepEqual([...first.paths], ["notes"]);
const removed = selectTreePath(added, "notes", visible, { ctrlKey: true });
assert.deepEqual([...removed.paths], ["z.md"]);
assert.deepEqual([...selectTreePath(removed, "z.md", visible, { ctrlKey: true }).paths], []);
assert.deepEqual([...selectTreePath(added, "src", visible).paths], ["src"]);
});
test("Shift-click selects an inclusive range in both directions across files and folders", () => {
const first = selectTreePath(empty(), "notes/b.md", visible);
const forward = selectTreePath(first, "src", visible, { shiftKey: true });
assert.deepEqual([...forward.paths], visible.slice(1, 6));
const reverse = selectTreePath(selectTreePath(empty(), "src", visible), "notes/b.md", visible, { shiftKey: true });
assert.deepEqual([...reverse.paths], visible.slice(1, 6));
});
test("repeated Shift-click keeps the anchor and shrinks or reverses the range", () => {
const first = selectTreePath(empty(), "notes/a.md", visible);
const extended = selectTreePath(first, "z.md", visible, { shiftKey: true });
const shrunk = selectTreePath(extended, "notes/nested", visible, { shiftKey: true });
assert.deepEqual([...shrunk.paths], ["notes/a.md", "notes/nested"]);
assert.equal(shrunk.anchor, "notes/a.md");
assert.deepEqual([...selectTreePath(shrunk, "notes", visible, { shiftKey: true }).paths], visible.slice(0, 3));
});
test("Ctrl+Shift adds a range and Command-click supports the same toggle behavior", () => {
let selection = selectTreePath(empty(), "z.md", visible);
selection = selectTreePath(selection, "notes/b.md", visible, { metaKey: true });
selection = selectTreePath(selection, "notes/nested", visible, { ctrlKey: true, shiftKey: true });
assert.deepEqual([...selection.paths], ["z.md", "notes/b.md", "notes/a.md", "notes/nested"]);
assert.deepEqual([...selectTreePath(selection, "z.md", visible, { metaKey: true }).paths], ["notes/b.md", "notes/a.md", "notes/nested"]);
});
test("a missing or hidden anchor makes Shift-click select only the clicked row", () => {
assert.deepEqual(selectTreePath(empty(), "src", visible, { shiftKey: true }), { paths: new Set(["src"]), anchor: "src" });
const hidden = selectTreePath(empty(), "notes/b.md", visible);
assert.deepEqual(selectTreePath(hidden, "z.md", ["notes", "src", "z.md"], { shiftKey: true }), { paths: new Set(["z.md"]), anchor: "z.md" });
});
+22
View File
@@ -0,0 +1,22 @@
// Platform shortcut labels (src/lib/ui/shortcuts.ts).
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { keys, shortcutLabel } from '../../../src/lib/ui/shortcuts.ts';
test('Windows and Linux labels use Ctrl, Alt, and Shift with plus signs', () => {
assert.equal(keys('Mod+Shift+P', false), 'Ctrl+Shift+P');
assert.equal(keys('Mod+\\', false), 'Ctrl+\\');
assert.equal(keys('Mod+,', false), 'Ctrl+,');
assert.equal(keys('F1', false), 'F1');
assert.equal(keys('Shift+Delete', false), 'Shift+Delete');
assert.equal(shortcutLabel({ key: 'Tab', ctrl: true, shift: true }, false), 'Ctrl+Shift+Tab');
assert.equal(shortcutLabel({ key: 'z', mod: true, alt: true, shift: true }, false), 'Ctrl+Alt+Shift+Z');
});
test('macOS labels use the symbols in the Apple order', () => {
assert.equal(keys('Mod+Shift+P', true), '⇧⌘P');
assert.equal(keys('Mod+B', true), '⌘B');
assert.equal(shortcutLabel({ key: 'Tab', ctrl: true, shift: true }, true), '⌃⇧⇥');
assert.equal(shortcutLabel({ key: 'z', mod: true, alt: true, shift: true }, true), '⌥⇧⌘Z');
assert.equal(keys('Escape', true), '⎋');
});
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";
import { chromeLayout, detectChrome, extensionOf, treeFileParts } from "../../../src/lib/workspace/chrome.ts";
test("markdown files open in writing chrome", () => {
assert.equal(detectChrome("notes/inbox.md"), "Writing");
assert.equal(detectChrome("README.markdown"), "Writing");
});
test("scripts open in ide chrome", () => {
assert.equal(detectChrome("src/hello.py"), "Source");
assert.equal(detectChrome("tools/setup.sh"), "Source");
assert.equal(detectChrome("Makefile"), "Source");
});
test("writing chrome wraps and hides the code gutters", () => {
assert.deepEqual(chromeLayout("Writing"), { wrap: true, gutters: false, activeLine: false });
});
test("ide chrome shows the code gutters and does not wrap", () => {
assert.deepEqual(chromeLayout("Source"), { wrap: false, gutters: true, activeLine: true });
});
test("extensionOf reads the last suffix", () => {
assert.equal(extensionOf("a/b.c.py"), "py");
assert.equal(extensionOf(".gitignore"), "");
});
test("treeFileParts splits a display name from its extension", () => {
assert.deepEqual(treeFileParts("inbox.md"), { label: "inbox", ext: "md" });
assert.deepEqual(treeFileParts("chrome_extensions.json"), {
label: "chrome_extensions",
ext: "json",
});
assert.deepEqual(treeFileParts(".gitignore"), { label: ".gitignore", ext: "" });
});
@@ -0,0 +1,29 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { documentSessionKey, parseDocumentSession, restoreDocumentSession } from "../../../src/lib/workspace/documentSession.ts";
test("document sessions isolate workspaces and discard unsafe or duplicate paths", () => {
assert.notEqual(documentSessionKey("C:\\one"), documentSessionKey("C:\\two"));
assert.equal(parseDocumentSession("invalid"), null);
assert.equal(parseDocumentSession('{"version":2,"documents":[]}'), null);
assert.deepEqual(parseDocumentSession(JSON.stringify({ version: 1, activePath: "b.md", documents: [
{ path: "b.md", pinned: true, contents: "unsaved" }, { path: "a.md" }, { path: "b.md" },
{ path: "../outside.md" }, { path: "C:\\outside.md" }, { path: "empty:test" }, null,
] })), { version: 1, activePath: "b.md", documents: [{ path: "b.md", pinned: true }, { path: "a.md", pinned: false }] });
});
test("restoration keeps order and active tab when a missing file fails", async () => {
const opened: string[] = [];
const session = parseDocumentSession(JSON.stringify({ version: 1, activePath: "c.md",
documents: ["b.md", "missing.md", "c.md", "a.md"].map(path => ({ path })) }))!;
const active = await restoreDocumentSession(session, async item => {
if (item.path === "missing.md") throw new Error("Not found");
opened.push(item.path);
});
assert.deepEqual(opened, ["b.md", "c.md", "a.md"]);
assert.equal(active, "c.md");
assert.equal(await restoreDocumentSession({ ...session, activePath: "missing.md" }, async item => {
if (item.path === "missing.md") throw new Error("Not found");
}), "b.md");
assert.equal(await restoreDocumentSession(session, async () => { throw new Error("Unavailable"); }), null);
});
+429
View File
@@ -0,0 +1,429 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { Documents } from "../../../src/lib/workspace/documents.svelte.ts";
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>(done => resolve = done);
return { promise, resolve };
}
const entry = (path: string) => ({ rel_path: path, name: path, kind: "file" as const });
function setup() {
const disk = new Map([["note.md", "original"], ["script.py", "print('hello')"]]);
const io = {
read: async (path: string) => { if (!disk.has(path)) throw new Error("missing"); return disk.get(path)!; },
write: async (path: string, contents: string, expected: string) => {
if (disk.get(path) !== expected) throw new Error("conflict");
disk.set(path, contents);
},
image: async () => "data:image/png;base64,",
kind: () => "text" as const,
chrome: () => "Writing" as const,
};
const docs = new Documents(io, () => {});
return { docs, disk, io };
}
test("imported tabs retain unsaved text and preserve pinned empty tabs", async () => {
const { docs } = setup();
docs.newTab();
const empty = docs.active!;
docs.togglePin(empty.relPath);
const source = setup().docs;
await source.open(entry("note.md"));
source.edit(source.active!.id, "unsaved source text");
source.togglePin("note.md");
assert.equal(docs.importTab(source.active!), true);
assert.equal(docs.active!.contents, "unsaved source text");
assert.equal(docs.active!.saved, "original");
assert.equal(docs.active!.pinned, true);
assert.notEqual(docs.active!.id, source.active!.id);
assert.ok(docs.buffers.some(tab => tab.id === empty.id));
assert.equal(docs.importTab({ ...source.active!, contents: "different" }), false);
assert.equal(docs.active!.contents, "unsaved source text");
});
test("background loading for a split preserves the selected document and its unsaved edits", async () => {
const { docs } = setup();
await docs.open(entry("note.md"));
const first = docs.active!;
docs.edit(first.id, "unsaved text");
await docs.open(entry("script.py"), "background");
assert.equal(docs.active, first);
assert.equal(first.contents, "unsaved text");
assert.equal(docs.buffers.length, 2);
await assert.rejects(docs.open(entry("missing.md"), "background"));
assert.equal(docs.active, first);
docs.select("script.py");
assert.equal(docs.active?.relPath, "script.py");
});
test("tab moves preserve selection, dirty buffers, and in-flight saves", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "my edits");
docs.setChrome("Source");
await docs.open(entry("script.py"));
docs.newTab();
const blank = docs.active!;
const gate = deferred<void>();
const write = io.write;
io.write = async (...args) => { await gate.promise; await write(...args); };
const pending = docs.save(note.id);
await Promise.resolve();
docs.move(note.relPath, 2);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["script.py", blank.relPath, "note.md"]);
assert.equal(docs.active, blank);
assert.equal(docs.buffers[2], note);
assert.equal(note.contents, "my edits");
assert.equal(note.saved, "original");
assert.equal(note.chromeOverride, "Source");
docs.move(blank.relPath, 0);
assert.equal(docs.active, blank);
gate.resolve();
await pending;
assert.equal(disk.get("note.md"), "my edits");
docs.close(blank.relPath);
assert.equal(docs.activePath, "script.py");
});
test("tab moves ignore stale paths and invalid indices and clamp to the tab strip", async () => {
const { docs } = setup();
await docs.open(entry("note.md"));
await docs.open(entry("script.py"));
docs.move("missing.md", 0);
docs.move("script.py", NaN);
docs.move("script.py", 0.5);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]);
docs.move("script.py", -1);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["script.py", "note.md"]);
docs.move("script.py", 99);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]);
docs.dispose();
docs.move("script.py", 0);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]);
});
test("empty tabs are independent, preserve dirty documents, and never access disk", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "keep my edits");
docs.newTab();
const first = docs.active!;
docs.newTab();
const second = docs.active!;
assert.equal(first.kind, "empty");
assert.equal(second.kind, "empty");
assert.notEqual(first.relPath, second.relPath);
assert.equal(note.contents, "keep my edits");
docs.select(first.relPath);
docs.close(first.relPath);
assert.equal(docs.active, second);
docs.close(note.relPath);
io.read = io.image = async () => { assert.fail("empty tabs must not read disk"); };
io.write = async () => { assert.fail("empty tabs must not write disk"); };
docs.edit(second.id, "ignored");
await docs.refresh();
await docs.save(second.id);
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
assert.equal(docs.dirty, false);
assert.equal(second.diskError, undefined);
docs.close(second.relPath);
assert.equal(docs.activePath, null);
});
test("opening a file fills the active empty tab in place and failed reads preserve it", async () => {
const { docs } = setup();
docs.newTab();
const first = docs.active!;
docs.newTab();
const second = docs.active!;
docs.select(first.relPath);
await assert.rejects(docs.open(entry("missing.md")), /missing/);
assert.equal(docs.active, first);
await docs.open(entry("note.md"));
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", second.relPath]);
docs.select(second.relPath);
await docs.open(entry("note.md"));
assert.equal(docs.buffers.length, 2);
assert.equal(docs.activePath, "note.md");
});
test("a new empty tab stays selected when an earlier file read finishes", async () => {
const { docs, io } = setup();
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("note.md"));
docs.newTab();
const blank = docs.active!;
gate.resolve("note");
await pending;
assert.equal(docs.active, blank);
assert.equal(docs.buffers.length, 2);
});
test("clean buffers follow agent edits; dirty buffers retain both versions", async () => {
const { docs, disk } = setup();
await docs.open(entry("note.md"));
disk.set("note.md", "agent version");
await docs.refresh();
assert.equal(docs.active?.contents, "agent version");
docs.edit(docs.active!.id, "my version");
disk.set("note.md", "agent version 2");
await docs.refresh();
assert.equal(docs.active?.contents, "my version");
assert.equal(docs.active?.diskContents, "agent version 2");
await assert.rejects(docs.save(docs.active!.id), /Resolve/);
docs.resolve(docs.active!.id, false);
await docs.save(docs.active!.id);
assert.equal(disk.get("note.md"), "my version");
});
test("typing during a save remains unsaved", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const gate = deferred<void>();
const write = io.write;
io.write = async (...args) => { await gate.promise; return write(...args); };
docs.edit(docs.active!.id, "first edit");
const pending = docs.save(docs.active!.id);
await Promise.resolve();
docs.edit(docs.active!.id, "second edit");
gate.resolve();
await pending;
assert.equal(disk.get("note.md"), "first edit");
assert.equal(docs.active!.saved, "first edit");
assert.equal(docs.active!.contents, "second edit");
assert.equal(docs.dirty, true);
});
test("concurrent saves serialize and finish at the latest edit", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const gate = deferred<void>();
const write = io.write;
io.write = async (...args) => { await gate.promise; return write(...args); };
docs.edit(docs.active!.id, "first");
const first = docs.save(docs.active!.id);
await Promise.resolve();
docs.edit(docs.active!.id, "latest");
const second = docs.save(docs.active!.id);
const third = docs.save(docs.active!.id);
gate.resolve();
await Promise.all([first, second, third]);
assert.equal(disk.get("note.md"), "latest");
assert.equal(docs.dirty, false);
});
test("latest navigation wins even when earlier reads finish later", async () => {
const { docs, io } = setup();
const gate = deferred<string>();
const read = io.read;
io.read = path => path === "note.md" ? gate.promise : read(path);
const first = docs.open(entry("note.md"));
await docs.open(entry("script.py"));
gate.resolve("note");
await first;
assert.equal(docs.activePath, "script.py");
});
test("duplicate opens share one document and do not lose edits", async () => {
const { docs } = setup();
await Promise.all([docs.open(entry("note.md")), docs.open(entry("note.md"))]);
assert.equal(docs.buffers.length, 1);
docs.edit(docs.active!.id, "unsaved");
await docs.open(entry("script.py"));
await docs.open(entry("note.md"));
assert.equal(docs.active!.contents, "unsaved");
});
test("current-tab navigation replaces the selected tab in place; new-tab navigation keeps it", async () => {
const { docs, disk } = setup();
disk.set("third.md", "third");
await docs.open(entry("note.md"));
await docs.open(entry("script.py"), "new");
docs.select("note.md");
await docs.open(entry("third.md"), "current");
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
assert.equal(docs.activePath, "third.md");
await docs.open(entry("script.py"), "current");
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
assert.equal(docs.activePath, "script.py");
});
test("current-tab navigation preserves edits made while the next file is loading", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("script.py"), "current");
docs.edit(note.id, "keep these edits");
gate.resolve("script");
await pending;
assert.equal(docs.buffers.length, 2);
assert.equal(note.contents, "keep these edits");
assert.equal(docs.activePath, "script.py");
});
test("failed current-tab navigation keeps the active document", async () => {
const { docs } = setup();
await docs.open(entry("note.md"), "current");
await assert.rejects(docs.open(entry("missing.md"), "current"), /missing/);
assert.equal(docs.buffers.length, 1);
assert.equal(docs.activePath, "note.md");
});
test("a late current-tab read cannot replace a more recently selected tab", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("script.py"), "current");
docs.select("note.md");
gate.resolve("script");
await pending;
assert.equal(docs.activePath, "note.md");
assert.equal(docs.buffers[0].relPath, "note.md");
});
test("removed files retain text and block accidental recreation", async () => {
const { docs, disk } = setup();
await docs.open(entry("note.md"));
docs.edit(docs.active!.id, "precious text");
disk.delete("note.md");
await docs.refresh();
assert.equal(docs.active!.contents, "precious text");
assert.match(docs.active!.diskError!, /unavailable/);
await assert.rejects(docs.save(docs.active!.id));
});
test("disposing a workspace ignores late open results", async () => {
const { docs, io } = setup();
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("note.md"));
docs.dispose(); gate.resolve("late");
await pending;
assert.equal(docs.buffers.length, 0);
});
test("renaming a folder preserves document identity and dirty state", async () => {
const { docs } = setup();
await docs.open(entry("note.md"));
const id = docs.active!.id;
docs.edit(id, "edits"); docs.rename("note.md", "notes/moved.md");
assert.equal(docs.activePath, "notes/moved.md");
assert.equal(docs.active!.id, id);
assert.equal(docs.dirty, true);
});
test("autosave writes changed background tabs once and skips clean or reverted text", async () => {
const { docs, io, disk } = setup();
const writes: string[] = [];
const write = io.write;
io.write = async (...args) => { writes.push(args[0]); await write(...args); };
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "background edit");
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "temporary edit");
docs.edit(docs.active!.id, docs.active!.saved);
assert.deepEqual(await docs.autosave(), { saved: ["note.md"], failed: [] });
assert.equal(disk.get("note.md"), "background edit");
await docs.autosave();
await docs.save(note.id);
assert.deepEqual(writes, ["note.md"]);
});
test("autosave skips in-flight saves and preserves edits for the next pass", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const gate = deferred<void>();
const write = io.write;
let writes = 0;
io.write = async (...args) => { writes++; await gate.promise; await write(...args); };
docs.edit(docs.active!.id, "first");
const pending = docs.autosave();
await Promise.resolve();
docs.edit(docs.active!.id, "still typing");
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
gate.resolve();
await pending;
assert.equal(writes, 1);
assert.equal(disk.get("note.md"), "first");
assert.equal(docs.dirty, true);
await docs.autosave();
assert.equal(writes, 2);
assert.equal(disk.get("note.md"), "still typing");
});
test("autosave skips known conflicts and unavailable files", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "my note");
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "my script");
disk.set("note.md", "external edit");
disk.delete("script.py");
await docs.refresh();
io.write = async () => { assert.fail("blocked files must not be written"); };
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
assert.equal(note.contents, "my note");
assert.equal(note.diskContents, "external edit");
assert.equal(docs.active!.contents, "my script");
assert.equal(docs.dirty, true);
});
test("an autosave failure preserves edits, saves other files, and can be retried", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "my note");
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "my script");
const write = io.write;
io.write = async (...args) => {
if (args[0] === "note.md") throw new Error("disk full");
await write(...args);
};
const result = await docs.autosave();
assert.deepEqual(result.saved, ["script.py"]);
assert.equal(result.failed[0].path, "note.md");
assert.match(String(result.failed[0].error), /disk full/);
assert.equal(note.saved, "original");
assert.equal(note.contents, "my note");
assert.equal(disk.get("script.py"), "my script");
io.write = write;
await docs.autosave();
assert.equal(disk.get("note.md"), "my note");
assert.equal(docs.dirty, false);
});
test("autosave cannot overwrite an external edit even before the watcher refreshes", async () => {
const { docs, disk } = setup();
await docs.open(entry("note.md"));
docs.edit(docs.active!.id, "my note");
disk.set("note.md", "external edit");
const result = await docs.autosave();
assert.equal(result.failed.length, 1);
assert.equal(disk.get("note.md"), "external edit");
assert.equal(docs.active!.contents, "my note");
assert.equal(docs.dirty, true);
});
test("closed documents and disposed workspaces are not autosaved", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
docs.edit(docs.active!.id, "discarded");
docs.close("note.md");
io.write = async () => { assert.fail("discarded edits must not be written"); };
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "disposed");
docs.dispose();
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
});
+209
View File
@@ -0,0 +1,209 @@
import test from "node:test";
import assert from "node:assert/strict";
import { WorkspaceNoteIndex, type NoteIndexIO } from "../../../src/lib/workspace/noteIndex.ts";
function workspace(files: Map<string, string>): NoteIndexIO {
return {
async list(folder) {
const prefix = folder ? `${folder}/` : "";
const entries = new Map<string, { rel_path: string; kind: "file" | "folder" }>();
for (const path of files.keys()) {
if (!path.startsWith(prefix)) continue;
const suffix = path.slice(prefix.length), separator = suffix.indexOf("/");
const rel_path = separator < 0 ? path : prefix + suffix.slice(0, separator);
entries.set(rel_path, { rel_path, kind: separator < 0 ? "file" : "folder" });
}
return [...entries.values()];
},
async read(path) {
if (!files.has(path)) throw new Error("File missing");
return files.get(path)!;
},
};
}
test("wiki names resolve anywhere and duplicate names require a path", async () => {
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(new Map([
["deep/source.md", "[[Elsewhere]]\n[[Root]]"], ["unrelated/nested/Elsewhere.md", ""], ["Root.md", ""],
])));
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "resolved", path: "unrelated/nested/Elsewhere.md" });
assert.deepEqual(index.resolve("deep/source.md", "Root#Heading", "wiki"), { status: "resolved", path: "Root.md" });
index.update("deep/Elsewhere.md", "");
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "ambiguous", candidates: ["deep/Elsewhere.md", "unrelated/nested/Elsewhere.md"] });
assert.equal(index.backlinks("deep/Elsewhere.md").length, 0);
assert.deepEqual(index.resolve("deep/source.md", "./Elsewhere", "wiki"), { status: "resolved", path: "deep/Elsewhere.md" });
index.update("documents/Other.mdown", "[[Root]]");
assert.deepEqual(index.resolve("deep/source.md", "Other", "wiki"), { status: "resolved", path: "documents/Other.mdown" });
assert.equal(index.backlinks("Root.md").length, 2);
index.update("documents/Version 1.2.md", "");
assert.deepEqual(index.resolve("deep/source.md", "Version 1.2", "wiki"), { status: "resolved", path: "documents/Version 1.2.md" });
});
test("explicit relative links do not fall back and cannot escape the workspace", () => {
const index = new WorkspaceNoteIndex();
for (const path of ["source.md", "deep/source.md", "Target.md", "deep/folder/Target.md", "folder/Target.md", "deep/Name with spaces.md"]) index.update(path, "");
assert.deepEqual(index.resolve("deep/source.md", "./Target", "wiki"), { status: "missing" });
assert.deepEqual(index.resolve("deep/source.md", "./Target.md", "md"), { status: "missing" });
assert.deepEqual(index.resolve("deep/source.md", "../Target", "wiki"), { status: "resolved", path: "Target.md" });
assert.deepEqual(index.resolve("deep/source.md", "/Target", "wiki"), { status: "resolved", path: "Target.md" });
assert.equal(index.resolve("deep/source.md", "folder/Target", "wiki").status, "ambiguous");
assert.deepEqual(index.resolve("deep/source.md", "Name%20with%20spaces.md#part", "md"), { status: "resolved", path: "deep/Name with spaces.md" });
assert.deepEqual(index.resolve("deep/source.md", "..\\Target.md", "md"), { status: "resolved", path: "Target.md" });
assert.equal(index.resolve("deep/source.md", "../../Target", "wiki").status, "missing");
assert.equal(index.resolve("source.md", "../Target", "wiki").status, "missing");
assert.equal(index.resolve("source.md", "https://example.test", "md").status, "external");
assert.equal(index.resolve("source.md", "//example.test/Target", "md").status, "external");
});
test("backlinks index wiki aliases, inline and reference Markdown links with source lines", () => {
const index = new WorkspaceNoteIndex();
index.update("Target.md", "");
index.update("source.md", [
"[[Target|Alias]]", "[Target](Target.md#Section)", "[Named][id]", "[id][]", "[id]", "", "[id]: Target.md", "",
"`[[Target]]`", "![picture](Target.md)", "![[Target]]", "\\[[Target]]", "<!-- [[Target]] -->", "```md", "[[Target]]", "```",
].join("\n"));
assert.deepEqual(index.backlinks("Target.md").map(link => [link.sourcePath, link.line, link.kind]), [
["source.md", 1, "wiki"], ["source.md", 2, "md"], ["source.md", 3, "md"], ["source.md", 4, "md"], ["source.md", 5, "md"],
]);
index.update("Target.md", "[Local section](#Heading)");
assert.equal(index.backlinks("Target.md").length, 5);
});
test("backlinks follow edits, create, file and folder moves, rename, and deletion", () => {
const index = new WorkspaceNoteIndex();
index.update("folder/source.md", "[[Target]]\n[Target](../Target.md)");
assert.deepEqual(index.backlinks("Target.md"), []);
index.update("Target.md", "");
assert.equal(index.backlinks("Target.md").length, 2);
index.update("folder/source.md", "[[Target]]");
assert.equal(index.backlinks("Target.md").length, 1);
index.rename("folder", "other/deep");
assert.equal(index.backlinks("Target.md")[0].sourcePath, "other/deep/source.md");
index.rename("Target.md", "notes/Target.md");
assert.equal(index.backlinks("notes/Target.md").length, 1);
index.rename("notes/Target.md", "notes/Renamed.md");
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
index.update("other/deep/source.md", "[[Renamed]]");
assert.equal(index.backlinks("notes/Renamed.md").length, 1);
index.remove("other");
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
index.remove("notes/Renamed.md");
assert.equal(index.resolve("", "Renamed", "wiki").status, "missing");
});
test("moving a relative-link source changes its target without rewriting Markdown", () => {
const index = new WorkspaceNoteIndex();
index.update("Target.md", "");
index.update("folder/Target.md", "");
index.update("source.md", "[Target](./Target.md)");
assert.equal(index.backlinks("Target.md").length, 1);
index.rename("source.md", "folder/source.md");
assert.equal(index.backlinks("Target.md").length, 0);
assert.equal(index.backlinks("folder/Target.md").length, 1);
});
test("rebuild replaces deleted paths and uses live drafts", async () => {
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(files));
assert.equal(index.backlinks("Target.md").length, 1);
files.delete("source.md");
files.set("elsewhere/source.md", "Old content");
const result = await index.rebuild(workspace(files), new Map([["elsewhere/source.md", "[[Target]]"]]));
assert.equal(result.committed, true);
assert.equal(result.indexed, 2);
assert.deepEqual(result.errors, []);
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["elsewhere/source.md"]);
index.clear();
assert.equal(index.size, 0);
await index.rebuild(workspace(files));
assert.equal(index.size, 2);
});
test("updates during a rebuild survive its disk snapshot", async () => {
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
const io = workspace(files);
let release!: () => void;
const barrier = new Promise<void>(resolve => release = resolve);
const index = new WorkspaceNoteIndex();
const rebuild = index.rebuild({ ...io, read: async path => { await barrier; return io.read(path); } });
await Promise.resolve();
index.update("source.md", "No link");
index.update("new.md", "[[Target]]");
index.rename("new.md", "moved.md");
release();
await rebuild;
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["moved.md"]);
});
test("workspace clear and a newer rebuild reject stale async results", async () => {
let release!: () => void;
const barrier = new Promise<void>(resolve => release = resolve);
const index = new WorkspaceNoteIndex();
const slow = index.rebuild({ list: async () => { await barrier; return [{ rel_path: "old.md", kind: "file" }]; }, read: async () => "" });
index.clear();
await index.rebuild(workspace(new Map([["new.md", ""]])));
release();
assert.equal((await slow).committed, false);
assert.equal(index.resolve("", "old", "wiki").status, "missing");
assert.deepEqual(index.resolve("", "new", "wiki"), { status: "resolved", path: "new.md" });
});
test("read and list failures report incomplete coverage and remain rebuildable", async () => {
const index = new WorkspaceNoteIndex();
const io = workspace(new Map([["Target.md", ""], ["source.md", "[[Target]]"], ["blocked/note.md", ""]]));
const result = await index.rebuild({
list: async folder => { if (folder === "blocked") throw new Error("Folder unavailable"); return io.list(folder); },
read: async path => { if (path === "source.md") throw new Error("File unavailable"); return io.read(path); },
});
assert.deepEqual(result.errors.map(error => [error.path, error.operation]), [["blocked", "list"], ["source.md", "read"]]);
assert.equal(index.backlinks("Target.md").length, 0);
await index.rebuild(io);
assert.equal(index.backlinks("Target.md").length, 1);
});
test("watcher paths update, add, and remove notes without a full rebuild", async () => {
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"], ["old/note.md", "[[Target]]"]]);
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(files));
assert.equal(index.backlinks("Target.md").length, 2);
let lists = 0;
const io = workspace(files), counted: NoteIndexIO = { ...io, list: folder => { lists++; return io.list(folder); } };
files.set("source.md", "No link now");
files.delete("old/note.md");
files.set("new/deeper/linker.md", "[[Target]]");
await index.refresh(counted, ["source.md", "old/note.md", "old", "new"]);
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["new/deeper/linker.md"]);
assert.equal(lists, 4, "The root, the deleted folder, the new folder, and its subfolder");
});
test("refresh keeps the unsaved links of an open draft", async () => {
const files = new Map([["Target.md", ""], ["draft.md", ""]]);
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(files));
index.update("draft.md", "[[Target]]");
await index.refresh(workspace(files), ["draft.md"], new Map([["draft.md", "[[Target]]"]]));
assert.equal(index.backlinks("Target.md").length, 1);
});
test("a rename keeps the links of the moved note", async () => {
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(new Map([["Target.md", ""], ["notes/source.md", "[Up](../Target.md)"]])));
index.rename("notes", "archive");
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["archive/source.md"]);
});
test("bulk reads use batches of 64 and read a file that is too large for a batch alone", async () => {
const files = new Map([["Target.md", ""], ...Array.from({ length: 70 }, (_, i) => [`n${i}.md`, "[[Target]]"] as [string, string])]);
const io = workspace(files), batches: number[] = [], singles: string[] = [];
const index = new WorkspaceNoteIndex();
await index.rebuild({
...io,
read: async path => { singles.push(path); return io.read(path); },
readMany: async paths => { batches.push(paths.length); return paths.map(path => path === "n5.md" ? { path, error: "The batch exceeds the 16 MiB limit." } : { path, source: files.get(path)! }); },
});
assert.deepEqual(batches, [64, 7]);
assert.deepEqual(singles, ["n5.md"]);
assert.equal(index.backlinks("Target.md").length, 70);
});
+12
View File
@@ -0,0 +1,12 @@
import assert from "node:assert/strict";
import test from "node:test";
import { buildOutline } from "../../../src/lib/workspace/outline.ts";
test("the Markdown outline skips code blocks and properties and shows rendered text", () => {
const source = "---\ntitle: Note\n---\n# **Bold** title\n\n```sh\n# not a heading\n```\n\nSetext\n------\n";
assert.deepEqual(buildOutline("note.md", source), [{ level: 1, text: "Bold title", line: 4 }, { level: 2, text: "Setext", line: 10 }]);
});
test("code files list their definitions", () => {
assert.deepEqual(buildOutline("tool.py", "import os\ndef run():\n pass\n"), [{ level: 1, text: "run", line: 2 }]);
});
+76
View File
@@ -0,0 +1,76 @@
import assert from "node:assert/strict";
import test from "node:test";
import { planRename, planTitleRename, planMarkdownTitleRename, planDocumentTitleRename } from "../../../src/lib/workspace/renamePath.ts";
test("rename in a folder keeps the parent", () => {
assert.deepEqual(planRename("notes/a.md", "b.md"), {
action: "rename",
to: "notes/b.md",
});
});
test("same name is a no-op", () => {
assert.deepEqual(planRename("notes/a.md", "a.md"), { action: "noop" });
});
test("path separators are rejected", () => {
assert.deepEqual(planRename("notes/a.md", "foo/bar"), {
action: "error",
message: "Name cannot contain a path separator",
});
assert.deepEqual(planRename("notes/a.md", "foo\\bar"), {
action: "error",
message: "Name cannot contain a path separator",
});
});
test("empty name is rejected", () => {
assert.deepEqual(planRename("notes/a.md", " "), {
action: "error",
message: "Name is empty",
});
});
test("root file rename stays at the root", () => {
assert.deepEqual(planRename("inbox.md", "todo.md"), {
action: "rename",
to: "todo.md",
});
});
test("title rename keeps the existing extension", () => {
assert.deepEqual(planTitleRename("notes/inbox.md", "hello"), {
action: "rename",
to: "notes/hello.md",
});
assert.deepEqual(planTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
});
test("title rename keeps a typed extension", () => {
assert.deepEqual(planTitleRename("notes/inbox.md", "hello.txt"), {
action: "rename",
to: "notes/hello.txt",
});
});
test("writing titles preserve Markdown extensions and allow dots in names", () => {
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "Release 1.2"), { action: "rename", to: "notes/Release 1.2.md" });
assert.deepEqual(planMarkdownTitleRename("notes/inbox.MD", " Renamed.md "), { action: "rename", to: "notes/Renamed.MD" });
assert.deepEqual(planMarkdownTitleRename("inbox.markdown", "Renamed"), { action: "rename", to: "Renamed.markdown" });
assert.deepEqual(planMarkdownTitleRename("inbox.mdown", "Renamed"), { action: "rename", to: "Renamed.mdown" });
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md.md", "inbox.md"), { action: "noop" });
for (const name of ["", " ", ".md", "../escape", "folder/note", "folder\\note"]) {
assert.equal(planMarkdownTitleRename("notes/inbox.md", name).action, "error", name);
}
});
test("document names retain their format and cannot hide or move the file", () => {
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Renamed"), { action: "rename", to: "Projects/Renamed.md" });
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Release 1.2"), { action: "rename", to: "Projects/Release 1.2.md" });
assert.deepEqual(planDocumentTitleRename("Projects/Board.MD", "Renamed.md"), { action: "rename", to: "Projects/Renamed.MD" });
assert.deepEqual(planDocumentTitleRename("Report.pdf", "Next.pdf"), { action: "rename", to: "Next.pdf" });
assert.deepEqual(planDocumentTitleRename("Board.md", "Board"), { action: "noop" });
for (const name of ["", " ", ".md", ".hidden", "../escape", "folder/name", "folder\\name", "a:b", "a?b"])
assert.equal(planDocumentTitleRename("Board.md", name).action, "error", name);
});
+26
View File
@@ -0,0 +1,26 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { TAB_TRANSFER_ID, parseTabTransfer } from '../../../src/lib/workspace/tabTransfer.ts';
const buffer = { id: 'one', relPath: 'a.md', name: 'a.md', kind: 'text', contents: 'Unsaved', saved: 'Saved' };
test('A buffer transfer needs a path, its text, and its saved text', () => {
assert.deepEqual(parseTabTransfer(JSON.stringify({ buffer, reading: true })), { buffer, reading: true });
assert.equal(parseTabTransfer(JSON.stringify({ buffer })).reading, false);
for (const field of ['relPath', 'contents', 'saved'] as const) {
assert.throws(() => parseTabTransfer(JSON.stringify({ buffer: { ...buffer, [field]: 1 } })), /Invalid tab transfer/);
}
});
test('A plugin transfer needs a state object, and other payloads are invalid', () => {
const plugin = { owner: 'test.plugin', id: 'board' };
assert.deepEqual(parseTabTransfer(JSON.stringify({ plugin, reading: false })), { plugin, reading: false });
for (const payload of ['{', 'null', '[]', '{}', '{"plugin":"text"}', '{"buffer":null}']) {
assert.throws(() => parseTabTransfer(payload), /Invalid tab transfer/, payload);
}
});
test('Transfer IDs are UUIDs', () => {
assert.ok(TAB_TRANSFER_ID.test(crypto.randomUUID()));
for (const id of ['', '../x', 'runestone.tab-transfer.1']) assert.ok(!TAB_TRANSFER_ID.test(id), id);
});