Move the tests from scripts/ to tests/ by feature

Unit tests go to tests/unit/<area>/, browser smoke tests to
tests/smoke/<area>/, and tests against a running desktop app to
tests/native/. Files named after dates, work passes, or Kanban cards get
feature names, for example editorOctober12 -> editor/footnotes.

scripts/ keeps the build, release, and package tools. Plugin repositories
import scripts/packagePlugin.mjs, and the Terminal smoke test imports
scripts/pluginMocks.mjs, which now re-exports the harness copy.

The unit tests get their own type check (tests/tsconfig.json) with Node
types. pnpm check runs it after the app check. Add @types/node and fix
the three test mocks that it reported.
This commit is contained in:
Knotty Wyvern
2026-10-27 19:47:39 -07:00
parent 90d1940c73
commit e433bed28e
154 changed files with 269 additions and 227 deletions
+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"]);
});
+23
View File
@@ -0,0 +1,23 @@
import test from "node:test";
import assert from "node:assert/strict";
import { SearchQuery } from "@codemirror/search";
import { documentMatches, replacementText } 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("replacement keeps regex context, capture groups, dollars, and line breaks", () => {
const query = new SearchQuery({ search: "(?<=G)(amma)", regexp: true, replace: "$1-$12-$&-$$\\n" });
assert.equal(replacementText("Gamma", 1, query), "amma-amma2-amma-$\n");
assert.equal(replacementText("Alpha", 0, new SearchQuery({ search: "Alpha", replace: "$1\\t" })), "$1\t");
});
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/);
});
+15
View File
@@ -0,0 +1,15 @@
import assert from "node:assert/strict";
import test from "node:test";
import { fenceOpenText, headingMarkText } from "../../../src/lib/editor/headingMarks.ts";
test("heading marks match the heading level", () => {
assert.equal(headingMarkText(1), "#");
assert.equal(headingMarkText(3), "###");
assert.equal(headingMarkText(6), "######");
});
test("fence open marks include the language", () => {
assert.equal(fenceOpenText(""), "```");
assert.equal(fenceOpenText("js"), "```js");
assert.equal(fenceOpenText(" pp "), "```pp");
});
+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-->');
});
+55
View File
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { attachmentRel, hasFileDrag, imageFiles, imageInsertion, workspaceImageLink } from "../../../src/lib/workspace/media.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("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");
});
+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>/);
});
+244
View File
@@ -0,0 +1,244 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
copySelection,
cutSelection,
pasteClipboard,
writerContextItems,
} from "../../../src/lib/editor/writerMenu.ts";
type Harness = {
selected: string;
inTable: boolean;
deleted: boolean;
focused: boolean;
inserted: string | null;
dispatched: boolean;
};
function fakeEditor(init?: { selected?: string; inTable?: boolean }) {
const harness: Harness = {
selected: init?.selected ?? "",
inTable: init?.inTable ?? false,
deleted: false,
focused: false,
inserted: null,
dispatched: false,
};
const tr = {
insertText(text: string) {
harness.inserted = text;
return tr;
},
};
const chainApi = {
focus() {
harness.focused = true;
return chainApi;
},
deleteSelection() {
harness.deleted = true;
return chainApi;
},
run() {
return true;
},
};
const editor = {
isActive(name: string) {
return name === "table" && harness.inTable;
},
chain() {
return chainApi;
},
state: {
selection: { from: 0, to: harness.selected.length },
doc: {
textBetween() {
return harness.selected;
},
},
tr,
},
view: {
dispatch() {
harness.dispatched = true;
},
},
};
return { editor, harness };
}
function withClipboard(
impl: { writeText?: (text: string) => Promise<void>; readText?: () => Promise<string> },
run: () => Promise<void>,
): Promise<void> {
const previous = Object.getOwnPropertyDescriptor(globalThis, "navigator");
Object.defineProperty(globalThis, "navigator", {
configurable: true,
value: { clipboard: impl },
});
return run().finally(() => {
if (previous) {
Object.defineProperty(globalThis, "navigator", previous);
} else {
Reflect.deleteProperty(globalThis, "navigator");
}
});
}
function actionLabels(items: ReturnType<typeof writerContextItems>): string[] {
const labels: string[] = [];
for (const item of items) {
if (item.kind === "action") {
labels.push(item.label);
} else if (item.kind === "group") {
for (const sub of item.items) {
if (sub.kind === "action") {
labels.push(sub.label);
}
}
}
}
return labels;
}
test("paste inserts clipboard text without parsing tags", async () => {
const { editor, harness } = fakeEditor();
await withClipboard(
{ readText: async () => "<b>bold</b>" },
async () => {
await pasteClipboard(editor as never);
},
);
assert.equal(harness.focused, true);
assert.equal(harness.dispatched, true);
assert.equal(harness.inserted, "<b>bold</b>");
});
test("paste swallows clipboard errors", async () => {
const { editor, harness } = fakeEditor();
await withClipboard(
{
readText: async () => {
throw new Error("denied");
},
},
async () => {
await pasteClipboard(editor as never);
},
);
assert.equal(harness.dispatched, false);
assert.equal(harness.inserted, null);
});
test("cut keeps the selection when clipboard write fails", async () => {
const { editor, harness } = fakeEditor({ selected: "gone" });
await withClipboard(
{
writeText: async () => {
throw new Error("denied");
},
},
async () => {
await cutSelection(editor as never);
},
);
assert.equal(harness.deleted, false);
});
test("copy swallows clipboard errors", async () => {
const { editor } = fakeEditor({ selected: "keep" });
let attempted = false;
await withClipboard(
{
writeText: async () => {
attempted = true;
throw new Error("denied");
},
},
async () => {
await copySelection(editor as never);
},
);
assert.equal(attempted, true);
});
test("cut writes selected text then deletes it", async () => {
const { editor, harness } = fakeEditor({ selected: "clip" });
let written = "";
await withClipboard(
{
writeText: async (text) => {
written = text;
},
},
async () => {
await cutSelection(editor as never);
},
);
assert.equal(written, "clip");
assert.equal(harness.deleted, true);
});
test("table row and column actions disable outside a table", () => {
const { editor } = fakeEditor({ inTable: false });
const items = writerContextItems(editor as never);
const table = items.find((item) => item.kind === "group" && item.label === "Table");
assert.equal(table?.kind, "group");
if (table?.kind !== "group") {
return;
}
const byLabel = new Map(
table.items.filter((item) => item.kind === "action").map((item) => [item.label, item]),
);
assert.equal(byLabel.get("Insert table")?.disabled, undefined);
assert.equal(byLabel.get("Add row above")?.disabled, true);
assert.equal(byLabel.get("Delete table")?.disabled, true);
});
test("table row and column actions enable inside a table", () => {
const { editor } = fakeEditor({ inTable: true });
const items = writerContextItems(editor as never);
const table = items.find((item) => item.kind === "group" && item.label === "Table");
assert.equal(table?.kind, "group");
if (table?.kind !== "group") {
return;
}
const byLabel = new Map(
table.items.filter((item) => item.kind === "action").map((item) => [item.label, item]),
);
assert.equal(byLabel.get("Insert table")?.disabled, undefined);
assert.equal(byLabel.get("Add row above")?.disabled, false);
assert.equal(byLabel.get("Delete table")?.disabled, false);
});
test("style and format actions cover the requested commands", () => {
const { editor } = fakeEditor();
const labels = actionLabels(writerContextItems(editor as never));
for (const label of [
"Cut",
"Copy",
"Paste",
"Heading 1",
"Heading 6",
"Body",
"Quote",
"Bullet list",
"Numbered list",
"Task list",
"Bold",
"Italic",
"Strikethrough",
"Highlight",
"Code",
"Math",
"Comment",
"Clear formatting",
"Insert table",
]) {
assert.equal(labels.includes(label), true, label);
}
assert.equal(labels.includes("Superscript"), false);
assert.equal(labels.includes("Subscript"), false);
});
+75
View File
@@ -0,0 +1,75 @@
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';
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', () => {
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;
const stop = syncLocale();
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(); assert.equal(events.size, 0);
} 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, []);
});
+57
View File
@@ -0,0 +1,57 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "../../../src/lib/workspace/documentPanes.ts";
import { paneBounds } 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("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();
});
+32
View File
@@ -0,0 +1,32 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, 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 });
}
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false });
});
test("preferences persist and load at both interval limits", () => {
const store = new Map<string, string>();
for (const autosaveSeconds of [1, 23, 300]) {
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false };
saveSettings({ setItem: (key, value) => { store.set(key, value); } }, settings);
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
}
});
test("invalid changes never reach storage and storage failures reach the caller", () => {
let writes = 0;
const storage = { setItem: () => { writes++; } };
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds, showInternalFolder: false }));
}
assert.equal(writes, 0);
assert.throws(() => saveSettings({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_SETTINGS }), /Storage unavailable/);
});
+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.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"));
});
+30
View File
@@ -0,0 +1,30 @@
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" })), {
...DEFAULT_WORKBENCH_LAYOUT, leftOpen: false, rightOpen: false, rightWidth: 320,
});
}
assert.deepEqual(parseWorkbenchLayout('{"leftOpen":"false","rightOpen":0}'), DEFAULT_WORKBENCH_LAYOUT);
});
test("layout survives storage round trips with hidden panels and all navigation views", () => {
const store = new Map<string, string>();
for (const leftView of ["files", "search", "bookmarks"] as const) {
for (const leftWidth of [160, 321.5, 480]) {
const layout = { leftOpen: false, rightOpen: false, leftWidth, rightWidth: 400, leftView };
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.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), [
{ text: "Install", slug: "install", line: 9 },
{ 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/);
});
+81
View File
@@ -0,0 +1,81 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { pluginAccess } from "../../../src/lib/plugins/access.ts";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import type { PluginApi, PluginCommand, PluginView } from "../../../src/lib/plugins/sdk.ts";
const view = (id: string, extra: Partial<PluginView> = {}): PluginView => ({ id, title: id, mount() {}, ...extra });
const command = (id: string, extra: Partial<PluginCommand> = {}): PluginCommand => ({ id, title: id, run() {}, ...extra });
test("plugin access separates settings, launchers, and commands without reading titles", () => {
const tools = pluginAccess("org.example.test", [command("open", { category: "open" }), command("configure")], [view("preferences", { settings: true }), view("tasks"), view("instance", { launcher: false })]);
assert.deepEqual(tools.map(({ id, surface }) => [id, surface]), [["open", "open"], ["configure", "commands"], ["preferences", "settings"], ["tasks", "open"]]);
});
test("installed RuneStone packages retain access before their next package update", () => {
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings")])[0].surface, "settings");
assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab")], [view("tab-123")]).map(({ id, surface }) => [id, surface]), [["new-tab", "open"]]);
assert.equal(pluginAccess("org.example.test", [], [view("settings")])[0].surface, "open");
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings", { settings: false })])[0].surface, "open");
assert.equal(pluginAccess("runestone.browser", [command("new-tab", { category: "action" })], [])[0].surface, "commands");
});
test("command launchers retain the plugin action icon", () => {
const tools = pluginAccess("runestone.git", [command("graph", { category: "open", icon: "git" })], []);
assert.equal(tools[0].icon, "git");
assert.equal(tools[0].surface, "open");
});
test("settings listeners are removable and revoked before plugin cleanup", async () => {
let api!: PluginApi, notify!: () => void;
let received = 0, disposed = 0;
const session = new ExternalSession("org.example.settings", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
assets: { read: async () => new Uint8Array() },
settings: { read: async () => null, write: async () => {}, subscribe(listener) { notify = listener; return () => { disposed++; }; } },
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
const off = api.settings.subscribe!(() => { received++; });
notify(); assert.equal(received, 1);
await off(); await off(); assert.equal(disposed, 1);
api.settings.subscribe!(() => { received++; });
await session.stop(); notify();
assert.equal(received, 1); assert.equal(disposed, 2);
assert.throws(() => api.settings.subscribe!(() => {}), /disabled/);
});
test("invalid access metadata fails registration", async () => {
for (const activate of [
(api: PluginApi) => api.registerCommand(command("invalid", { category: "unknown" as "open" })),
(api: PluginApi) => api.registerView(view("invalid", { settings: "yes" as unknown as boolean })),
(api: PluginApi) => api.registerView(view("invalid", { launcher: "yes" as unknown as boolean })),
]) {
const session = new ExternalSession("org.example.invalid", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
}, () => {}, () => {});
await assert.rejects(session.start({ activate }), /category|boolean/);
await session.stop();
}
});
test("settings windows permit model checks and cancellation", () => {
const capability = JSON.parse(readFileSync(new URL("../../../src-tauri/capabilities/settings.json", import.meta.url), "utf8"));
for (const permission of ["allow-completion-request", "allow-completion-cancel", "allow-plugins-data"]) assert(capability.permissions.includes(permission));
});
test("view mount context distinguishes Settings from editor and dialog views", async () => {
const surfaces: string[] = [];
const session = new ExternalSession("org.example.context", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
}, () => {}, () => {});
await session.start({ activate(api) { api.registerView(view("settings", { mount(_element, context) { surfaces.push(context!.surface); } })); } });
const target = { replaceChildren() {} } as unknown as HTMLElement;
const disposeView = await session.mount("settings", target);
await disposeView();
const disposeSettings = await session.mount("settings", target, undefined, "settings");
await disposeSettings(); await session.stop();
assert.deepEqual(surfaces, ["view", "settings"]);
});
@@ -0,0 +1,96 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import type { PluginApi, PluginDocumentType } from "../../../src/lib/plugins/sdk.ts";
const services = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
};
const type: PluginDocumentType = {
id: "board", title: "Board", icon: "kanban", extensions: ["md"],
identify: (_path, source) => source === "board" ? { id: "stable" } : null,
create: { label: "New board", defaultName: "Untitled board", extension: "md", contents: () => "board" },
mount: () => {},
};
test("document renames pass the stable identity and stop after shutdown", async () => {
let api!: PluginApi;
const calls: unknown[] = [];
const session = new ExternalSession("fixture", services, () => {}, () => {}, undefined, undefined,
async (document, name) => { calls.push({ document, name }); return "Renamed.md"; });
await session.start({ activate(value) { api = value; } });
assert.equal(await api.renameDocument!({ id: "stable", path: "Board.md" }, "Renamed"), "Renamed.md");
assert.deepEqual(calls, [{ document: { id: "stable", path: "Board.md" }, name: "Renamed" }]);
await session.stop();
assert.throws(() => api.renameDocument!({ id: "stable", path: "Board.md" }, "Other"), /disabled/);
assert.equal(calls.length, 1);
});
test("binary document registration preserves bytes and revokes reads on shutdown", async () => {
let api!: PluginApi;
const bytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0xff, 0x00]);
const paths: string[] = [];
const session = new ExternalSession("fixture", {
...services, workspace: { ...services.workspace, readBytes: async path => { paths.push(path); return bytes; } },
}, () => {}, () => {});
await session.start({ activate(value) {
api = value;
api.registerDocumentType({ ...type, id: "pdf", extensions: ["pdf"], content: "binary", create: undefined });
} });
assert.equal(session.documentTypes.get("pdf")?.content, "binary");
assert.deepEqual(await api.workspace.readBytes!("report.pdf"), bytes);
assert.deepEqual(paths, ["report.pdf"]);
assert.throws(() => api.registerDocumentType({ ...type, content: "invalid" as "binary" }), /content type/);
await session.stop();
assert.throws(() => api.workspace.readBytes!("report.pdf"), /disabled/);
});
test("document types have independent registrations and reject invalid creation actions", async () => {
let api!: PluginApi;
const session = new ExternalSession("fixture", services, () => {}, () => {});
await session.start({ activate(value) { api = value; api.registerDocumentType(type); } });
assert.equal(session.documentTypes.get("board")?.identify("Board.md", "board")?.id, "stable");
assert.equal(session.documentTypes.get("board")?.identify("Note.md", "plain"), null);
assert.throws(() => api.registerDocumentType(type), /duplicate/);
assert.throws(() => api.registerDocumentType({ ...type, id: "other", create: { ...type.create!, extension: "exe" } }), /Invalid document creation/);
await session.stop();
assert.equal(session.documentTypes.size, 0);
assert.throws(() => api.registerDocumentType(type), /disabled/);
});
test("two document mounts retain independent context and clean up once", async () => {
const mounted: string[] = [], cleaned: string[] = [];
const session = new ExternalSession("fixture", services, () => {}, () => {});
await session.start({ activate(api) {
api.registerDocumentType({ ...type, mount(_node, context) { mounted.push(context.path); return () => { cleaned.push(context.id); }; } });
} });
const element = () => ({ replaceChildren() {} }) as unknown as HTMLElement;
const first = await session.mount("board", element(), { id: "first", path: "One.md" });
await session.mount("board", element(), { id: "second", path: "Two.md" });
assert.deepEqual(mounted, ["One.md", "Two.md"]);
await first(); await first();
assert.deepEqual(cleaned, ["first"]);
await session.stop();
assert.deepEqual(cleaned, ["first", "second"]);
});
test("document opening and workspace subscriptions stop with their plugin", async () => {
let api!: PluginApi;
let listener: (() => void) | undefined;
let notifications = 0, removed = 0;
const opened: string[] = [];
const session = new ExternalSession("fixture", {
...services,
workspace: { ...services.workspace, subscribe(callback) { listener = callback; return () => { removed++; }; } },
}, () => {}, () => {}, undefined, async path => { opened.push(path); });
await session.start({ activate(value) { api = value; api.workspace.subscribe!(() => { notifications++; }); } });
await api.openDocument("Board.md"); listener!();
assert.deepEqual(opened, ["Board.md"]);
assert.equal(notifications, 1);
await session.stop(); listener!();
assert.equal(notifications, 1);
assert.equal(removed, 1);
assert.throws(() => api.openDocument("Board.md"), /disabled/);
});
@@ -0,0 +1,60 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
test("Git and file access stop before plugin cleanup", async () => {
const calls: unknown[] = [];
let api!: PluginApi;
const registry = new ContributionRegistry();
const session = new ExternalSession("test.git", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
openFile: async path => { calls.push(path); },
git: {
status: async () => ({ available: true, repository: true, branch: "main", changes: [] }),
diff: async (path, staged) => { calls.push([path, staged]); return "diff"; },
stage: async paths => { calls.push(paths); }, unstage: async paths => { calls.push(paths); },
commit: async message => { calls.push(message); }, blame: async () => null,
push: async () => { calls.push('push'); }, pull: async () => { calls.push('pull'); }, graph: async () => ({ commits: [] }),
commitDetails: async () => { throw new Error("not used"); }, commitDiff: async () => "",
},
}, () => {}, () => {}, registry);
await session.start({ activate(value) { api = value; api.contribute("git", { blame: (path, line) => api.git!.blame(path, line) }); } });
await api.openFile!("notes.md");
assert.equal(await api.git!.diff("notes.md", true), "diff");
await api.git!.stage(["notes.md"]);
assert.deepEqual(calls, ["notes.md", ["notes.md", true], ["notes.md"]]);
await api.git!.push();
await api.git!.pull();
assert.deepEqual(await api.git!.graph(), { commits: [] });
assert.deepEqual(calls.slice(-2), ['push', 'pull']);
await session.stop();
assert.equal(registry.get("git"), undefined);
assert.throws(() => api.openFile!("notes.md"), /disabled/);
for (const action of [() => api.git!.push(), () => api.git!.pull(), () => api.git!.graph()]) assert.throws(action, /disabled/);
for (const action of [() => api.git!.status(), () => api.git!.diff("a", false), () => api.git!.stage(["a"]), () => api.git!.unstage(["a"]), () => api.git!.commit("a"), () => api.git!.blame("a", 1)]) assert.throws(action, /disabled/);
});
test("view replacement rejects unknown destinations and stops after disposal", async () => {
let api!: PluginApi;
const calls: unknown[] = [];
const session = new ExternalSession("test.boards", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
}, () => {}, () => {}, new ContributionRegistry(), undefined, undefined, undefined,
(current, next) => calls.push([current, next]), (document, next) => calls.push([document, next]));
await session.start({ activate(value) {
api = value;
for (const id of ["a", "b"]) api.registerView({ id, title: id, placement: "editor", mount() {} });
api.registerView({ id: "sidebar", title: "Sidebar", placement: "sidebar", navigation: true, icon: "git", mount() {} });
} });
api.replaceView!("a", "b");
api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "b");
assert.deepEqual(calls, [["a", "b"], [{ id: "legacy", path: "Board.md" }, "b"]]);
assert.throws(() => api.replaceView!("missing", "b"), /Unknown/);
assert.throws(() => api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "missing"), /Unknown/);
await session.stop();
assert.throws(() => api.replaceView!("a", "b"), /disabled/);
});
@@ -0,0 +1,64 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, readFile, writeFile, rm, realpath } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
// @ts-ignore The build tool is a JavaScript module.
import { packagePlugin } from "../../../scripts/packagePlugin.mjs";
test("plugin packaging rejects invalid release inputs before writing an archive", async () => {
const root = await mkdtemp(join(tmpdir(), "runestone-packaging-"));
const source = join(root, "plugin"), output = join(root, "releases");
await mkdir(source);
const manifest = {
schemaVersion: 1, apiVersion: 1, id: "org.test.demo", name: "Demo", author: "Test",
description: "Test plugin", version: "1.0.0", entry: "main.js", access: "full-app",
};
const save = async (changes = {}) => writeFile(join(source, "plugin.json"), JSON.stringify({ ...manifest, ...changes }));
try {
await assert.rejects(packagePlugin(source, output), /plugin.json at its root/);
await save();
await assert.rejects(packagePlugin(source, output), /entry module is missing/);
await writeFile(join(source, "main.js"), "export function activate() {}");
for (const [changes, message] of [
[{ id: "../escape" }, /ID is invalid/],
[{ version: "1.0" }, /version such as/],
[{ version: "1.0.0A" }, /version such as/],
[{ version: "1.0.0a1" }, /version such as/],
[{ version: "1.0.0-beta" }, /version such as/],
[{ version: "1.0.0+build" }, /version such as/],
[{ entry: "../main.js" }, /compiled JavaScript/],
[{ apiVersion: 99 }, /Unsupported/],
[{ author: "" }, /valid author/],
] as const) {
await save(changes);
await assert.rejects(packagePlugin(source, output), message);
}
await save();
await assert.rejects(packagePlugin(source, source), /outside the plugin folder/);
await writeFile(join(source, "invalid file.txt"), "test");
await assert.rejects(packagePlugin(source, output), /Invalid package path/);
await rm(join(source, "invalid file.txt"));
await writeFile(join(root, "package.json"), JSON.stringify({ name: "test-plugin" }));
const path = await packagePlugin(source);
assert.equal(path, join(await realpath(output), "org.test.demo-1.0.0.zip"));
const first = await readFile(path);
await packagePlugin(source, output);
assert.deepEqual(await readFile(path), first);
await writeFile(join(source, "main.js"), "export function activate() { return 1; }");
await assert.rejects(packagePlugin(source), /different contents/);
assert.deepEqual(await readFile(path), first);
await writeFile(join(source, "main.js"), "export function activate() {}");
for (const version of ["0.2.28a", "0.2.28b", "0.2.28aa"]) {
await save({ version });
const hotfix = await packagePlugin(source, output);
assert.equal(hotfix, join(await realpath(output), `org.test.demo-${version}.zip`));
assert.ok((await readFile(hotfix)).length > 0);
assert.deepEqual(await readFile(path), first);
}
} finally {
// mkdtemp returns this test's unique directory under the operating system temp folder.
assert.equal(root.startsWith(join(tmpdir(), "runestone-packaging-")), true);
await rm(root, { recursive: true, force: true });
}
});
+89
View File
@@ -0,0 +1,89 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ContributionRegistry, pluginHost } from "../../../src/lib/plugins/registry.ts";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import { existsSync } from "node:fs";
// The Table Formulas package comes from a sibling repository. Run `pnpm build:plugins` to build it.
const tableFormulasEntry = new URL("../../../plugin-packages/table-formulas/main.js", import.meta.url);
const tableFormulas = existsSync(tableFormulasEntry) ? await import(tableFormulasEntry.href) : undefined;
const activate = tableFormulas?.activate;
const needsTableFormulas = { skip: tableFormulas ? false : "the Table Formulas package is not built; run pnpm build:plugins" };
import { renderMarkdownHtml, renderMarkdownSections } from "../../../src/lib/workspace/noteHtml.ts";
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
const services = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
};
test("optional workspace creation and reads stop when the plugin is disabled", async () => {
const files = new Map<string, string>();
let api!: PluginApi;
const session = new ExternalSession("workspace-test", {
...services,
workspace: {
...services.workspace,
readOptional: async path => files.get(path) ?? null,
create: async (path, contents) => { if (files.has(path)) throw new Error("exists"); files.set(path, contents); },
},
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
assert.equal(await api.workspace.readOptional!("board.json"), null);
await api.workspace.create!("board.json", "{}");
assert.equal(await api.workspace.readOptional!("board.json"), "{}");
await assert.rejects(api.workspace.create!("board.json", "replacement"), /exists/);
await session.stop();
assert.throws(() => api.workspace.create!("other.json", "{}"), /disabled/);
assert.throws(() => api.workspace.readOptional!("board.json"), /disabled/);
assert.equal(files.size, 1);
});
test("core starts without optional features and formula packages preserve source when stopped", needsTableFormulas, async () => {
assert.equal(pluginHost.get("terminal"), undefined);
assert.equal(pluginHost.get("tableFormulas"), undefined);
const source = "| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n";
assert.doesNotMatch(renderMarkdownHtml(source, new Map()), /md-table-formula/);
const session = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
await session.start({ activate });
const enabled = renderMarkdownHtml(source, new Map());
assert.match(enabled, />6<\/span>/);
await session.stop();
for (const html of [renderMarkdownHtml(source, new Map()), ...renderMarkdownSections(source, new Map()).map(section => section.html)]) {
assert.doesNotMatch(html, /md-table-formula/);
assert.match(html, /=A2\*3/);
assert.match(html, /<table>/);
}
const next = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
await next.start({ activate });
assert.equal(renderMarkdownHtml(source, new Map()), enabled);
await next.stop();
});
test("package contribution conflicts preserve the first owner and revoke access before cleanup", needsTableFormulas, async () => {
const registry = new ContributionRegistry();
const first = new ExternalSession("first", services, () => {}, () => {}, registry);
const second = new ExternalSession("second", services, () => {}, () => {}, registry);
let api!: PluginApi;
await first.start({ activate(value) { api = value; activate(api); } });
const contribution = registry.get("tableFormulas");
await assert.rejects(second.start({ activate }), /already registered/);
await second.stop();
assert.equal(registry.get("tableFormulas"), contribution);
api.onDispose(() => {
assert.equal(registry.get("tableFormulas"), undefined);
assert.throws(() => api.contribute("tableFormulas", contribution!), /disabled/);
});
await first.stop();
});
test("partial activation and failed cleanup cannot retain feature contributions", needsTableFormulas, async () => {
const registry = new ContributionRegistry();
const session = new ExternalSession("failed", services, () => {}, () => {}, registry);
await assert.rejects(session.start({ activate(api) {
activate(api);
api.onDispose(() => { throw new Error("Cleanup failed"); });
throw new Error("Activation failed");
} }), /Activation failed/);
await assert.rejects(session.stop(), /Cleanup failed/);
assert.equal(registry.get("tableFormulas"), undefined);
});
@@ -0,0 +1,77 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
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'];
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));
});
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; run pnpm build:installer once to download it';
test('the native NSIS comparator blocks older hotfixes and permits reinstall', { skip: nsisSkip }, async () => {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-version-'));
try {
const checks: string[] = [];
checks.push('StrCpy $0 "keep0"\nStrCpy $1 "keep1"\nPush "0.1.23a"\nPush "0.1.23"\nCall RuneStoneCompareVersions\nPop $2\nStrCmp $0 "keep0" saved0\nSetErrorLevel 1\nQuit\nsaved0:\nStrCmp $1 "keep1" saved1\nSetErrorLevel 1\nQuit\nsaved1:');
let index = 0;
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) {
checks.push(`Push "${ordering[i]}"\nPush "${ordering[j]}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 ${Math.sign(i - j)} check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
}
for (const version of ['0.1.23A', '0.1.23a1', '0.1.a', '0.1.23-rc', '0.1.23aaaaa', '4294967296.0.0']) {
checks.push(`Push "0.1.23a"\nPush "${version}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 -1 check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
}
const executable = path.join(root, 'compare.exe');
const source = `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone version check"\nOutFile "${executable}"\n!include LogicLib.nsh\n!include WordFunc.nsh\n!include "${path.resolve('src-tauri/windows/versionCompare.nsh')}"\nSection\n${checks.join('\n')}\nSetErrorLevel 0\nSectionEnd\n`;
const script = path.join(root, 'compare.nsi');
await writeFile(script, source);
const compiler = makensis;
const built = spawnSync(compiler, ['/V2', script], { encoding: 'utf8', windowsHide: true });
assert.equal(built.status, 0, built.stdout + built.stderr);
const checked = spawnSync(executable, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
assert.equal(checked.status, 0, checked.stdout + checked.stderr);
const patched = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.resolve('scripts/setWindowsVersion.ps1'), '-Path', executable, '-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/);
// Git can check the template out with CRLF line endings on Windows.
const template = (await readFile('src-tauri/windows/installer.nsi', 'utf8')).replaceAll('\r\n', '\n');
assert.ok(template.includes('Call RuneStoneCompareVersions'));
assert.ok(!template.includes('nsis_tauri_utils::SemverCompare'));
assert.match(template, /SetErrorLevel 2\n\s+Quit/);
const guard = / !if "\$\{ALLOWDOWNGRADES\}" == "false"\n \$\{If\} \$R0 = -1[\s\S]+? !endif/.exec(template)?.[0];
assert.ok(guard, 'The downgrade guard must precede reinstall and update actions.');
const blockExe = path.join(root, 'block.exe');
const blockScript = path.join(root, 'block.nsi');
await writeFile(blockScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone downgrade check"\nOutFile "${blockExe}"\n!include LogicLib.nsh\n!define ALLOWDOWNGRADES "false"\nLangString dontUninstallDowngrade 1033 "Older versions cannot replace this installation."\nSection\nStrCpy $R0 -1\n${guard}\nSetErrorLevel 1\nSectionEnd\n`);
const blockBuilt = spawnSync(compiler, ['/V2', blockScript], { encoding: 'utf8', windowsHide: true });
assert.equal(blockBuilt.status, 0, blockBuilt.stdout + blockBuilt.stderr);
for (const flags of [['/S'], ['/S', '/P'], ['/S', '/UPDATE']]) {
const blocked = spawnSync(blockExe, flags, { encoding: 'utf8', windowsHide: true, timeout: 30000 });
assert.equal(blocked.status, 2, 'The installer must block a downgrade with ' + flags.join(' '));
}
assert.match(template, /\$\{ElseIf\} \$R0 = 1 ; Upgrading\n\s+\$\{If\} \$R1 = 1\n\s+Goto reinst_done/);
assert.ok(template.includes('"RuneStoneReleaseVersion" "${VERSION}"'));
assert.ok(template.includes('"DisplayVersion" "${TOOLCHAINVERSION}"'));
const legacyExe = path.join(root, 'legacy.exe');
const legacyScript = path.join(root, 'legacy.nsi');
const pluginPath = path.join(process.env.LOCALAPPDATA!, 'tauri/NSIS/Plugins/x86-unicode/additional');
await writeFile(legacyScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone legacy version check"\nOutFile "${legacyExe}"\n!addplugindir "${pluginPath}"\nSection\nnsis_tauri_utils::SemverCompare "0.1.23" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_ok\nSetErrorLevel 1\nQuit\nlegacy_ok:\nnsis_tauri_utils::SemverCompare "0.1.22" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_older_ok\nSetErrorLevel 1\nQuit\nlegacy_older_ok:\nnsis_tauri_utils::SemverCompare "0.1.24" "0.1.23+1"\nPop $0\nStrCmp $0 1 legacy_newer_ok\nSetErrorLevel 1\nQuit\nlegacy_newer_ok:\nSetErrorLevel 0\nSectionEnd\n`);
const legacyBuilt = spawnSync(compiler, ['/V2', legacyScript], { encoding: 'utf8', windowsHide: true });
assert.equal(legacyBuilt.status, 0, legacyBuilt.stdout + legacyBuilt.stderr);
const legacyChecked = spawnSync(legacyExe, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
assert.equal(legacyChecked.status, 0, 'Older installers must detect the encoded hotfix as newer.');
} finally {
assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-version-')), true);
await rm(root, { recursive: true, force: true });
}
});
+42
View File
@@ -0,0 +1,42 @@
import assert from "node:assert/strict";
import test, { before, after } from "node:test";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import { existsSync } from "node:fs";
// The Table Formulas package comes from a sibling repository. Run `pnpm build:plugins` to build it.
const tableFormulasEntry = new URL("../../../plugin-packages/table-formulas/main.js", import.meta.url);
const tableFormulas = existsSync(tableFormulasEntry) ? await import(tableFormulasEntry.href) : undefined;
const activate = tableFormulas?.activate;
const needsTableFormulas = { skip: tableFormulas ? false : "the Table Formulas package is not built; run pnpm build:plugins" };
const session = new ExternalSession("runestone.table-formulas", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
before(() => activate && session.start({ activate }));
after(() => activate && session.stop());
import { tableCellMarkdown } from "../../../src/lib/editor/tableCellMarkdown.ts";
import { renderMarkdownHtml, renderMarkdownSections } from "../../../src/lib/workspace/noteHtml.ts";
test("Markdown rendering isolates tables and preserves literal, formatted, and non-table text", needsTableFormulas, () => {
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", needsTableFormulas, () => {
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`");
});
+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");
});
+106
View File
@@ -0,0 +1,106 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { CHARACTER_THEMES, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.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 });
}
});
function luminance(color: string) {
const rgb = color.slice(1).match(/../g)!.map(value => parseInt(value, 16) / 255)
.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4);
return rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722;
}
function contrast(foreground: string, background: string) {
const values = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (values[0] + 0.05) / (values[1] + 0.05);
}
test('Character palettes restore one appearance and export readable surfaces and syntax', () => {
for (const theme of Object.keys(CHARACTER_THEMES) as (keyof typeof CHARACTER_THEMES)[]) {
const exported = exportAppearanceTheme(theme);
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme, mode: CHARACTER_THEMES[theme].mode });
const colors = exported.colors;
for (const foreground of ['text', 'text-dim', 'text-strong', 'accent'] as const) {
for (const background of ['bg', 'bg-elevated', 'bg-active', 'selection'] as const) {
if (foreground === 'accent' && background === 'selection') continue;
assert(contrast(colors[foreground]!, colors[background]!) >= 4.5, `${theme} ${mode}: ${foreground} on ${background}`);
}
}
}
assert.deepEqual(themeModes(theme), [CHARACTER_THEMES[theme].mode]);
assert.equal(exported.schema, 2);
assert.deepEqual(parseCustomTheme(exported), exported);
for (const role of SYNTAX_ROLES) {
for (const background of ['bg', 'bg-active'] as const) {
assert(contrast(exported.colors[`syntax-${role}`]!, exported.colors[background]!) >= 4.5, `${theme}: ${role} on ${background}`);
}
}
assert(new Set(SYNTAX_ROLES.map(role => exported.colors[`syntax-${role}`])).size >= 7);
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);
});
+44
View File
@@ -0,0 +1,44 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { characterTheme, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts';
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);
}
test('Crimson Pilot text and syntax remain readable in active and selected states', () => {
const palette = characterTheme('crimson-pilot')!;
const [background, elevated, active, , dim, text, strong, accent, selection] = palette.surfaces;
const foregrounds = { dim, text, strong, accent, secondary: palette.secondary,
...Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, palette.syntax[index]])) };
for (const [role, foreground] of Object.entries(foregrounds)) {
for (const surface of [background, elevated, active, selection]) {
assert(contrast(foreground, surface) >= 4.5, `${role} on ${surface} needs 4.5:1 contrast`);
}
}
});
test('Crimson Pilot text remains readable on image-tinted editor and panel surfaces', () => {
const palette = characterTheme('crimson-pilot')!;
const [background, elevated, , , dim, text, strong] = palette.surfaces;
const editor = mix(background, '#ffffff', 0.9);
const codeBlock = mix(elevated, editor, 0.82);
const panel = mix(elevated, '#ffffff', 0.82);
for (const foreground of palette.syntax) {
for (const surface of [editor, codeBlock]) {
assert(contrast(foreground, surface) >= 4.5, `${foreground} on ${surface} needs 4.5:1 contrast`);
}
}
for (const foreground of [dim, text, strong]) {
assert(contrast(foreground, panel) >= 4.5, `${foreground} on image panel ${panel} needs 4.5:1 contrast`);
}
});
+155
View File
@@ -0,0 +1,155 @@
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 { BackgroundFrame, PluginApi } from '../../../src/lib/plugins/sdk.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('disable removes frames and subscriptions before cleanup and rejects pending file results', async () => {
let api!: PluginApi;
let finishRead!: (value: Uint8Array) => void;
let finishList!: (value: { name: string }[]) => void;
let finishPicker!: (value: string | null) => void;
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() },
backgrounds: {
chooseFolder: () => new Promise(resolve => { finishPicker = resolve; }),
list: () => new Promise(resolve => { finishList = resolve; }),
read: () => new Promise(resolve => { finishRead = resolve; }),
},
}, () => {}, () => {});
let notifications = 0;
await session.start({ activate(value) {
api = value;
api.backgrounds!.subscribe(() => { notifications++; });
api.backgrounds!.set('app', frame);
api.backgrounds!.set('pm-all', frame);
api.onDispose(() => {
assert.equal(backgroundHub.get('app'), null);
assert.equal(backgroundHub.get('pm-all'), null);
assert.throws(() => api.backgrounds!.get('app'), /disabled/);
});
} });
const pending = [api.backgrounds!.read('folder', 'file.png'), api.backgrounds!.list('folder'), api.backgrounds!.chooseFolder()];
const rejected = pending.map(request => assert.rejects(request, /disabled/));
await session.stop();
finishRead(new Uint8Array([1])); finishList([{ name: 'file.png' }]); finishPicker('folder');
await Promise.all(rejected);
assert.equal(notifications, 2);
assert.throws(() => api.backgrounds!.set('app', frame), /disabled/);
assert.throws(() => api.backgrounds!.read('folder', 'file.png'), /disabled/);
assert.throws(() => api.backgrounds!.subscribe(() => {}), /disabled/);
assert.equal(backgroundHub.get('app'), null);
});
test('background commands are allowed in main and settings windows', () => {
const build = readFileSync(new URL('../../../src-tauri/build.rs', import.meta.url), 'utf8');
for (const scope of ['default', 'settings']) {
const capability = JSON.parse(readFileSync(new URL(`../../../src-tauri/capabilities/${scope}.json`, import.meta.url), 'utf8'));
for (const command of ['backgrounds_choose_folder', 'backgrounds_default_folder', 'backgrounds_list', 'backgrounds_read', 'backgrounds_read_image_settings', 'backgrounds_write_image_settings']) {
assert(build.includes(`"${command}"`), `${command} needs a generated desktop permission`);
assert(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), `${scope} must allow ${command}`);
}
}
});
+111
View File
@@ -0,0 +1,111 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { COLOR_TOKENS, parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { applyTransparency, normalizeAppearance, exportAppearanceTheme, 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('Fixed theme palettes retain all supplied colors', () => {
assert.deepEqual(parseCustomTheme(theme), theme);
});
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 current color token 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).sort(), [...COLOR_TOKENS].sort());
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 legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } };
const stored = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]);
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.equal(JSON.parse(stored.get(CUSTOM_THEMES_KEY)!)[0].schema, 2);
assert.deepEqual(JSON.parse(stored.get(`${CUSTOM_THEMES_KEY}.legacy`)!)[0], legacy);
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
} finally { globalThis.localStorage = previous; }
});
test('Legacy migration storage failure leaves the original palette available', 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 raw = JSON.stringify([legacy]);
const previous = globalThis.localStorage;
let original = raw;
try {
globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? original : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage;
assert.deepEqual(customThemes('light')[0].colors, legacy.light);
assert.equal(original, raw);
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
} finally { globalThis.localStorage = previous; }
});
+40
View File
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { CHARACTER_THEMES, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts';
const rgb = (hex: string) => hex.match(/[0-9a-f]{2}/gi)!.map(channel => parseInt(channel, 16));
const luminance = (hex: string) => rgb(hex).map(channel => channel / 255)
.map(channel => channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4)
.reduce((sum, channel, index) => sum + channel * [.2126, .7152, .0722][index], 0);
const contrast = (a: string, b: string) => (Math.max(luminance(a), luminance(b)) + .05) / (Math.min(luminance(a), luminance(b)) + .05);
const mix = (a: string, b: string, ratio: number) => '#' + rgb(a)
.map((channel, index) => Math.round(channel * ratio + rgb(b)[index] * (1 - ratio)).toString(16).padStart(2, '0')).join('');
test('Silver Serpent text and syntax remain readable on opaque and image surfaces', () => {
const { surfaces, syntax, secondary } = CHARACTER_THEMES['silver-serpent'];
const [bg, elevated, active, , dim, text, strong, accent, selection] = surfaces;
const panelOnWhite = mix(elevated, '#ffffff', .82);
const editorOnWhite = mix(bg, '#ffffff', .9);
const backgrounds = {
bg, elevated, active, selection,
panelOnWhite,
editorOnWhite,
menuHoverOnWhite: mix(active, panelOnWhite, .82),
controlHoverOnWhite: mix(active, '#ffffff', .92),
codeBlockOnWhite: mix(elevated, editorOnWhite, .82),
};
const foregrounds = { dim, text, strong, accent, secondary,
...Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, syntax[index]])) };
for (const [backgroundName, background] of Object.entries(backgrounds)) {
for (const [foregroundName, foreground] of Object.entries(foregrounds)) {
assert(contrast(foreground, background) >= 4.5, `${foregroundName} on ${backgroundName}`);
}
}
});
test('Silver Serpent selection has a readable perimeter and a separate fill', () => {
const [bg, elevated, , , , , , accent, selection] = CHARACTER_THEMES['silver-serpent'].surfaces;
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');
});
+40
View File
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts';
const rgb = (color: string) => color.slice(1).match(/../g)!.map(value => parseInt(value, 16) / 255);
function luminance(color: string) {
return rgb(color).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 values = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (values[0] + 0.05) / (values[1] + 0.05);
}
test('Harvest Moon text and syntax stay readable on editor, panel, and selected surfaces', () => {
const palette = characterTheme('harvest-moon')!;
const [background, elevated, active, , dim, text, strong, accent, selection] = palette.surfaces;
for (const foreground of [dim, text, strong, accent, palette.secondary]) {
for (const surface of [background, elevated, active, selection]) {
assert(contrast(foreground, surface) >= 4.5, `${foreground} on ${surface} needs 4.5:1 contrast`);
}
}
for (const [index, foreground] of palette.syntax.entries()) {
for (const surface of [background, elevated, selection]) {
assert(contrast(foreground, surface) >= 4.5, `${SYNTAX_ROLES[index]} on ${surface} needs 4.5:1 contrast`);
}
}
});
test('Harvest Moon uses the warm character colors for all palette roles', () => {
const palette = characterTheme('harvest-moon')!;
for (const color of [...palette.surfaces, palette.secondary, ...palette.syntax]) {
assert.match(color, /^#[0-9a-f]{6}$/i);
const [red, green, blue] = rgb(color);
assert(red >= green && green >= blue, `${color} must follow the copper, amber, red, or cream palette`);
}
assert.equal(palette.mode, 'dark');
assert.equal(Object.keys(characterSyntax('harvest-moon')).length, SYNTAX_ROLES.length);
assert.deepEqual(characterSyntax('unknown'), {});
});
+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" });
});
+41
View File
@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import test from "node:test";
import { detectChrome, extensionOf, treeFileParts } from "../../../src/lib/workspace/chrome.ts";
import { monacoChrome } from "../../../src/lib/editor/monacoChrome.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"), "Ide");
assert.equal(detectChrome("tools/setup.sh"), "Ide");
assert.equal(detectChrome("Makefile"), "Ide");
});
test("writing chrome wraps and hides line numbers", () => {
assert.equal(monacoChrome("Writing").wordWrap, "on");
assert.equal(monacoChrome("Writing").lineNumbers, "off");
assert.equal(monacoChrome("Writing").minimap.enabled, false);
});
test("ide chrome shows line numbers and no wrap", () => {
assert.equal(monacoChrome("Ide").wordWrap, "off");
assert.equal(monacoChrome("Ide").lineNumbers, "on");
assert.equal(monacoChrome("Ide").minimap.enabled, 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.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("Ide");
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, "Ide");
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: [] });
});
+164
View File
@@ -0,0 +1,164 @@
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);
});
+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);
});