Make Project Management a native feature
- Move the storage and model of the plugin into src/lib/features/pm/ as pure TypeScript, so the skill can still bundle them. - Move the DOM interface onto the host menus, the shared tooltip, and the host icons. - A ribbon button opens Project Management. Board tabs keep the owner runestone.pm and the board-<hex> view IDs through view patterns. - Read only .runestone/pm/. Offer the plugin migration, with backups, for legacy notes. - A save, move, or delete reads only that card again. Watcher paths reach the feature. - Add Settings → Project Management and the projectManagement section. View states move to localStorage. - Background reads the boards from workspace.json. Remove api.backgrounds and the boards service. - Add yaml 2.9.1. Use the host markdown-it. - Move 18 plugin test files to tests/unit/features/pm/ and add native tests.
This commit is contained in:
@@ -0,0 +1,374 @@
|
||||
import { statuses, type Status, type Task, type Workspace } from "../model/model.ts";
|
||||
import { Document } from "yaml";
|
||||
import { split } from "./notes.ts";
|
||||
import {
|
||||
isManagedBoard,
|
||||
readCatalog,
|
||||
managedDocuments,
|
||||
writeCatalog,
|
||||
validateName,
|
||||
} from "./catalog.ts";
|
||||
|
||||
export interface BoardReference {
|
||||
id: string;
|
||||
path: string;
|
||||
}
|
||||
export interface BoardDocument extends BoardReference {
|
||||
name: string;
|
||||
value: Board;
|
||||
source: string;
|
||||
archived?: boolean;
|
||||
}
|
||||
export interface BoardList {
|
||||
id: string;
|
||||
name: string;
|
||||
status: Status | null;
|
||||
collapsed: boolean;
|
||||
maxCards?: number;
|
||||
}
|
||||
export interface Board {
|
||||
schema: 1;
|
||||
kind: "board";
|
||||
id: string;
|
||||
lists: BoardList[];
|
||||
backgroundImage?: string | null;
|
||||
backgroundAppearance?: import("../model/background.ts").BackgroundAppearance;
|
||||
defaults: Record<Status, string | null>;
|
||||
}
|
||||
export function defaultBoard(id: string = crypto.randomUUID()): Board {
|
||||
return {
|
||||
schema: 1,
|
||||
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 },
|
||||
],
|
||||
defaults: { todo: "todo", doing: "doing", done: "done" },
|
||||
};
|
||||
}
|
||||
export function parseBoard(source: string): Board {
|
||||
const value = split(source).doc.toJS({ maxAliasCount: 50 }).runestone_pm;
|
||||
if (
|
||||
!value ||
|
||||
value.schema !== 1 ||
|
||||
value.kind !== "board" ||
|
||||
typeof value.id !== "string" ||
|
||||
!value.id.trim() ||
|
||||
!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.");
|
||||
const ids = new Set<string>();
|
||||
for (const list of value.lists) {
|
||||
if (
|
||||
!list ||
|
||||
typeof list.id !== "string" ||
|
||||
!list.id ||
|
||||
ids.has(list.id) ||
|
||||
typeof list.name !== "string" ||
|
||||
!list.name.trim() ||
|
||||
list.name.length > 80 ||
|
||||
(list.status !== null && !statuses.includes(list.status)) ||
|
||||
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.",
|
||||
);
|
||||
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.");
|
||||
return value;
|
||||
}
|
||||
export function boardDocument(
|
||||
source: string,
|
||||
path: string,
|
||||
): BoardDocument | null {
|
||||
const value = split(source).doc.toJS({ maxAliasCount: 50 }).runestone_pm;
|
||||
if (value?.kind !== "board") return null;
|
||||
const board = parseBoard(source);
|
||||
return {
|
||||
id: board.id,
|
||||
path,
|
||||
name: path
|
||||
.split("/")
|
||||
.at(-1)!
|
||||
.replace(/\.(md|markdown|mdown)$/i, ""),
|
||||
value: board,
|
||||
source,
|
||||
};
|
||||
}
|
||||
export function newBoardSource(): string {
|
||||
return `---\n${new Document({ runestone_pm: defaultBoard() }).toString({ lineWidth: 0 })}---\n`;
|
||||
}
|
||||
export class BoardStore {
|
||||
value = defaultBoard("all-tasks");
|
||||
name = "All tasks";
|
||||
available = true;
|
||||
archived = false;
|
||||
private source: string | null = null;
|
||||
private workspace: Workspace;
|
||||
readonly reference?: BoardReference;
|
||||
constructor(workspace: Workspace, reference?: BoardReference) {
|
||||
this.workspace = workspace;
|
||||
this.reference = reference ? { ...reference } : undefined;
|
||||
}
|
||||
get editable() {
|
||||
return (
|
||||
!!this.reference &&
|
||||
this.available &&
|
||||
!this.archived &&
|
||||
this.source !== null
|
||||
);
|
||||
}
|
||||
async reload() {
|
||||
if (!this.reference) return;
|
||||
if (!isManagedBoard(this.reference.path) && this.workspace.readOptional) {
|
||||
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.");
|
||||
}
|
||||
const managed = snapshot.value.boards.find(
|
||||
(board) => board.value.id === this.reference!.id,
|
||||
);
|
||||
if (managed) {
|
||||
const current = await this.workspace.readOptional(this.reference.path);
|
||||
if (
|
||||
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.",
|
||||
);
|
||||
this.load(
|
||||
managedDocuments(snapshot.value, snapshot.source!).find(
|
||||
(board) => board.id === this.reference!.id,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (isManagedBoard(this.reference.path)) {
|
||||
const snapshot = await readCatalog(this.workspace);
|
||||
this.load(
|
||||
managedDocuments(snapshot.value, snapshot.source ?? "").find(
|
||||
(board) => board.id === this.reference!.id,
|
||||
),
|
||||
);
|
||||
if (!this.available)
|
||||
throw new Error("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.");
|
||||
this.load(document);
|
||||
}
|
||||
load(document?: BoardDocument) {
|
||||
if (!this.reference) return;
|
||||
this.available = !!document;
|
||||
this.source = document?.source ?? null;
|
||||
if (document) {
|
||||
this.reference.path = document.path;
|
||||
this.value = document.value;
|
||||
this.name = document.name;
|
||||
this.archived = document.archived ?? false;
|
||||
}
|
||||
}
|
||||
listFor(
|
||||
task: Pick<Task, "listId" | "status" | "placements">,
|
||||
): BoardList | undefined {
|
||||
const id = this.reference
|
||||
? (task.placements?.[this.reference.id]?.listId ??
|
||||
(task.listId !== undefined ? task.listId : null))
|
||||
: this.value.defaults[task.status];
|
||||
return this.value.lists.find((list) => list.id === id);
|
||||
}
|
||||
async update(change: (board: Board) => void) {
|
||||
if (!this.editable)
|
||||
throw new Error("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.");
|
||||
if (
|
||||
snapshot.value.boards.some(
|
||||
(board) => board.value.id === this.reference!.id,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
"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.");
|
||||
const board = snapshot.value.boards.find(
|
||||
(item) => item.value.id === this.reference!.id,
|
||||
);
|
||||
if (!board) throw new Error("The board is unavailable.");
|
||||
change(board.value);
|
||||
this.source = await writeCatalog(
|
||||
this.workspace,
|
||||
snapshot.value,
|
||||
expected,
|
||||
);
|
||||
this.value = board.value;
|
||||
return;
|
||||
}
|
||||
const current = await this.workspace.read(this.reference!.path);
|
||||
if (current !== expected)
|
||||
throw new Error("The board changed. Refresh before editing its lists.");
|
||||
const next = structuredClone(this.value);
|
||||
change(next);
|
||||
const { doc, body, newline, match } = split(expected!);
|
||||
for (const key of ["lists", "defaults", "backgroundImage", "backgroundAppearance"] as const)
|
||||
if (next[key] !== undefined) doc.setIn(["runestone_pm", key], next[key]);
|
||||
const source = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||
parseBoard(source);
|
||||
await this.workspace.write(this.reference!.path, source, expected!);
|
||||
this.source = source;
|
||||
this.value = next;
|
||||
}
|
||||
async deleteBoard() {
|
||||
if (!this.reference || !this.available || this.source === null)
|
||||
throw new Error("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.");
|
||||
if (isManagedBoard(path)) {
|
||||
if (snapshot.source !== this.source)
|
||||
throw new Error("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.");
|
||||
} else {
|
||||
if (snapshot.value.boards.some((board) => board.value.id === id))
|
||||
throw new Error("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.");
|
||||
}
|
||||
snapshot.value.boards = snapshot.value.boards.filter((board) => board.value.id !== id);
|
||||
// Keep originals and card memberships intact. The record prevents legacy rediscovery.
|
||||
snapshot.value.deletedBoardIds = [...(snapshot.value.deletedBoardIds ?? []), id];
|
||||
await writeCatalog(this.workspace, snapshot.value, snapshot.source);
|
||||
this.load();
|
||||
}
|
||||
async manage(patch: { name?: string; archived?: boolean }) {
|
||||
if (
|
||||
!this.reference ||
|
||||
!isManagedBoard(this.reference.path) ||
|
||||
!this.available
|
||||
)
|
||||
throw new Error("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.");
|
||||
const board = snapshot.value.boards.find(
|
||||
(item) => item.value.id === this.reference!.id,
|
||||
)!;
|
||||
if (patch.name !== undefined) {
|
||||
validateName(patch.name);
|
||||
if (
|
||||
snapshot.value.boards.some(
|
||||
(item) =>
|
||||
item !== board &&
|
||||
item.name.toLocaleLowerCase() ===
|
||||
patch.name!.trim().toLocaleLowerCase(),
|
||||
)
|
||||
)
|
||||
throw new Error("A board with this name already exists.");
|
||||
board.name = patch.name.trim();
|
||||
}
|
||||
if (patch.archived !== undefined) board.archived = patch.archived;
|
||||
this.source = await writeCatalog(
|
||||
this.workspace,
|
||||
snapshot.value,
|
||||
snapshot.source,
|
||||
);
|
||||
this.name = board.name;
|
||||
this.archived = board.archived ?? false;
|
||||
}
|
||||
async add(name: string, status: Status | null) {
|
||||
await this.update((board) => {
|
||||
this.checkName(board, name);
|
||||
board.lists.push({
|
||||
id: crypto.randomUUID(),
|
||||
name: name.trim(),
|
||||
status,
|
||||
collapsed: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
async edit(id: string, name: string, status: Status | null) {
|
||||
await this.update((board) => {
|
||||
this.checkName(board, name, id);
|
||||
const list = this.requireList(board, id);
|
||||
list.name = name.trim();
|
||||
list.status = status;
|
||||
});
|
||||
}
|
||||
async collapse(id: string) {
|
||||
await this.update((board) => {
|
||||
const list = this.requireList(board, id);
|
||||
list.collapsed = !list.collapsed;
|
||||
});
|
||||
}
|
||||
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.");
|
||||
await this.update((board) => {
|
||||
const list = this.requireList(board, id);
|
||||
if (maximum === undefined) delete list.maxCards;
|
||||
else list.maxCards = maximum;
|
||||
});
|
||||
}
|
||||
async move(id: string, index: number) {
|
||||
await this.update((board) => {
|
||||
const list = this.requireList(board, id);
|
||||
board.lists = board.lists.filter((item) => item.id !== id);
|
||||
board.lists.splice(
|
||||
Math.max(0, Math.min(index, board.lists.length)),
|
||||
0,
|
||||
list,
|
||||
);
|
||||
});
|
||||
}
|
||||
async remove(id: string) {
|
||||
await this.update((board) => {
|
||||
this.requireList(board, id);
|
||||
board.lists = board.lists.filter((list) => list.id !== id);
|
||||
for (const status of statuses)
|
||||
if (board.defaults[status] === id) board.defaults[status] = null;
|
||||
});
|
||||
}
|
||||
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.");
|
||||
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.");
|
||||
if (
|
||||
board.lists.some(
|
||||
(list) =>
|
||||
list.id !== except &&
|
||||
list.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
|
||||
)
|
||||
)
|
||||
throw new Error("A list with this name already exists.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { readTask, newTask, split } from "./notes.ts";
|
||||
import type { Task, TaskFields, Workspace } from "../model/model.ts";
|
||||
import { backupFile, type OriginalFile } from "./catalog.ts";
|
||||
import { legacyPosition } from "./order.ts";
|
||||
import { mapConcurrent, readSources } from "./scan.ts";
|
||||
import {
|
||||
cardsFolder,
|
||||
cardsMarker,
|
||||
isHiddenCard,
|
||||
readOptional,
|
||||
saveDocument,
|
||||
} from "./persistence.ts";
|
||||
|
||||
export function cardPath(id: string) {
|
||||
const key = Array.from(new TextEncoder().encode(id), (byte) =>
|
||||
byte.toString(16).padStart(2, "0"),
|
||||
).join("");
|
||||
return `${cardsFolder}/${key}.md`;
|
||||
}
|
||||
export function cardOrigin(source: string): OriginalFile | undefined {
|
||||
const origin = split(source).doc.toJS({
|
||||
maxAliasCount: 50,
|
||||
}).runestone_pm_origin;
|
||||
if (origin === undefined) return;
|
||||
if (
|
||||
!origin ||
|
||||
typeof origin.path !== "string" ||
|
||||
typeof origin.source !== "string" ||
|
||||
typeof origin.backup !== "string" ||
|
||||
origin.path.startsWith(".") ||
|
||||
origin.path.includes("\\") ||
|
||||
origin.path
|
||||
.split("/")
|
||||
.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.",
|
||||
);
|
||||
return origin;
|
||||
}
|
||||
/** Read one hidden card file. It throws when the file is invalid or when its name does not match the card ID. */
|
||||
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.");
|
||||
return task;
|
||||
}
|
||||
export async function prepareCards(workspace: Workspace) {
|
||||
const marker = await readOptional(workspace, cardsMarker);
|
||||
if (marker !== null) return;
|
||||
try {
|
||||
await saveDocument(workspace, cardsMarker, "*\n", null);
|
||||
} catch (error) {
|
||||
if ((await readOptional(workspace, cardsMarker)) !== "*\n") throw error;
|
||||
}
|
||||
}
|
||||
export async function readCards(
|
||||
workspace: Workspace,
|
||||
previous: ReadonlyMap<string, Task> = new Map(),
|
||||
): Promise<{ tasks: Task[]; issues: string[] }> {
|
||||
const tasks: Task[] = [],
|
||||
issues: string[] = [];
|
||||
// Direct reads are necessary because the host hides .runestone from root listings.
|
||||
if (
|
||||
!workspace.readOptional ||
|
||||
(await workspace.readOptional(cardsMarker)) === null
|
||||
)
|
||||
return { tasks, issues };
|
||||
const entries = (await workspace.list(cardsFolder)).filter(
|
||||
(entry) => entry.kind !== "folder" && isHiddenCard(entry.rel_path),
|
||||
);
|
||||
const sources = await readSources(workspace, entries.map(entry => entry.rel_path));
|
||||
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.");
|
||||
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)}`,
|
||||
};
|
||||
}
|
||||
});
|
||||
for (const document of documents) {
|
||||
if (document.task) tasks.push(document.task);
|
||||
if (document.issue) issues.push(document.issue);
|
||||
}
|
||||
return { tasks, issues };
|
||||
}
|
||||
export async function createCard(
|
||||
workspace: Workspace,
|
||||
title: string,
|
||||
fields: TaskFields,
|
||||
body: string,
|
||||
id: string = crypto.randomUUID(),
|
||||
) {
|
||||
// The storage name is independent of the title, so punctuation and duplicate titles are safe.
|
||||
const note = newTask(id, { ...fields, title: title.trim() }, body, id);
|
||||
const path = cardPath(id);
|
||||
await prepareCards(workspace);
|
||||
await saveDocument(workspace, path, note.source, null);
|
||||
return { path, source: note.source };
|
||||
}
|
||||
export async function migrateCards(workspace: Workspace, tasks: Task[]) {
|
||||
for (const task of tasks) {
|
||||
if (isHiddenCard(task.path)) continue;
|
||||
if ((await workspace.read(task.path)) !== task.source)
|
||||
throw new Error(
|
||||
`The card changed: ${task.path}. Refresh before migration.`,
|
||||
);
|
||||
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}.`,
|
||||
);
|
||||
}
|
||||
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.`,
|
||||
);
|
||||
}
|
||||
for (const task of tasks) {
|
||||
if (isHiddenCard(task.path)) continue;
|
||||
const original = await backupFile(workspace, task.path, task.source);
|
||||
const path = cardPath(task.id);
|
||||
if ((await readOptional(workspace, path)) !== null) continue;
|
||||
const { doc, body, newline, match } = split(task.source);
|
||||
doc.set("runestone_pm_origin", original);
|
||||
if (task.order === undefined)
|
||||
doc.setIn(["runestone_pm", "order"], legacyPosition(task.path));
|
||||
for (const [id, placement] of Object.entries(task.placements ?? {}))
|
||||
if (placement.order === undefined)
|
||||
doc.setIn(
|
||||
["runestone_pm", "placements", id, "order"],
|
||||
legacyPosition(task.path),
|
||||
);
|
||||
const source = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||
const copied = readTask(path, source)!;
|
||||
if (
|
||||
copied.id !== task.id ||
|
||||
copied.title !== task.title ||
|
||||
copied.body !== task.body
|
||||
)
|
||||
throw new Error(
|
||||
`The card copy differs from ${task.path}. Keep the original.`,
|
||||
);
|
||||
if ((await workspace.read(task.path)) !== task.source)
|
||||
throw new Error(`The card changed: ${task.path}. Retry migration.`);
|
||||
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.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { Document } from "yaml";
|
||||
import {
|
||||
defaultBoard,
|
||||
parseBoard,
|
||||
type Board,
|
||||
type BoardDocument,
|
||||
} from "./board.ts";
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
import { readOptional, saveDocument } from "./persistence.ts";
|
||||
|
||||
export const catalogPath = ".runestone/pm/workspace.json";
|
||||
export const boardKey = (id: string) => `pm-board:${id}`;
|
||||
export const isManagedBoard = (path: string) => path.startsWith("pm-board:");
|
||||
export interface OriginalFile {
|
||||
path: string;
|
||||
source: string;
|
||||
backup: string;
|
||||
}
|
||||
export interface ManagedBoard {
|
||||
name: string;
|
||||
value: Board;
|
||||
archived?: boolean;
|
||||
original?: OriginalFile;
|
||||
}
|
||||
export interface Catalog {
|
||||
schema: 1;
|
||||
boards: ManagedBoard[];
|
||||
deletedBoardIds?: string[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
export function boardMarkdown(value: Board): string {
|
||||
return `---\n${new Document({ runestone_pm: value }).toString({ lineWidth: 0 })}---\n`;
|
||||
}
|
||||
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.");
|
||||
}
|
||||
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.",
|
||||
);
|
||||
const ids = new Set<string>();
|
||||
if (
|
||||
data.deletedBoardIds !== undefined &&
|
||||
(!Array.isArray(data.deletedBoardIds) ||
|
||||
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.");
|
||||
for (const board of data.boards) {
|
||||
if (!board || typeof board.name !== "string")
|
||||
throw new Error("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.");
|
||||
ids.add(board.value.id);
|
||||
if (data.deletedBoardIds?.includes(board.value.id))
|
||||
throw new Error("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.");
|
||||
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.");
|
||||
}
|
||||
return data;
|
||||
}
|
||||
export async function readCatalog(workspace: Workspace) {
|
||||
const source = await readOptional(workspace, catalogPath);
|
||||
return { source, value: parseCatalog(source) };
|
||||
}
|
||||
export async function writeCatalog(
|
||||
workspace: Workspace,
|
||||
value: Catalog,
|
||||
expected: string | null,
|
||||
) {
|
||||
if (!workspace.readOptional)
|
||||
throw new Error("Update RuneStone to use hidden Project Management storage.");
|
||||
const source = JSON.stringify(value, null, 2) + "\n";
|
||||
parseCatalog(source);
|
||||
await saveDocument(workspace, catalogPath, source, expected);
|
||||
return source;
|
||||
}
|
||||
export function managedDocuments(
|
||||
value: Catalog,
|
||||
source: string,
|
||||
): BoardDocument[] {
|
||||
return value.boards.map((board) => ({
|
||||
id: board.value.id,
|
||||
path: boardKey(board.value.id),
|
||||
name: board.name,
|
||||
value: board.value,
|
||||
archived: board.archived,
|
||||
source,
|
||||
}));
|
||||
}
|
||||
export async function createBoard(workspace: Workspace, name: string) {
|
||||
validateName(name);
|
||||
const snapshot = await readCatalog(workspace);
|
||||
if (
|
||||
snapshot.value.boards.some(
|
||||
(board) =>
|
||||
board.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
|
||||
)
|
||||
)
|
||||
throw new Error("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);
|
||||
return { id: value.id, path: boardKey(value.id) };
|
||||
}
|
||||
export async function backupFile(
|
||||
workspace: Workspace,
|
||||
path: string,
|
||||
source: string,
|
||||
): Promise<OriginalFile> {
|
||||
if (
|
||||
path.startsWith(".") ||
|
||||
path.includes("\\") ||
|
||||
path.split("/").some((part) => !part || part === ".." || part === ".")
|
||||
)
|
||||
throw new Error("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.`,
|
||||
);
|
||||
if ((await workspace.read(backup)) !== source)
|
||||
throw new Error(`Backup check failed for ${path}.`);
|
||||
return { path, source, backup };
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
import { readOptional, saveDocument } from "./persistence.ts";
|
||||
|
||||
export const deletedCardsPath = ".runestone/pm/deleted-cards.json";
|
||||
|
||||
export async function readDeletedCards(workspace: Workspace) {
|
||||
const source = await readOptional(workspace, deletedCardsPath);
|
||||
if (source === null) return { source, ids: [] as string[] };
|
||||
const value = JSON.parse(source);
|
||||
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.");
|
||||
return { source, ids: value.ids as string[] };
|
||||
}
|
||||
|
||||
/** Keep a deletion record so saved legacy notes cannot restore deleted cards. */
|
||||
export async function recordCardDeletion(workspace: Workspace, id: string) {
|
||||
const snapshot = await readDeletedCards(workspace);
|
||||
if (snapshot.ids.includes(id)) return;
|
||||
await saveDocument(workspace, deletedCardsPath,
|
||||
JSON.stringify({ schema: 1, ids: [...snapshot.ids, id] }, null, 2) + "\n", snapshot.source);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
import { readOptional, saveDocument } from "./persistence.ts";
|
||||
|
||||
/** A draft is separate from the saved card and uses compare-and-write protection. */
|
||||
export class DescriptionDraft {
|
||||
private source: string | null = null;
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
readonly path: string;
|
||||
private workspace: Workspace;
|
||||
constructor(workspace: Workspace, id: string) {
|
||||
this.workspace = workspace;
|
||||
const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join("");
|
||||
this.path = `.runestone/pm/drafts/${key}.json`;
|
||||
}
|
||||
async load(): Promise<string | null> {
|
||||
this.source = await readOptional(this.workspace, this.path);
|
||||
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.");
|
||||
return value.body;
|
||||
}
|
||||
save(body: string | null): Promise<void> {
|
||||
const write = this.queue.then(async () => {
|
||||
const source = JSON.stringify({ schema: 1, body }) + "\n";
|
||||
if (source === this.source || (body === null && this.source === null)) return;
|
||||
await saveDocument(this.workspace, this.path, source, this.source);
|
||||
this.source = source;
|
||||
});
|
||||
this.queue = write.catch(() => {});
|
||||
return write;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { Workspace, TaskFields } from "../model/model.ts";
|
||||
import { saveDocument, storageRoot } from "./persistence.ts";
|
||||
|
||||
export const maxImageBytes = 50 * 1024 * 1024;
|
||||
export const imageTypes = [
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
];
|
||||
const idPattern =
|
||||
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
export const imageFolder = `${storageRoot}/images`;
|
||||
export function imagePath(id: string) {
|
||||
if (!new RegExp(`^${idPattern}$`).test(id))
|
||||
throw new Error("The image ID is invalid.");
|
||||
return `${imageFolder}/${id}.json`;
|
||||
}
|
||||
export function imageReferences(body: string) {
|
||||
return [
|
||||
...body.matchAll(
|
||||
new RegExp(`!\\[([^\\]\\r\\n]*)\\]\\(pm-image:(${idPattern})\\)`, "g"),
|
||||
),
|
||||
].map((match) => ({
|
||||
id: match[2],
|
||||
name: match[1] || "Pasted image",
|
||||
markdown: match[0],
|
||||
index: match.index,
|
||||
}));
|
||||
}
|
||||
export function imageMarkdown(name: string, id: string) {
|
||||
imagePath(id);
|
||||
return `![${name.replace(/[\[\]\r\n\\]/g, " ").trim() || "Pasted image"}](pm-image:${id})`;
|
||||
}
|
||||
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.");
|
||||
const value = JSON.parse(source);
|
||||
if (value?.schema !== 1 || typeof value.data !== "string")
|
||||
throw new Error("The saved image is invalid.");
|
||||
const match =
|
||||
/^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(
|
||||
value.data,
|
||||
);
|
||||
if (
|
||||
!match ||
|
||||
match[2].length % 4 !== 0 ||
|
||||
atob(match[2]).length > maxImageBytes
|
||||
)
|
||||
throw new Error("The saved image is invalid or exceeds 50 MiB.");
|
||||
return value.data;
|
||||
}
|
||||
export async function saveImages(
|
||||
workspace: Workspace,
|
||||
body: string,
|
||||
pending: Map<string, string>,
|
||||
attachments: TaskFields["attachments"] = [],
|
||||
) {
|
||||
for (const id of new Set([...imageReferences(body), ...attachments].map((image) => image.id))) {
|
||||
const data = pending.get(id);
|
||||
if (!data) continue;
|
||||
const source = JSON.stringify({ schema: 1, data }) + "\n";
|
||||
parseImage(source);
|
||||
const path = imagePath(id);
|
||||
// Retrying a failed card save reuses its complete image files.
|
||||
const previous = await workspace.readOptional?.(path);
|
||||
if (previous !== source) await saveDocument(workspace, path, source, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { cardColors, type Workspace } from "../model/model.ts";
|
||||
import { readOptional, saveDocument } from "./persistence.ts";
|
||||
|
||||
export const labelsPath = ".runestone/pm/labels.json";
|
||||
export const legacyLabelsPath = "runestone-pm-labels.json";
|
||||
export interface SavedLabel {
|
||||
id: string;
|
||||
name: string;
|
||||
color: keyof typeof cardColors;
|
||||
archived?: boolean;
|
||||
}
|
||||
export interface LabelSnapshot {
|
||||
source: string | null;
|
||||
labels: SavedLabel[];
|
||||
legacy?: boolean;
|
||||
}
|
||||
export function defaultLabels(): SavedLabel[] {
|
||||
return [
|
||||
{ id: "bug", name: "Bug", color: "red" },
|
||||
{ id: "feature", name: "Feature", color: "blue" },
|
||||
{ id: "improvement", name: "Improvement", color: "green" },
|
||||
];
|
||||
}
|
||||
export function validateLabels(
|
||||
labels: unknown,
|
||||
): asserts labels is SavedLabel[] {
|
||||
if (!Array.isArray(labels)) throw new Error("Saved labels must be a list.");
|
||||
const ids = new Set<string>(),
|
||||
names = new Set<string>();
|
||||
for (const label of labels) {
|
||||
if (
|
||||
!label ||
|
||||
typeof label !== "object" ||
|
||||
Array.isArray(label) ||
|
||||
typeof label.id !== "string" ||
|
||||
!/^[a-zA-Z0-9_-]{1,100}$/.test(label.id) ||
|
||||
ids.has(label.id)
|
||||
)
|
||||
throw new Error("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.");
|
||||
const name = label.name.trim().toLocaleLowerCase();
|
||||
if (names.has(name))
|
||||
throw new Error(
|
||||
"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.");
|
||||
if (label.archived !== undefined && typeof label.archived !== "boolean")
|
||||
throw new Error("Label archive state must be true or false.");
|
||||
ids.add(label.id);
|
||||
names.add(name);
|
||||
}
|
||||
}
|
||||
export function parseLabels(source: string | null): LabelSnapshot {
|
||||
if (source === null) return { source, labels: defaultLabels() };
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(source);
|
||||
} catch {
|
||||
throw new Error("Fix the saved labels file before editing labels.");
|
||||
}
|
||||
if (
|
||||
!data ||
|
||||
typeof data !== "object" ||
|
||||
Array.isArray(data) ||
|
||||
data.schema !== 1
|
||||
)
|
||||
throw new Error("The saved labels file has an unsupported schema.");
|
||||
validateLabels(data.labels);
|
||||
return { source, labels: data.labels };
|
||||
}
|
||||
|
||||
export class LabelStore {
|
||||
value: SavedLabel[] = [];
|
||||
source: string | null | undefined;
|
||||
error = "";
|
||||
legacy = false;
|
||||
readonly workspace: Workspace;
|
||||
constructor(workspace: Workspace) {
|
||||
this.workspace = workspace;
|
||||
}
|
||||
async read(): Promise<LabelSnapshot> {
|
||||
const source = await readOptional(this.workspace, labelsPath);
|
||||
if (source !== null) return parseLabels(source);
|
||||
const legacy = await readOptional(this.workspace, legacyLabelsPath);
|
||||
return { ...parseLabels(legacy), legacy: legacy !== null };
|
||||
}
|
||||
load(snapshot?: LabelSnapshot, error = "") {
|
||||
this.value = snapshot?.labels ?? [];
|
||||
this.source = snapshot?.source;
|
||||
this.error = error;
|
||||
this.legacy = snapshot?.legacy ?? false;
|
||||
}
|
||||
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.",
|
||||
);
|
||||
if (!this.workspace.readOptional)
|
||||
throw new Error("Update RuneStone to use hidden Project Management storage.");
|
||||
if (expected === undefined || this.error)
|
||||
throw new Error(
|
||||
"Saved labels are unavailable. Refresh before editing labels.",
|
||||
);
|
||||
validateLabels(labels);
|
||||
}
|
||||
async save(labels: SavedLabel[], expected: string | null | undefined, allowDelete = false) {
|
||||
this.checkSave(labels, expected);
|
||||
const previous = parseLabels(expected!);
|
||||
if (
|
||||
!allowDelete && previous.labels.some(
|
||||
(label) => !labels.some((next) => next.id === label.id),
|
||||
)
|
||||
)
|
||||
throw new Error("Archive unused labels to preserve existing cards.");
|
||||
const data = expected === null ? { schema: 1 } : JSON.parse(expected);
|
||||
const source =
|
||||
JSON.stringify(
|
||||
{
|
||||
...data,
|
||||
labels: labels.map((label) => ({
|
||||
...label,
|
||||
name: label.name.trim(),
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n";
|
||||
await saveDocument(this.workspace, labelsPath, source, expected);
|
||||
this.load(parseLabels(source));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// The legacy format: boards and task notes in visible Markdown files, and the root label file.
|
||||
// The native feature reads only `.runestone/pm/`. When it opens a workspace that still has data in the legacy format,
|
||||
// it offers the migration (`migrateStorage` in `migration.ts`), and it migrates only after the user chooses it.
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
import { readCatalog } from "./catalog.ts";
|
||||
import { cardPath } from "./cards.ts";
|
||||
import { readDeletedCards } from "./deleted-cards.ts";
|
||||
import { labelsPath, legacyLabelsPath } from "./labels.ts";
|
||||
import { split } from "./notes.ts";
|
||||
import { cardsFolder, readOptional } from "./persistence.ts";
|
||||
import { markdownPaths, readSources } from "./scan.ts";
|
||||
|
||||
/** The legacy data that the migration has not copied to `.runestone/pm/` yet. */
|
||||
export interface LegacyContent {
|
||||
/** The paths of board notes. */
|
||||
boards: string[];
|
||||
/** The paths of task notes. */
|
||||
cards: string[];
|
||||
/** The paths of notes with invalid Project Management properties. The migration reports them. */
|
||||
invalid: string[];
|
||||
/** True when `runestone-pm-labels.json` exists and `.runestone/pm/labels.json` does not. */
|
||||
labels: boolean;
|
||||
}
|
||||
|
||||
/** The YAML properties at the start of a note, up to a line that starts with `runestone_pm:`. The closing line stops it. */
|
||||
const properties = /^---[ \t]*\r?\n(?:(?!(?:---|\.\.\.)[ \t]*\r?\n)[^\n]*\n)*?runestone_pm[ \t]*:/;
|
||||
|
||||
/** True when the YAML properties of a note can contain Project Management data. It needs no YAML parse. */
|
||||
export function mentionsProjectData(source: string): boolean {
|
||||
return properties.test(source.charCodeAt(0) === 0xfeff ? source.slice(1) : source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the legacy data of a workspace. Only notes that name `runestone_pm` in their properties get a YAML parse.
|
||||
* A board or a card that the migration copied, or that the user deleted, does not count.
|
||||
*/
|
||||
export async function findLegacy(workspace: Workspace, check: () => void = () => {}): Promise<LegacyContent> {
|
||||
const result: LegacyContent = { boards: [], cards: [], invalid: [], labels: false };
|
||||
const paths = await markdownPaths(workspace, check);
|
||||
const found: { path: string; kind: "board" | "task"; id: string }[] = [];
|
||||
// One batch at a time, so the texts of all notes are never in memory together.
|
||||
for (let offset = 0; offset < paths.length; offset += 64) {
|
||||
const sources = await readSources(workspace, paths.slice(offset, offset + 64));
|
||||
check();
|
||||
for (const [path, file] of sources) {
|
||||
if (file.source === undefined || !mentionsProjectData(file.source)) continue;
|
||||
try {
|
||||
const value = split(file.source).doc.toJS({ maxAliasCount: 50 }).runestone_pm;
|
||||
if (value === undefined) continue;
|
||||
if (!value || typeof value.id !== "string" || !value.id.trim() || (value.kind !== "board" && value.kind !== "task")) throw new Error("Invalid data.");
|
||||
found.push({ path, kind: value.kind, id: value.id });
|
||||
} catch { result.invalid.push(path); }
|
||||
}
|
||||
}
|
||||
let saved = new Set<string>(), deletedBoards = new Set<string>(), deletedCards = new Set<string>();
|
||||
try {
|
||||
const catalog = await readCatalog(workspace);
|
||||
saved = new Set(catalog.value.boards.map(board => board.value.id));
|
||||
deletedBoards = new Set(catalog.value.deletedBoardIds ?? []);
|
||||
} catch { /* The migration reports a damaged catalog. */ }
|
||||
try { deletedCards = new Set((await readDeletedCards(workspace)).ids); } catch { /* The migration reports it. */ }
|
||||
let cards = new Set<string>();
|
||||
if (found.some(item => item.kind === "task")) {
|
||||
try { cards = new Set((await workspace.list(cardsFolder)).map(entry => entry.rel_path)); } catch { /* No card folder yet. */ }
|
||||
}
|
||||
for (const item of found) {
|
||||
if (item.kind === "board" && !saved.has(item.id) && !deletedBoards.has(item.id)) result.boards.push(item.path);
|
||||
if (item.kind === "task" && !cards.has(cardPath(item.id)) && !deletedCards.has(item.id)) result.cards.push(item.path);
|
||||
}
|
||||
result.labels = (await readOptional(workspace, legacyLabelsPath)) !== null && (await readOptional(workspace, labelsPath)) === null;
|
||||
for (const list of [result.boards, result.cards, result.invalid]) list.sort();
|
||||
return result;
|
||||
}
|
||||
|
||||
/** True when the workspace has legacy data to migrate. */
|
||||
export function hasLegacy(content: LegacyContent): boolean {
|
||||
return content.boards.length > 0 || content.cards.length > 0 || content.invalid.length > 0 || content.labels;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { Workspace, Task } from "../model/model.ts";
|
||||
import { migrateCards, readCards, cardOrigin } from "./cards.ts";
|
||||
import type { BoardDocument } from "./board.ts";
|
||||
import {
|
||||
backupFile,
|
||||
readCatalog,
|
||||
writeCatalog,
|
||||
isManagedBoard,
|
||||
type OriginalFile,
|
||||
} from "./catalog.ts";
|
||||
import { labelsPath, legacyLabelsPath, parseLabels } from "./labels.ts";
|
||||
import {
|
||||
readOptional,
|
||||
saveDocument,
|
||||
ensurePrivateStorage,
|
||||
} from "./persistence.ts";
|
||||
|
||||
/** Retain originals until the user checks the boards and removes the listed files. */
|
||||
export async function migrateStorage(
|
||||
workspace: Workspace,
|
||||
boards: BoardDocument[],
|
||||
cards: Task[] = [],
|
||||
) {
|
||||
if (!workspace.readOptional || !workspace.create)
|
||||
throw new Error("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);
|
||||
const savedLabels = await readOptional(workspace, labelsPath);
|
||||
if (legacyLabels !== null) parseLabels(legacyLabels);
|
||||
if (savedLabels !== null) parseLabels(savedLabels);
|
||||
// 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.");
|
||||
if ((await workspace.read(board.path)) !== board.source)
|
||||
throw new Error(
|
||||
`The board changed: ${board.path}. Refresh before migration.`,
|
||||
);
|
||||
const existing = snapshot.value.boards.find(
|
||||
(item) => item.value.id === board.id,
|
||||
);
|
||||
if (
|
||||
existing &&
|
||||
(existing.original?.path !== board.path ||
|
||||
existing.original.source !== board.source)
|
||||
)
|
||||
throw new Error(
|
||||
`A different board already uses the ID from ${board.path}.`,
|
||||
);
|
||||
}
|
||||
if (legacyLabels !== null && savedLabels !== null) {
|
||||
const original = JSON.parse(savedLabels).original;
|
||||
if (
|
||||
original?.path !== legacyLabelsPath ||
|
||||
original?.source !== legacyLabels
|
||||
)
|
||||
throw new Error(
|
||||
"Hidden labels and legacy labels both exist. Resolve their differences before migration.",
|
||||
);
|
||||
}
|
||||
await ensurePrivateStorage(workspace);
|
||||
let changed = false;
|
||||
for (const board of legacy) {
|
||||
if (snapshot.value.boards.some((item) => item.value.id === board.id))
|
||||
continue;
|
||||
const original = await backupFile(workspace, board.path, board.source);
|
||||
snapshot.value.boards.push({
|
||||
name: board.name,
|
||||
value: board.value,
|
||||
original,
|
||||
});
|
||||
changed = true;
|
||||
}
|
||||
const labelBackup =
|
||||
legacyLabels !== null && savedLabels === null
|
||||
? await backupFile(workspace, legacyLabelsPath, legacyLabels)
|
||||
: undefined;
|
||||
for (const board of legacy)
|
||||
if ((await workspace.read(board.path)) !== board.source)
|
||||
throw new Error(
|
||||
`The board changed: ${board.path}. Refresh before migration.`,
|
||||
);
|
||||
if (legacyLabels !== (await readOptional(workspace, legacyLabelsPath)))
|
||||
throw new Error("Legacy labels changed. Refresh before migration.");
|
||||
if (changed) await writeCatalog(workspace, snapshot.value, snapshot.source);
|
||||
if (labelBackup) {
|
||||
const source =
|
||||
JSON.stringify(
|
||||
{ ...JSON.parse(legacyLabels!), original: labelBackup },
|
||||
null,
|
||||
2,
|
||||
) + "\n";
|
||||
await saveDocument(workspace, labelsPath, source, null);
|
||||
if ((await workspace.read(labelsPath)) !== source)
|
||||
throw new Error("The saved label check failed. Retry migration.");
|
||||
}
|
||||
const saved = await readCatalog(workspace);
|
||||
for (const board of legacy) {
|
||||
const entry = saved.value.boards.find((item) => item.value.id === board.id);
|
||||
const expected = snapshot.value.boards.find(
|
||||
(item) => item.value.id === board.id,
|
||||
);
|
||||
if (
|
||||
entry?.original?.source !== board.source ||
|
||||
JSON.stringify(entry) !== JSON.stringify(expected)
|
||||
)
|
||||
throw new Error("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.`,
|
||||
);
|
||||
const current = await readOptional(workspace, file.path);
|
||||
if (current !== null && current !== file.source)
|
||||
throw new Error(
|
||||
`The original changed: ${file.path}. Keep both versions.`,
|
||||
);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
export async function migrationFiles(
|
||||
workspace: Workspace,
|
||||
): Promise<OriginalFile[]> {
|
||||
const snapshot = await readCatalog(workspace);
|
||||
const files = snapshot.value.boards.flatMap((board) =>
|
||||
board.original ? [board.original] : [],
|
||||
);
|
||||
const labels = await readOptional(workspace, labelsPath);
|
||||
if (labels !== null) {
|
||||
parseLabels(labels);
|
||||
const original = JSON.parse(labels).original;
|
||||
if (
|
||||
original &&
|
||||
typeof original.path === "string" &&
|
||||
typeof original.source === "string" &&
|
||||
typeof original.backup === "string"
|
||||
)
|
||||
files.push(original);
|
||||
}
|
||||
const cards = await readCards(workspace);
|
||||
if (cards.issues.length) throw new Error(cards.issues.join(" "));
|
||||
for (const task of cards.tasks) {
|
||||
const original = cardOrigin(task.source);
|
||||
if (original) files.push(original);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { Document, isMap, parseDocument } from "yaml";
|
||||
import { isHiddenCard } from "./persistence.ts";
|
||||
import {
|
||||
validateFields,
|
||||
type Task,
|
||||
type TaskFields,
|
||||
type Status,
|
||||
type Session,
|
||||
} from "../model/model.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.",
|
||||
);
|
||||
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.",
|
||||
);
|
||||
if (!isMap(doc.contents))
|
||||
throw new Error("Note properties must be a YAML mapping.");
|
||||
return {
|
||||
match,
|
||||
doc,
|
||||
body: match ? source.slice(match[0].length) : source,
|
||||
newline: source.includes("\r\n") ? "\r\n" : "\n",
|
||||
};
|
||||
}
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
export function readTask(path: string, source: string): Task | null {
|
||||
const { doc, body } = split(source);
|
||||
const metadata = doc.toJS({ maxAliasCount: 50 });
|
||||
const pm: unknown = metadata.runestone_pm;
|
||||
if (pm === undefined) return null;
|
||||
if (record(pm) && pm.kind === "board") return null;
|
||||
if (
|
||||
!record(pm) ||
|
||||
pm.schema !== 1 ||
|
||||
pm.kind !== "task" ||
|
||||
typeof pm.id !== "string" ||
|
||||
!pm.id.trim()
|
||||
) {
|
||||
throw new Error("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.");
|
||||
if (
|
||||
pm.due !== undefined &&
|
||||
(!record(pm.due) || typeof pm.due.date !== "string")
|
||||
)
|
||||
throw new Error("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.");
|
||||
if (
|
||||
pm.sessions !== undefined &&
|
||||
(!Array.isArray(pm.sessions) ||
|
||||
pm.sessions.some(
|
||||
(value) =>
|
||||
!record(value) ||
|
||||
typeof value.id !== "string" ||
|
||||
typeof value.start !== "string" ||
|
||||
typeof value.end !== "string" ||
|
||||
typeof value.timeZone !== "string",
|
||||
))
|
||||
) {
|
||||
throw new Error("Sessions need an ID, start, end, and time zone.");
|
||||
}
|
||||
const task: Task = {
|
||||
id: pm.id,
|
||||
createdAt: pm.createdAt as string | undefined,
|
||||
path,
|
||||
title:
|
||||
pm.title === undefined
|
||||
? (isHiddenCard(path) &&
|
||||
record(metadata.runestone_pm_origin) &&
|
||||
typeof metadata.runestone_pm_origin.path === "string"
|
||||
? metadata.runestone_pm_origin.path
|
||||
: path
|
||||
)
|
||||
.split("/")
|
||||
.at(-1)!
|
||||
.replace(/\.(md|markdown|mdown)$/i, "")
|
||||
: (pm.title as string),
|
||||
order: pm.order as string | undefined,
|
||||
body,
|
||||
source,
|
||||
status: pm.status as Status,
|
||||
listId: pm.listId as string | null | undefined,
|
||||
placements: pm.placements as Task["placements"],
|
||||
tags: (pm.tags ?? []) as string[],
|
||||
labels: pm.labels as Task["labels"],
|
||||
priority: pm.priority as Task["priority"],
|
||||
coverImage: pm.coverImage as Task["coverImage"],
|
||||
attachments: pm.attachments as Task["attachments"],
|
||||
subtasks: pm.subtasks as Task["subtasks"],
|
||||
links: pm.links as Task["links"],
|
||||
color: pm.color as Task["color"],
|
||||
assignees: pm.assignees as Task["assignees"],
|
||||
customFields: pm.customFields as Task["customFields"],
|
||||
due: pm.due as Task["due"],
|
||||
plan: pm.plan as Task["plan"],
|
||||
sessions: (pm.sessions ?? []) as Session[],
|
||||
archived: pm.archived === true,
|
||||
};
|
||||
validateFields({ ...task, title: pm.title as string | undefined });
|
||||
return task;
|
||||
}
|
||||
|
||||
// Update individual YAML nodes so unknown keys and comments remain in the document.
|
||||
export function editTask(
|
||||
task: Task,
|
||||
patch: Partial<TaskFields> & { body?: string },
|
||||
): 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.");
|
||||
validateFields(fields);
|
||||
const { doc, match, newline } = split(task.source);
|
||||
for (const key of [
|
||||
"title",
|
||||
"order",
|
||||
"listId",
|
||||
"placements",
|
||||
"status",
|
||||
"tags",
|
||||
"labels",
|
||||
"priority",
|
||||
"coverImage",
|
||||
"attachments",
|
||||
"subtasks",
|
||||
"links",
|
||||
"color",
|
||||
"assignees",
|
||||
"customFields",
|
||||
"due",
|
||||
"plan",
|
||||
"sessions",
|
||||
"archived",
|
||||
] as const) {
|
||||
if (!Object.hasOwn(patch, key)) continue;
|
||||
const value = patch[key];
|
||||
if (value === undefined) {
|
||||
doc.deleteIn(["runestone_pm", key]);
|
||||
continue;
|
||||
}
|
||||
if (key === "due" || key === "plan") {
|
||||
for (const [name, child] of Object.entries(value as object))
|
||||
doc.setIn(["runestone_pm", key, name], child);
|
||||
} else doc.setIn(["runestone_pm", key], value);
|
||||
}
|
||||
const bom = match?.[1] ?? "";
|
||||
const yaml = doc.toString({ lineWidth: 0 }).replaceAll("\n", newline);
|
||||
const closing = match?.[4].replace(/^\r?\n/, "") ?? `---${newline}`;
|
||||
return `${bom}---${newline}${yaml}${closing}${patch.body ?? task.body}`;
|
||||
}
|
||||
export function newTask(
|
||||
title: string,
|
||||
fields: TaskFields,
|
||||
body = "",
|
||||
id: string = crypto.randomUUID(),
|
||||
): { path: string; source: string } {
|
||||
title = title.trim();
|
||||
if (
|
||||
!title ||
|
||||
title.length > 100 ||
|
||||
/[<>:"/\\|?*\x00-\x1f]/.test(title) ||
|
||||
/[. ]$/.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.");
|
||||
validateFields(fields);
|
||||
const doc = new Document({
|
||||
runestone_pm: { schema: 1, id, kind: "task", ...fields, createdAt: fields.createdAt ?? new Date().toISOString() },
|
||||
});
|
||||
return {
|
||||
path: `Projects/Inbox/${title}.md`,
|
||||
source: `---\n${doc.toString({ lineWidth: 0 })}---\n${body}`,
|
||||
};
|
||||
}
|
||||
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.",
|
||||
);
|
||||
doc.set("runestone_pm", {
|
||||
schema: 1,
|
||||
id: crypto.randomUUID(),
|
||||
kind: "task",
|
||||
createdAt: new Date().toISOString(),
|
||||
status: "todo",
|
||||
tags: [],
|
||||
sessions: [],
|
||||
archived: false,
|
||||
});
|
||||
return `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { Task } from "../model/model.ts";
|
||||
|
||||
const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
const encode = (text: string) =>
|
||||
text
|
||||
.split("")
|
||||
.map((char) => char.charCodeAt(0).toString(16).padStart(4, "0"))
|
||||
.join("");
|
||||
|
||||
export function cardOrder(task: Task, boardId?: string): string {
|
||||
const saved = boardId ? task.placements?.[boardId]?.order : task.order;
|
||||
// Old notes keep filename order. Title edits do not change their positions.
|
||||
const position = saved ?? legacyPosition(task.path);
|
||||
// The ID breaks ties when separate windows choose the same position.
|
||||
return position + "i" + encode(task.id) + "8";
|
||||
}
|
||||
|
||||
export function legacyPosition(path: string): string {
|
||||
return encode(path.split("/").at(-1)!.toLowerCase()) + "0000" + encode(path);
|
||||
}
|
||||
|
||||
export function compareCards(a: Task, b: Task, boardId?: string): number {
|
||||
const left = cardOrder(a, boardId),
|
||||
right = cardOrder(b, boardId);
|
||||
return left < right ? -1 : left > right ? 1 : 0;
|
||||
}
|
||||
|
||||
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.");
|
||||
let result = "";
|
||||
for (let index = 0; ; index++) {
|
||||
const low =
|
||||
index < (lower?.length ?? 0) ? digits.indexOf(lower![index]) : 0;
|
||||
const high =
|
||||
upper === undefined ? digits.length : digits.indexOf(upper[index]);
|
||||
if (high - low > 1) return result + digits[Math.floor((low + high) / 2)];
|
||||
result += digits[low];
|
||||
if (low < high) upper = undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
|
||||
export const storageRoot = ".runestone/pm";
|
||||
export const privateRulesPath = `${storageRoot}/.gitignore`;
|
||||
export const cardsFolder = `${storageRoot}/cards`;
|
||||
export const cardsMarker = `${cardsFolder}/.gitignore`;
|
||||
export const isHiddenCard = (path: string) =>
|
||||
path.startsWith(cardsFolder + "/") && /\.md$/i.test(path);
|
||||
|
||||
/** 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.");
|
||||
const expected = await workspace.readOptional(privateRulesPath);
|
||||
const rules = expected
|
||||
?.split(/\r?\n/)
|
||||
.filter((line) => line && !line.startsWith("#"));
|
||||
if (rules?.at(-1) === "*") return;
|
||||
const source =
|
||||
(expected ? expected + (expected.endsWith("\n") ? "" : "\n") : "") +
|
||||
"# RuneStone Project Management local data\n*\n";
|
||||
if (expected === null) {
|
||||
try {
|
||||
await workspace.create(privateRulesPath, source);
|
||||
} catch (error) {
|
||||
if ((await workspace.readOptional(privateRulesPath)) !== source)
|
||||
throw error;
|
||||
}
|
||||
} 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.",
|
||||
);
|
||||
}
|
||||
|
||||
/** Older hosts cannot discover hidden files through the root listing. */
|
||||
export async function readOptional(
|
||||
workspace: Workspace,
|
||||
path: string,
|
||||
): Promise<string | null> {
|
||||
if (workspace.readOptional) return workspace.readOptional(path);
|
||||
const entries = await workspace.list();
|
||||
if (entries.some((entry) => entry.rel_path === path))
|
||||
return workspace.read(path);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function saveDocument(
|
||||
workspace: Workspace,
|
||||
path: string,
|
||||
source: string,
|
||||
expected: string | null,
|
||||
) {
|
||||
if (path.startsWith(storageRoot + "/") && path !== privateRulesPath)
|
||||
await ensurePrivateStorage(workspace);
|
||||
if (expected === null) {
|
||||
if (!workspace.create)
|
||||
throw new Error("Update RuneStone to create Project Management storage.");
|
||||
await workspace.create(path, source);
|
||||
} else await workspace.write(path, source, expected);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
|
||||
// Limit concurrent bridge requests, including large workspaces with many notes.
|
||||
export const scanConcurrency = 8;
|
||||
|
||||
/** Read bounded batches while retaining each file's failure and conflict evidence. */
|
||||
export async function readSources(workspace: Workspace, paths: string[]) {
|
||||
const results = new Map<string, { source?: string; error?: string }>();
|
||||
if (workspace.readMany) {
|
||||
for (let offset = 0; offset < paths.length; offset += 64) {
|
||||
const batch = paths.slice(offset, offset + 64);
|
||||
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." });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
await mapConcurrent(paths, async path => {
|
||||
try { results.set(path, { source: await workspace.read(path) }); }
|
||||
catch (error) { results.set(path, { error: error instanceof Error ? error.message : String(error) }); }
|
||||
});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function mapConcurrent<T, R>(
|
||||
items: readonly T[],
|
||||
visit: (item: T) => Promise<R>,
|
||||
): Promise<R[]> {
|
||||
const results = new Array<R>(items.length);
|
||||
let next = 0;
|
||||
const workers = Array.from(
|
||||
{ length: Math.min(scanConcurrency, items.length) },
|
||||
async () => {
|
||||
while (next < items.length) {
|
||||
const index = next++;
|
||||
results[index] = await visit(items[index]);
|
||||
}
|
||||
},
|
||||
);
|
||||
// Drain every worker before returning or reporting a failed directory read.
|
||||
const settled = await Promise.allSettled(workers);
|
||||
const failed = settled.find((result) => result.status === "rejected");
|
||||
if (failed?.status === "rejected") throw failed.reason;
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function markdownPaths(
|
||||
workspace: Workspace,
|
||||
check: () => void,
|
||||
): Promise<string[]> {
|
||||
check();
|
||||
if (workspace.listMarkdown) {
|
||||
const paths = await workspace.listMarkdown();
|
||||
check();
|
||||
return paths;
|
||||
}
|
||||
const files: string[] = [];
|
||||
let folders = [""];
|
||||
while (folders.length) {
|
||||
const listings = await mapConcurrent(folders, async (path) => {
|
||||
check();
|
||||
return workspace.list(path);
|
||||
});
|
||||
folders = [];
|
||||
for (const entries of listings) {
|
||||
check();
|
||||
for (const entry of entries) {
|
||||
if (
|
||||
entry.name.startsWith(".") ||
|
||||
entry.rel_path.startsWith(".runestone/")
|
||||
)
|
||||
continue;
|
||||
if (entry.kind === "folder") folders.push(entry.rel_path);
|
||||
else if (/\.(md|markdown|mdown)$/i.test(entry.name))
|
||||
files.push(entry.rel_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
Reference in New Issue
Block a user