Translate Project Management and add its tests and guide

- Every interface string of Project Management goes through the catalog: 539 new rows with fr, ja, and zh-CN.
- Storage and model messages use a local message() marker and stay free of host imports. The interface translates them.
- A board renders again when the language changes. Dates use the interface language.
- Fix: the ribbon button waits for the feature switches at startup, and the settings code loads no feature module.
- Add six smoke tests: board state, cards, menus, drag and drop, views, and language.
- Add docs/guides/project-management.md and UI-060. Update the user, plugin, SDK, host, development, and interface docs and CLAUDE.md.
- Name the fake board view of tree/renameUndo "Board fixture", because the native Project Management button is now in the ribbon.
This commit is contained in:
Knotty Wyvern
2026-10-29 21:53:09 -07:00
parent e66f089176
commit 956ead818b
53 changed files with 2510 additions and 867 deletions
+32 -39
View File
@@ -8,6 +8,7 @@ import {
writeCatalog,
validateName,
} from "./catalog.ts";
import { message } from "./message.ts";
export interface BoardReference {
id: string;
@@ -41,9 +42,9 @@ export function defaultBoard(id: string = crypto.randomUUID()): Board {
kind: "board",
id,
lists: [
{ id: "todo", name: "To do", status: "todo", collapsed: false },
{ id: "doing", name: "In progress", status: "doing", collapsed: false },
{ id: "done", name: "Done", status: "done", collapsed: false },
{ id: "todo", name: message("To do"), status: "todo", collapsed: false },
{ id: "doing", name: message("In progress"), status: "doing", collapsed: false },
{ id: "done", name: message("Done"), status: "done", collapsed: false },
],
defaults: { todo: "todo", doing: "doing", done: "done" },
};
@@ -59,10 +60,8 @@ export function parseBoard(source: string): Board {
!Array.isArray(value.lists) ||
!value.defaults
)
throw new Error(
"The board file has an unsupported format. Restore or repair it before editing lists.",
);
if (value.backgroundImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(value.backgroundImage)) throw new Error("The board background image is invalid.");
throw new Error(message("The board file has an unsupported format. Restore or repair it before editing lists."));
if (value.backgroundImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(value.backgroundImage)) throw new Error(message("The board background image is invalid."));
const ids = new Set<string>();
for (const list of value.lists) {
if (
@@ -77,14 +76,12 @@ export function parseBoard(source: string): Board {
typeof list.collapsed !== "boolean" ||
(list.maxCards !== undefined && (!Number.isSafeInteger(list.maxCards) || list.maxCards < 1))
)
throw new Error(
"The board contains an invalid list. Repair the board file before editing.",
);
throw new Error(message("The board contains an invalid list. Repair the board file before editing."));
ids.add(list.id);
}
for (const status of statuses)
if (value.defaults[status] !== null && !ids.has(value.defaults[status]))
throw new Error("The board has an invalid default list.");
throw new Error(message("The board has an invalid default list."));
return value;
}
export function boardDocument(
@@ -110,7 +107,7 @@ export function newBoardSource(): string {
}
export class BoardStore {
value = defaultBoard("all-tasks");
name = "All tasks";
name: string = message("All tasks");
available = true;
archived = false;
private source: string | null = null;
@@ -134,7 +131,7 @@ export class BoardStore {
const snapshot = await readCatalog(this.workspace);
if (snapshot.value.deletedBoardIds?.includes(this.reference.id)) {
this.load();
throw new Error("This board was deleted. Open All tasks to find its cards.");
throw new Error(message("This board was deleted. Open All tasks to find its cards."));
}
const managed = snapshot.value.boards.find(
(board) => board.value.id === this.reference!.id,
@@ -145,9 +142,7 @@ export class BoardStore {
managed.original?.path !== this.reference.path ||
(current !== null && current !== managed.original.source)
)
throw new Error(
"The legacy board differs from hidden storage. Preserve both versions.",
);
throw new Error(message("The legacy board differs from hidden storage. Preserve both versions."));
this.load(
managedDocuments(snapshot.value, snapshot.source!).find(
(board) => board.id === this.reference!.id,
@@ -164,13 +159,13 @@ export class BoardStore {
),
);
if (!this.available)
throw new Error("This board is unavailable. Refresh Project Management.");
throw new Error(message("This board is unavailable. Refresh Project Management."));
return;
}
const source = await this.workspace.read(this.reference.path);
const document = boardDocument(source, this.reference.path);
if (!document || document.id !== this.reference.id)
throw new Error("The board changed. Reopen it from navigation.");
throw new Error(message("The board changed. Reopen it from navigation."));
this.load(document);
}
load(document?: BoardDocument) {
@@ -195,29 +190,27 @@ export class BoardStore {
}
async update(change: (board: Board) => void) {
if (!this.editable)
throw new Error("Open an available board to edit its lists.");
throw new Error(message("Open an available board to edit its lists."));
const expected = this.source;
if (!isManagedBoard(this.reference!.path) && this.workspace.readOptional) {
const snapshot = await readCatalog(this.workspace);
if (snapshot.value.deletedBoardIds?.includes(this.reference!.id))
throw new Error("This board was deleted. Open All tasks to find its cards.");
throw new Error(message("This board was deleted. Open All tasks to find its cards."));
if (
snapshot.value.boards.some(
(board) => board.value.id === this.reference!.id,
)
)
throw new Error(
"This board moved to hidden storage. Refresh before editing.",
);
throw new Error(message("This board moved to hidden storage. Refresh before editing."));
}
if (isManagedBoard(this.reference!.path)) {
const snapshot = await readCatalog(this.workspace);
if (snapshot.source !== expected)
throw new Error("The board changed. Refresh before editing its lists.");
throw new Error(message("The board changed. Refresh before editing its lists."));
const board = snapshot.value.boards.find(
(item) => item.value.id === this.reference!.id,
);
if (!board) throw new Error("The board is unavailable.");
if (!board) throw new Error(message("The board is unavailable."));
change(board.value);
this.source = await writeCatalog(
this.workspace,
@@ -229,7 +222,7 @@ export class BoardStore {
}
const current = await this.workspace.read(this.reference!.path);
if (current !== expected)
throw new Error("The board changed. Refresh before editing its lists.");
throw new Error(message("The board changed. Refresh before editing its lists."));
const next = structuredClone(this.value);
change(next);
const { doc, body, newline, match } = split(expected!);
@@ -243,21 +236,21 @@ export class BoardStore {
}
async deleteBoard() {
if (!this.reference || !this.available || this.source === null)
throw new Error("Open an available board before deleting it.");
throw new Error(message("Open an available board before deleting it."));
const { id, path } = this.reference;
const snapshot = await readCatalog(this.workspace);
if (snapshot.value.deletedBoardIds?.includes(id))
throw new Error("This board was already deleted. Refresh Project Management.");
throw new Error(message("This board was already deleted. Refresh Project Management."));
if (isManagedBoard(path)) {
if (snapshot.source !== this.source)
throw new Error("The board changed. Cancel, refresh, and review it before deleting.");
throw new Error(message("The board changed. Cancel, refresh, and review it before deleting."));
if (!snapshot.value.boards.some((board) => board.value.id === id))
throw new Error("The board is unavailable. Refresh Project Management.");
throw new Error(message("The board is unavailable. Refresh Project Management."));
} else {
if (snapshot.value.boards.some((board) => board.value.id === id))
throw new Error("This board moved to hidden storage. Refresh before deleting.");
throw new Error(message("This board moved to hidden storage. Refresh before deleting."));
if ((await this.workspace.read(path)) !== this.source)
throw new Error("The board changed. Cancel, refresh, and review it before deleting.");
throw new Error(message("The board changed. Cancel, refresh, and review it before deleting."));
}
snapshot.value.boards = snapshot.value.boards.filter((board) => board.value.id !== id);
// Keep originals and card memberships intact. The record prevents legacy rediscovery.
@@ -271,10 +264,10 @@ export class BoardStore {
!isManagedBoard(this.reference.path) ||
!this.available
)
throw new Error("Migrate this board before managing hidden storage.");
throw new Error(message("Migrate this board before managing hidden storage."));
const snapshot = await readCatalog(this.workspace);
if (snapshot.source !== this.source)
throw new Error("The board changed. Refresh before saving.");
throw new Error(message("The board changed. Refresh before saving."));
const board = snapshot.value.boards.find(
(item) => item.value.id === this.reference!.id,
)!;
@@ -288,7 +281,7 @@ export class BoardStore {
patch.name!.trim().toLocaleLowerCase(),
)
)
throw new Error("A board with this name already exists.");
throw new Error(message("A board with this name already exists."));
board.name = patch.name.trim();
}
if (patch.archived !== undefined) board.archived = patch.archived;
@@ -327,7 +320,7 @@ export class BoardStore {
}
async setLimit(id: string, maximum?: number) {
if (maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < 1))
throw new Error("Enter a whole number of at least 1, or leave the maximum blank.");
throw new Error(message("Enter a whole number of at least 1, or leave the maximum blank."));
await this.update((board) => {
const list = this.requireList(board, id);
if (maximum === undefined) delete list.maxCards;
@@ -356,12 +349,12 @@ export class BoardStore {
private requireList(board: Board, id: string) {
const list = board.lists.find((item) => item.id === id);
if (!list)
throw new Error("This list no longer exists. Refresh the board.");
throw new Error(message("This list no longer exists. Refresh the board."));
return list;
}
private checkName(board: Board, name: string, except?: string) {
if (!name.trim() || name.trim().length > 80)
throw new Error("Enter a list name of 1 to 80 characters.");
throw new Error(message("Enter a list name of 1 to 80 characters."));
if (
board.lists.some(
(list) =>
@@ -369,6 +362,6 @@ export class BoardStore {
list.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
)
)
throw new Error("A list with this name already exists.");
throw new Error(message("A list with this name already exists."));
}
}
+16 -12
View File
@@ -10,6 +10,12 @@ import {
readOptional,
saveDocument,
} from "./persistence.ts";
import { format, message } from "./message.ts";
/** The issue of one file: its path and its problem. */
export function fileIssue(path: string, problem: string) {
return format(message("In {path}: {problem}"), { path, problem });
}
export function cardPath(id: string) {
const key = Array.from(new TextEncoder().encode(id), (byte) =>
@@ -34,9 +40,7 @@ export function cardOrigin(source: string): OriginalFile | undefined {
.some((part: string) => !part || part === "." || part === "..") ||
origin.backup !== `.runestone/pm/backups/${origin.path}`
)
throw new Error(
"The card migration record is invalid. Keep the original note.",
);
throw new Error(message("The card migration record is invalid. Keep the original note."));
return origin;
}
/** Read one hidden card file. It throws when the file is invalid or when its name does not match the card ID. */
@@ -44,7 +48,7 @@ export function parseCard(path: string, source: string): Task {
cardOrigin(source);
const task = readTask(path, source);
if (!task || cardPath(task.id) !== path)
throw new Error("The hidden card ID does not match its storage path.");
throw new Error(message("The hidden card ID does not match its storage path."));
return task;
}
export async function prepareCards(workspace: Workspace) {
@@ -75,14 +79,14 @@ export async function readCards(
const documents = await mapConcurrent(entries, async (entry) => {
try {
const result = sources.get(entry.rel_path)!;
if (result.error || result.source === undefined) throw new Error(result.error ?? "The card is unavailable.");
if (result.error || result.source === undefined) throw new Error(result.error ?? message("The card is unavailable."));
const source = result.source;
const cached = previous.get(entry.rel_path);
if (cached?.source === source) return { task: cached };
return { task: parseCard(entry.rel_path, source) };
} catch (error) {
return {
issue: `${entry.rel_path}: ${error instanceof Error ? error.message : String(error)}`,
issue: fileIssue(entry.rel_path, error instanceof Error ? error.message : String(error)),
};
}
});
@@ -111,19 +115,19 @@ export async function migrateCards(workspace: Workspace, tasks: Task[]) {
if (isHiddenCard(task.path)) continue;
if ((await workspace.read(task.path)) !== task.source)
throw new Error(
`The card changed: ${task.path}. Refresh before migration.`,
format(message("The card changed: {path}. Refresh before migration."), { path: task.path }),
);
const destination = await readOptional(workspace, cardPath(task.id));
if (destination !== null) {
const origin = cardOrigin(destination);
if (origin?.path !== task.path || origin.source !== task.source)
throw new Error(
`A different hidden card already uses the ID from ${task.path}.`,
format(message("A different hidden card already uses the ID from {path}."), { path: task.path }),
);
}
if (split(task.source).doc.has("runestone_pm_origin"))
throw new Error(
`The note already contains a migration record: ${task.path}. Review it before migration.`,
format(message("The note already contains a migration record: {path}. Review it before migration."), { path: task.path }),
);
}
for (const task of tasks) {
@@ -149,15 +153,15 @@ export async function migrateCards(workspace: Workspace, tasks: Task[]) {
copied.body !== task.body
)
throw new Error(
`The card copy differs from ${task.path}. Keep the original.`,
format(message("The card copy differs from {path}. Keep the original."), { path: task.path }),
);
if ((await workspace.read(task.path)) !== task.source)
throw new Error(`The card changed: ${task.path}. Retry migration.`);
throw new Error(format(message("The card changed: {path}. Retry migration."), { path: task.path }));
await prepareCards(workspace);
await saveDocument(workspace, path, source, null);
if ((await workspace.read(path)) !== source)
throw new Error(
`The saved card check failed: ${task.path}. Keep the original.`,
format(message("The saved card check failed: {path}. Keep the original."), { path: task.path }),
);
}
}
+14 -15
View File
@@ -7,6 +7,7 @@ import {
} from "./board.ts";
import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts";
import { format, message } from "./message.ts";
export const catalogPath = ".runestone/pm/workspace.json";
export const boardKey = (id: string) => `pm-board:${id}`;
@@ -33,15 +34,13 @@ export function boardMarkdown(value: Board): string {
}
export function validateName(name: string) {
if (!name.trim() || name.trim().length > 100 || /[\x00-\x1f]/.test(name))
throw new Error("Enter a board name of 1 to 100 characters.");
throw new Error(message("Enter a board name of 1 to 100 characters."));
}
export function parseCatalog(source: string | null): Catalog {
if (source === null) return { schema: 1, boards: [] };
const data = JSON.parse(source);
if (!data || data.schema !== 1 || !Array.isArray(data.boards))
throw new Error(
"The Project Management storage format is unsupported. Restore a backup or update Project Management.",
);
throw new Error(message("The Project Management storage format is unsupported. Restore a backup or update Project Management."));
const ids = new Set<string>();
if (
data.deletedBoardIds !== undefined &&
@@ -49,26 +48,26 @@ export function parseCatalog(source: string | null): Catalog {
data.deletedBoardIds.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
new Set(data.deletedBoardIds).size !== data.deletedBoardIds.length)
)
throw new Error("The deleted board record is invalid.");
throw new Error(message("The deleted board record is invalid."));
for (const board of data.boards) {
if (!board || typeof board.name !== "string")
throw new Error("A saved board has no name.");
throw new Error(message("A saved board has no name."));
validateName(board.name);
parseBoard(boardMarkdown(board.value));
if (ids.has(board.value.id))
throw new Error("Project Management storage contains duplicate board IDs.");
throw new Error(message("Project Management storage contains duplicate board IDs."));
ids.add(board.value.id);
if (data.deletedBoardIds?.includes(board.value.id))
throw new Error("A deleted board still has an active storage entry.");
throw new Error(message("A deleted board still has an active storage entry."));
if (board.archived !== undefined && typeof board.archived !== "boolean")
throw new Error("The board archive state is invalid.");
throw new Error(message("The board archive state is invalid."));
if (
board.original &&
(typeof board.original.path !== "string" ||
typeof board.original.source !== "string" ||
typeof board.original.backup !== "string")
)
throw new Error("The board migration record is invalid.");
throw new Error(message("The board migration record is invalid."));
}
return data;
}
@@ -82,7 +81,7 @@ export async function writeCatalog(
expected: string | null,
) {
if (!workspace.readOptional)
throw new Error("Update RuneStone to use hidden Project Management storage.");
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
const source = JSON.stringify(value, null, 2) + "\n";
parseCatalog(source);
await saveDocument(workspace, catalogPath, source, expected);
@@ -110,7 +109,7 @@ export async function createBoard(workspace: Workspace, name: string) {
board.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
)
)
throw new Error("A board with this name already exists.");
throw new Error(message("A board with this name already exists."));
const value = defaultBoard();
snapshot.value.boards.push({ name: name.trim(), value });
await writeCatalog(workspace, snapshot.value, snapshot.source);
@@ -126,15 +125,15 @@ export async function backupFile(
path.includes("\\") ||
path.split("/").some((part) => !part || part === ".." || part === ".")
)
throw new Error("The migration source path is invalid.");
throw new Error(message("The migration source path is invalid."));
const backup = `.runestone/pm/backups/${path}`;
const saved = await readOptional(workspace, backup);
if (saved === null) await saveDocument(workspace, backup, source, null);
else if (saved !== source)
throw new Error(
`The backup differs from ${path}. Preserve both versions before migration.`,
format(message("The backup differs from {path}. Preserve both versions before migration."), { path }),
);
if ((await workspace.read(backup)) !== source)
throw new Error(`Backup check failed for ${path}.`);
throw new Error(format(message("The backup check failed for {path}."), { path }));
return { path, source, backup };
}
+2 -1
View File
@@ -1,5 +1,6 @@
import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts";
export const deletedCardsPath = ".runestone/pm/deleted-cards.json";
@@ -10,7 +11,7 @@ export async function readDeletedCards(workspace: Workspace) {
if (value?.schema !== 1 || !Array.isArray(value.ids) ||
value.ids.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
new Set(value.ids).size !== value.ids.length)
throw new Error("The deleted card record is invalid. Restore it before editing cards.");
throw new Error(message("The deleted card record is invalid. Restore it before editing cards."));
return { source, ids: value.ids as string[] };
}
@@ -1,5 +1,6 @@
import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts";
/** A draft is separate from the saved card and uses compare-and-write protection. */
export class DescriptionDraft {
@@ -17,7 +18,7 @@ export class DescriptionDraft {
if (this.source === null) return null;
const value = JSON.parse(this.source);
if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string"))
throw new Error("The description draft is invalid. Preserve it before recovery.");
throw new Error(message("The description draft is invalid. Preserve it before recovery."));
return value.body;
}
save(body: string | null): Promise<void> {
+5 -4
View File
@@ -1,5 +1,6 @@
import type { Workspace, TaskFields } from "../model/model.ts";
import { saveDocument, storageRoot } from "./persistence.ts";
import { message } from "./message.ts";
export const maxImageBytes = 50 * 1024 * 1024;
export const imageTypes = [
@@ -13,7 +14,7 @@ const idPattern =
export const imageFolder = `${storageRoot}/images`;
export function imagePath(id: string) {
if (!new RegExp(`^${idPattern}$`).test(id))
throw new Error("The image ID is invalid.");
throw new Error(message("The image ID is invalid."));
return `${imageFolder}/${id}.json`;
}
export function imageReferences(body: string) {
@@ -34,10 +35,10 @@ export function imageMarkdown(name: string, id: string) {
}
export function parseImage(source: string): string {
if (source.length > Math.ceil(maxImageBytes / 3) * 4 + 256)
throw new Error("The saved image exceeds the 50 MiB limit.");
throw new Error(message("The saved image exceeds the 50 MiB limit."));
const value = JSON.parse(source);
if (value?.schema !== 1 || typeof value.data !== "string")
throw new Error("The saved image is invalid.");
throw new Error(message("The saved image is invalid."));
const match =
/^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(
value.data,
@@ -47,7 +48,7 @@ export function parseImage(source: string): string {
match[2].length % 4 !== 0 ||
atob(match[2]).length > maxImageBytes
)
throw new Error("The saved image is invalid or exceeds 50 MiB.");
throw new Error(message("The saved image is invalid or exceeds 50 MiB."));
return value.data;
}
export async function saveImages(
+13 -18
View File
@@ -1,5 +1,6 @@
import { cardColors, type Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts";
export const labelsPath = ".runestone/pm/labels.json";
export const legacyLabelsPath = "runestone-pm-labels.json";
@@ -24,7 +25,7 @@ export function defaultLabels(): SavedLabel[] {
export function validateLabels(
labels: unknown,
): asserts labels is SavedLabel[] {
if (!Array.isArray(labels)) throw new Error("Saved labels must be a list.");
if (!Array.isArray(labels)) throw new Error(message("Saved labels must be a list."));
const ids = new Set<string>(),
names = new Set<string>();
for (const label of labels) {
@@ -36,26 +37,24 @@ export function validateLabels(
!/^[a-zA-Z0-9_-]{1,100}$/.test(label.id) ||
ids.has(label.id)
)
throw new Error("Each saved label needs a unique ID.");
throw new Error(message("Each saved label needs a unique ID."));
if (
typeof label.name !== "string" ||
!label.name.trim() ||
label.name.trim().length > 80 ||
/[\x00-\x1f\x7f]/.test(label.name)
)
throw new Error("Enter a label name of 1 to 80 characters.");
throw new Error(message("Enter a label name of 1 to 80 characters."));
const name = label.name.trim().toLocaleLowerCase();
if (names.has(name))
throw new Error(
"Use a different name for each label, including archived labels.",
);
throw new Error(message("Use a different name for each label, including archived labels."));
if (
typeof label.color !== "string" ||
!Object.hasOwn(cardColors, label.color)
)
throw new Error("Choose a supported label color.");
throw new Error(message("Choose a supported label color."));
if (label.archived !== undefined && typeof label.archived !== "boolean")
throw new Error("Label archive state must be true or false.");
throw new Error(message("The label archive state must be true or false."));
ids.add(label.id);
names.add(name);
}
@@ -66,7 +65,7 @@ export function parseLabels(source: string | null): LabelSnapshot {
try {
data = JSON.parse(source);
} catch {
throw new Error("Fix the saved labels file before editing labels.");
throw new Error(message("Fix the saved labels file before editing labels."));
}
if (
!data ||
@@ -74,7 +73,7 @@ export function parseLabels(source: string | null): LabelSnapshot {
Array.isArray(data) ||
data.schema !== 1
)
throw new Error("The saved labels file has an unsupported schema.");
throw new Error(message("The saved labels file has an unsupported schema."));
validateLabels(data.labels);
return { source, labels: data.labels };
}
@@ -102,15 +101,11 @@ export class LabelStore {
}
checkSave(labels: SavedLabel[], expected: string | null | undefined): asserts expected is string | null {
if (this.legacy)
throw new Error(
"Use the workspace migration tool before editing legacy labels. See the Project Management development guide.",
);
throw new Error(message("Use the workspace migration tool before editing legacy labels. See the Project Management development guide."));
if (!this.workspace.readOptional)
throw new Error("Update RuneStone to use hidden Project Management storage.");
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
if (expected === undefined || this.error)
throw new Error(
"Saved labels are unavailable. Refresh before editing labels.",
);
throw new Error(message("Saved labels are unavailable. Refresh before editing labels."));
validateLabels(labels);
}
async save(labels: SavedLabel[], expected: string | null | undefined, allowDelete = false) {
@@ -121,7 +116,7 @@ export class LabelStore {
(label) => !labels.some((next) => next.id === label.id),
)
)
throw new Error("Archive unused labels to preserve existing cards.");
throw new Error(message("Archive unused labels to preserve existing cards."));
const data = expected === null ? { schema: 1 } : JSON.parse(expected);
const source =
JSON.stringify(
+13
View File
@@ -0,0 +1,13 @@
// The user-visible text of the storage code and the domain code. These folders use no host module, so the skill helper
// can bundle them for Node. `message()` marks a key of the host catalog (`src/lib/i18n/messages.ts`), and the catalog
// audit counts it. The text stays English here. The interface translates it with `localize()` (`../ui/text.ts`).
/** Mark a catalog key. It returns the text unchanged. */
export function message<T extends string>(text: T): T {
return text;
}
/** Put the values into the `{name}` placeholders of a catalog key. */
export function format(template: string, values: Record<string, string | number>): string {
return template.replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match);
}
+12 -13
View File
@@ -14,6 +14,7 @@ import {
saveDocument,
ensurePrivateStorage,
} from "./persistence.ts";
import { format, message } from "./message.ts";
/** Retain originals until the user checks the boards and removes the listed files. */
export async function migrateStorage(
@@ -22,7 +23,7 @@ export async function migrateStorage(
cards: Task[] = [],
) {
if (!workspace.readOptional || !workspace.create)
throw new Error("Update RuneStone before migrating Project Management storage.");
throw new Error(message("Update RuneStone before migrating Project Management storage."));
const snapshot = await readCatalog(workspace);
const legacy = boards.filter((board) => !isManagedBoard(board.path));
const legacyLabels = await readOptional(workspace, legacyLabelsPath);
@@ -32,10 +33,10 @@ export async function migrateStorage(
// Validate every source before creating backups or publishing any changes.
for (const board of legacy) {
if (snapshot.value.deletedBoardIds?.includes(board.id))
throw new Error("This board was deleted. Refresh Project Management before migration.");
throw new Error(message("This board was deleted. Refresh Project Management before migration."));
if ((await workspace.read(board.path)) !== board.source)
throw new Error(
`The board changed: ${board.path}. Refresh before migration.`,
format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
);
const existing = snapshot.value.boards.find(
(item) => item.value.id === board.id,
@@ -46,7 +47,7 @@ export async function migrateStorage(
existing.original.source !== board.source)
)
throw new Error(
`A different board already uses the ID from ${board.path}.`,
format(message("A different board already uses the ID from {path}."), { path: board.path }),
);
}
if (legacyLabels !== null && savedLabels !== null) {
@@ -55,9 +56,7 @@ export async function migrateStorage(
original?.path !== legacyLabelsPath ||
original?.source !== legacyLabels
)
throw new Error(
"Hidden labels and legacy labels both exist. Resolve their differences before migration.",
);
throw new Error(message("Hidden labels and legacy labels both exist. Resolve their differences before migration."));
}
await ensurePrivateStorage(workspace);
let changed = false;
@@ -79,10 +78,10 @@ export async function migrateStorage(
for (const board of legacy)
if ((await workspace.read(board.path)) !== board.source)
throw new Error(
`The board changed: ${board.path}. Refresh before migration.`,
format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
);
if (legacyLabels !== (await readOptional(workspace, legacyLabelsPath)))
throw new Error("Legacy labels changed. Refresh before migration.");
throw new Error(message("Legacy labels changed. Refresh before migration."));
if (changed) await writeCatalog(workspace, snapshot.value, snapshot.source);
if (labelBackup) {
const source =
@@ -93,7 +92,7 @@ export async function migrateStorage(
) + "\n";
await saveDocument(workspace, labelsPath, source, null);
if ((await workspace.read(labelsPath)) !== source)
throw new Error("The saved label check failed. Retry migration.");
throw new Error(message("The saved label check failed. Retry migration."));
}
const saved = await readCatalog(workspace);
for (const board of legacy) {
@@ -105,19 +104,19 @@ export async function migrateStorage(
entry?.original?.source !== board.source ||
JSON.stringify(entry) !== JSON.stringify(expected)
)
throw new Error("The saved board check failed. Retry migration.");
throw new Error(message("The saved board check failed. Retry migration."));
}
await migrateCards(workspace, cards);
const files = await migrationFiles(workspace);
for (const file of files) {
if ((await workspace.read(file.backup)) !== file.source)
throw new Error(
`Backup check failed for ${file.path}. Keep the original.`,
format(message("The backup check failed for {path}. Keep the original."), { path: file.path }),
);
const current = await readOptional(workspace, file.path);
if (current !== null && current !== file.source)
throw new Error(
`The original changed: ${file.path}. Keep both versions.`,
format(message("The original changed: {path}. Keep both versions."), { path: file.path }),
);
}
return files;
+12 -17
View File
@@ -7,24 +7,21 @@ import {
type Status,
type Session,
} from "../model/model.ts";
import { message } from "./message.ts";
const frontmatter =
/^(\uFEFF?)(---[ \t]*\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$))/;
export function split(source: string) {
const match = frontmatter.exec(source);
if (!match && /^\uFEFF?---[ \t]*\r?\n/.test(source))
throw new Error(
"Close the YAML properties block before editing this note.",
);
throw new Error(message("Close the YAML properties block before editing this note."));
const doc = match
? parseDocument(match[3], { uniqueKeys: true, keepSourceTokens: true })
: new Document({});
if (doc.errors.length || doc.warnings.length)
throw new Error(
"Fix invalid or unsupported YAML properties before editing this note.",
);
throw new Error(message("Fix invalid or unsupported YAML properties before editing this note."));
if (!isMap(doc.contents))
throw new Error("Note properties must be a YAML mapping.");
throw new Error(message("Note properties must be a YAML mapping."));
return {
match,
doc,
@@ -48,22 +45,22 @@ export function readTask(path: string, source: string): Task | null {
typeof pm.id !== "string" ||
!pm.id.trim()
) {
throw new Error("This note has an unsupported Project Management schema, kind, or ID.");
throw new Error(message("This note has an unsupported Project Management schema, kind, or ID."));
}
if (pm.archived !== undefined && typeof pm.archived !== "boolean")
throw new Error("Archive state must be true or false.");
throw new Error(message("The archive state must be true or false."));
if (
pm.due !== undefined &&
(!record(pm.due) || typeof pm.due.date !== "string")
)
throw new Error("This preview supports date-only deadlines.");
throw new Error(message("This preview supports date-only deadlines."));
if (
pm.plan !== undefined &&
(!record(pm.plan) ||
typeof pm.plan.start !== "string" ||
typeof pm.plan.end !== "string")
)
throw new Error("The plan needs a start and an exclusive end date.");
throw new Error(message("The plan needs a start and an exclusive end date."));
if (
pm.sessions !== undefined &&
(!Array.isArray(pm.sessions) ||
@@ -76,7 +73,7 @@ export function readTask(path: string, source: string): Task | null {
typeof value.timeZone !== "string",
))
) {
throw new Error("Sessions need an ID, start, end, and time zone.");
throw new Error(message("Sessions need an ID, start, end, and time zone."));
}
const task: Task = {
id: pm.id,
@@ -126,7 +123,7 @@ export function editTask(
): string {
const fields = { ...task, title: undefined, ...patch };
if (Object.hasOwn(patch, "createdAt") && patch.createdAt !== task.createdAt)
throw new Error("The card creation timestamp cannot change.");
throw new Error(message("The card creation timestamp cannot change."));
validateFields(fields);
const { doc, match, newline } = split(task.source);
for (const key of [
@@ -180,7 +177,7 @@ export function newTask(
/[. ]$/.test(title) ||
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(title)
)
throw new Error("Use a valid note name of 1 to 100 characters.");
throw new Error(message("Use a valid note name of 1 to 100 characters."));
validateFields(fields);
const doc = new Document({
runestone_pm: { schema: 1, id, kind: "task", ...fields, createdAt: fields.createdAt ?? new Date().toISOString() },
@@ -194,9 +191,7 @@ export function adoptNote(path: string, source: string): string {
if (readTask(path, source)) return source;
const { doc, body, match, newline } = split(source);
if (doc.has("runestone_pm"))
throw new Error(
"This document already contains Project Management data and cannot become a task.",
);
throw new Error(message("This document already contains Project Management data and cannot become a task."));
doc.set("runestone_pm", {
schema: 1,
id: crypto.randomUUID(),
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Task } from "../model/model.ts";
import { message } from "./message.ts";
const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
const encode = (text: string) =>
@@ -27,7 +28,7 @@ export function compareCards(a: Task, b: Task, boardId?: string): number {
export function orderBetween(lower?: string, upper?: string): string {
if (lower !== undefined && upper !== undefined && lower >= upper)
throw new Error("The card order changed. Refresh the board.");
throw new Error(message("The card order changed. Refresh the board."));
let result = "";
for (let index = 0; ; index++) {
const low =
+4 -5
View File
@@ -1,4 +1,5 @@
import type { Workspace } from "../model/model.ts";
import { message } from "./message.ts";
export const storageRoot = ".runestone/pm";
export const privateRulesPath = `${storageRoot}/.gitignore`;
@@ -10,7 +11,7 @@ export const isHiddenCard = (path: string) =>
/** Install the local exclusion before publishing any private Project Management data. */
export async function ensurePrivateStorage(workspace: Workspace) {
if (!workspace.readOptional || !workspace.create)
throw new Error("Update RuneStone to use hidden Project Management storage.");
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
const expected = await workspace.readOptional(privateRulesPath);
const rules = expected
?.split(/\r?\n/)
@@ -28,9 +29,7 @@ export async function ensurePrivateStorage(workspace: Workspace) {
}
} else await workspace.write(privateRulesPath, source, expected);
if ((await workspace.readOptional(privateRulesPath)) !== source)
throw new Error(
"The Project Management Git exclusion changed. Retry before saving private data.",
);
throw new Error(message("The Project Management Git exclusion changed. Retry before saving private data."));
}
/** Older hosts cannot discover hidden files through the root listing. */
@@ -55,7 +54,7 @@ export async function saveDocument(
await ensurePrivateStorage(workspace);
if (expected === null) {
if (!workspace.create)
throw new Error("Update RuneStone to create Project Management storage.");
throw new Error(message("Update RuneStone to create Project Management storage."));
await workspace.create(path, source);
} else await workspace.write(path, source, expected);
}
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Workspace } from "../model/model.ts";
import { message } from "./message.ts";
// Limit concurrent bridge requests, including large workspaces with many notes.
export const scanConcurrency = 8;
@@ -12,7 +13,7 @@ export async function readSources(workspace: Workspace, paths: string[]) {
const rows = await workspace.readMany(batch);
for (const path of batch) {
const row = rows.find(row => row.path === path);
results.set(path, row && (typeof row.source === "string" || row.error) ? row : { error: "The batch did not return this file." });
results.set(path, row && (typeof row.source === "string" || row.error) ? row : { error: message("The batch did not return this file.") });
}
}
} else {