import { message } from "../storage/message.ts"; export const statuses = ["todo", "doing", "done"] as const; export type Status = (typeof statuses)[number]; export const priorities = ["highest", "high", "medium", "low", "lowest"] as const; export type PriorityLevels = 2 | 3 | 5; export function availablePriorities(levels: PriorityLevels): readonly Priority[] { return levels === 2 ? ["high", "low"] : levels === 3 ? ["high", "medium", "low"] : priorities; } export type Priority = (typeof priorities)[number]; export const priorityNames: Record = { highest: message("Highest"), high: message("High"), medium: message("Medium"), low: message("Low"), lowest: message("Lowest"), }; export const statusNames: Record = { todo: message("To do"), doing: message("In progress"), done: message("Done"), }; export const cardColors = { red: "#df7373", orange: "#d99554", amber: "#dda83e", yellow: "#c5ae4f", lime: "#a4bd58", green: "#63ad84", teal: "#4cafa6", cyan: "#53b8cf", blue: "#729fe0", indigo: "#8790df", purple: "#ac89d8", magenta: "#cb75c8", pink: "#d784b0", brown: "#b48b68", slate: "#8398ae", gray: "#a4a6ad", } as const; export interface Plan { start: string; end: string; } export interface Session { id: string; start: string; end: string; timeZone: string; } export interface TaskFields { createdAt?: string; title?: string; order?: string; color?: string; assignees?: string[]; customFields?: { name: string; value: string }[]; listId?: string | null; placements?: Record; status: Status; tags: string[]; labels?: string[]; priority?: Priority | null; coverImage?: string | null; attachments?: { id: string; name: string }[]; subtasks?: { id: string; title: string; done: boolean; taskId?: string }[]; links?: { taskId: string; relation: "relates" | "blocks" | "blocked-by" }[]; due?: { date: string }; plan?: Plan; sessions: Session[]; archived: boolean; } export interface Task extends TaskFields { id: string; path: string; title: string; body: string; source: string; } export interface Entry { name: string; rel_path: string; kind: string; } export interface Workspace { list(path?: string): Promise; listMarkdown?(): Promise; read(path: string): Promise; readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>; readOptional?(path: string): Promise; write(path: string, contents: string, expected: string): Promise; create?(path: string, contents: string): Promise; subscribe?(listener: () => void): () => void; } export function validDate(value: unknown): value is string { if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false; const date = new Date(`${value}T00:00:00Z`); return !isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value; } export function addDays(value: string, days: number): string { if (!validDate(value)) throw new Error(message("Enter a valid calendar date.")); const date = new Date(`${value}T12:00:00Z`); date.setUTCDate(date.getUTCDate() + days); return date.toISOString().slice(0, 10); } export function dayDistance(start: string, end: string): number { return Math.round( (Date.parse(`${end}T12:00:00Z`) - Date.parse(`${start}T12:00:00Z`)) / 86_400_000, ); } export function localDay(date = new Date()): string { return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; } export function localTime(instant: string): string { const date = new Date(instant); return `${localDay(date)}T${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; } export function localInstant(value: string): string { const date = new Date(value); if (isNaN(date.getTime()) || localTime(date.toISOString()) !== value) throw new Error(message("Enter an existing local date and time.")); return date.toISOString(); } export function validateFields(fields: TaskFields): void { if (fields.createdAt !== undefined && (typeof fields.createdAt !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(fields.createdAt) || !validDate(fields.createdAt.slice(0, 10)) || !Number.isFinite(Date.parse(fields.createdAt)))) throw new Error(message("The card creation timestamp is invalid.")); if (fields.attachments !== undefined && (!Array.isArray(fields.attachments) || fields.attachments.some(item => !item || typeof item.id !== "string" || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(item.id) || typeof item.name !== "string" || !item.name.trim() || item.name.length > 255) || new Set(fields.attachments.map(item => item.id)).size !== fields.attachments.length)) throw new Error(message("Each image attachment needs a unique image ID and a name of 1 to 255 characters.")); if (fields.priority !== undefined && fields.priority !== null && !priorities.includes(fields.priority)) throw new Error(message("Choose a supported priority or No priority.")); if (fields.coverImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(fields.coverImage)) throw new Error(message("Choose an image from this card.")); if (fields.subtasks !== undefined && (!Array.isArray(fields.subtasks) || fields.subtasks.some(item => !item || typeof item.id !== "string" || !item.id || typeof item.title !== "string" || !item.title.trim() || item.title.length > 200 || typeof item.done !== "boolean" || (item.taskId !== undefined && (typeof item.taskId !== "string" || !item.taskId))) || new Set(fields.subtasks.map(item => item.id)).size !== fields.subtasks.length)) throw new Error(message("Each subtask needs a unique ID, a title, and a completion state.")); if (fields.links !== undefined && (!Array.isArray(fields.links) || fields.links.some(item => !item || typeof item.taskId !== "string" || !item.taskId || !["relates", "blocks", "blocked-by"].includes(item.relation)) || new Set(fields.links.map(item => item.taskId)).size !== fields.links.length)) throw new Error(message("Choose each linked card once and select its relationship.")); if ( fields.title !== undefined && (typeof fields.title !== "string" || !fields.title.trim() || fields.title.length > 100 || /[\x00-\x1f]/.test(fields.title)) ) throw new Error(message("Enter a card title of 1 to 100 characters.")); const validOrder = (value: unknown) => value === undefined || (typeof value === "string" && /^[0-9a-z]*[1-9a-z]$/.test(value)); if (!validOrder(fields.order)) throw new Error(message("The card order is invalid. Refresh the board.")); if (fields.placements !== undefined) { if ( !fields.placements || typeof fields.placements !== "object" || Array.isArray(fields.placements) ) throw new Error(message("Board placements must be a mapping.")); for (const [id, placement] of Object.entries(fields.placements)) { if ( !id.trim() || !placement || typeof placement !== "object" || Array.isArray(placement) || (placement.listId !== null && (typeof placement.listId !== "string" || !placement.listId)) || !validOrder(placement.order) ) throw new Error(message("Each board placement needs a board ID and a valid list ID.")); } } if ( fields.color !== undefined && (typeof fields.color !== "string" || !Object.hasOwn(cardColors, fields.color)) ) throw new Error(message("Choose a supported card color.")); if ( fields.assignees !== undefined && (!Array.isArray(fields.assignees) || fields.assignees.some((name) => typeof name !== "string" || !name.trim())) ) throw new Error(message("Assignments must contain names.")); if (fields.customFields !== undefined) { if ( !Array.isArray(fields.customFields) || fields.customFields.some( (field) => !field || typeof field.name !== "string" || !field.name.trim() || typeof field.value !== "string", ) ) throw new Error(message("Each custom field needs a name and a text value.")); const names = fields.customFields.map((field) => field.name.trim().toLocaleLowerCase(), ); if (new Set(names).size !== names.length) throw new Error(message("Use a different name for each custom field.")); } if ( fields.listId !== undefined && fields.listId !== null && (typeof fields.listId !== "string" || !fields.listId) ) throw new Error(message("The task has an invalid list ID.")); if (!statuses.includes(fields.status)) throw new Error(message("Choose a supported task status.")); if ( !Array.isArray(fields.tags) || fields.tags.some((tag) => typeof tag !== "string") ) throw new Error(message("Tags must be text.")); if ( fields.labels !== undefined && (!Array.isArray(fields.labels) || fields.labels.some( (id) => typeof id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(id), ) || new Set(fields.labels).size !== fields.labels.length) ) throw new Error(message("Labels must contain unique saved label IDs.")); if (fields.due && !validDate(fields.due.date)) throw new Error(message("Enter a valid deadline date.")); if ( fields.plan && (!validDate(fields.plan.start) || !validDate(fields.plan.end) || fields.plan.end <= fields.plan.start) ) { throw new Error(message("The planned end must follow the start.")); } const ids = new Set(); for (const session of fields.sessions) { const instant = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/; if ( !session.id || ids.has(session.id) || !instant.test(session.start) || !instant.test(session.end) || !validDate(session.start.slice(0, 10)) || !validDate(session.end.slice(0, 10)) || !Number.isFinite(Date.parse(session.start)) || !Number.isFinite(Date.parse(session.end)) || Date.parse(session.end) <= Date.parse(session.start) ) throw new Error(message("Each session needs a unique ID and a valid time range.")); new Intl.DateTimeFormat("en", { timeZone: session.timeZone }).format(); ids.add(session.id); } }