All files / apps/developer-portal/layers/workflows/server/utils workflows.ts

94.04% Statements 158/168
86.29% Branches 107/124
100% Functions 24/24
97.61% Lines 123/126

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275                                      95x   1x 47x   47x       1x   1x 29x   224x   1x 23x 6x 10x     6x 2x   4x     21x       1x       9x   9x 5x   5x 5x   5x 6x 6x 18x     6x 5x 5x 3x 1x     2x 2x     1x     1x 21x 21x     21x       1x 5x   5x     1x           14x   13x           65x 13x 14x   14x 13x 12x 11x       11x 14x   14x   9x   9x   5x   5x                     14x 14x                 5x 5x       1x           14x 56x   14x 13x   12x   14x     14x   11x   11x 1x 10x 1x     36x 9x 1x   9x 9x   9x       1x         7x 7x   7x 6x 1x     5x 1x 1x 1x 1x     4x 4x   4x 1x   3x   2x 2x 2x   2x             1x 46x 46x   46x   41x 41x   41x 27x   25x 2x 2x 2x     23x   23x   23x   23x       23x 9x 2x   21x   12x 12x    
import { existsSync } from "node:fs";
import { readFile, rm, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { isMap, parseDocument, type Document } from "yaml";
import {
    assembleWorkflows,
    diaryHeader,
    PROJECT_ID,
    projectYaml,
    SETTLED_STATES,
    TICKET_SIZES,
    type NewPage,
    type ProjectView,
    type Template,
    type TicketSize,
    type Workflows,
} from "../../shared/workflows.ts";
import { readWorkflowFiles } from "./workflowFiles.ts";
 
const workflowsDir = (): string => String(useRuntimeConfig().workflowsDir);
 
export const loadWorkflows = async (): Promise<Workflows> => {
    const { templates, projects, snapshots } = await readWorkflowFiles(workflowsDir());
 
    return assembleWorkflows(templates, projects, snapshots);
};
 
/** The project fields the page edits; the template stays, since its switches and settled blocks belong to it. */
const DETAILS = ["title", "summary", "milestone", "area"] as const;
 
const isRecord = (value: unknown): value is Record<string, unknown> =>
    value !== null && typeof value === "object" && !Array.isArray(value);
 
const textOf = (value: unknown): string => (typeof value === "string" ? value.trim() : "");
 
const switchProblem = (template: Template, switches: Record<string, unknown>): string | null => {
    for (const [key, on] of Object.entries(switches)) {
        const switchable = [...template.capabilities, ...template.groups].find(
            (candidate) => candidate.id === key,
        );
 
        if (!switchable?.optional) {
            return `\`${key}\` isn't an optional capability or group of ${template.id}`;
        }
        Iif (typeof on !== "boolean") return "a switch is on or off";
    }
 
    return null;
};
 
/** The pages a new project adds, each an extra naming one of the template's page types. */
const readPages = (
    template: Template,
    raw: unknown,
): { pages: NewPage[] } | { problem: string } => {
    const failed = (problem: string) => ({ problem });
 
    if (raw === undefined) return { pages: [] };
    Iif (!Array.isArray(raw)) return failed("the pages are a list");
 
    const taken = new Set(template.capabilities.map(({ id }) => id));
    const pages: NewPage[] = [];
 
    for (const entry of raw) {
        const page = isRecord(entry) ? entry : {};
        const [id = "", type = "", title = ""] = ["id", "type", "title"].map((key) =>
            textOf(page[key]),
        );
 
        if (!title) return failed("a page needs a title");
        Iif (!PROJECT_ID.test(id)) return failed(`\`${id}\` isn't a kebab-case page id`);
        if (taken.has(id)) return failed(`\`${id}\` is already taken in ${template.id}`);
        if (!template.types.some((candidate) => candidate.id === type)) {
            return failed(`\`${type || "(none)"}\` isn't a page type of ${template.id}`);
        }
 
        taken.add(id);
        pages.push({ id, type, title });
    }
 
    return { pages };
};
 
const milestoneProblem = (workflows: Workflows, id: string, milestone: string): string | null => {
    const owner = workflows.projects.find(
        ({ project }) => project.id !== id && project.milestone === milestone,
    );
 
    return owner ? `\`${milestone}\` is already ${owner.project.id}'s milestone` : null;
};
 
/** Opens the project's diary, keeping the one a dropped project of the same id left. */
const startDiary = async (id: string, title: string): Promise<void> => {
    const path = resolve(workflowsDir(), "projects", `${id}.diary.md`);
 
    if (!existsSync(path)) await writeFile(path, diaryHeader(title), "utf8");
};
 
const createProject = async (
    edit: Record<string, unknown>,
    id: string,
    path: string,
    workflows: Workflows,
): Promise<string | null> => {
    if (existsSync(path)) return `${id} already exists`;
 
    const [title, templateId, area, milestone, summary] = [
        "title",
        "template",
        "area",
        "milestone",
        "summary",
    ].map((key) => textOf(edit[key]));
    const ticketSize = textOf(edit.ticketSize) || "block";
    const template = workflows.templates.find((candidate) => candidate.id === templateId);
 
    Iif (!title) return "a project needs a title";
    if (!milestone) return "a project needs a milestone";
    if (!template) return `\`${templateId || "(none)"}\` names no template`;
    Iif (!(TICKET_SIZES as readonly string[]).includes(ticketSize)) {
        return `\`${ticketSize}\` isn't a ticket size`;
    }
 
    const switches = isRecord(edit.switches) ? edit.switches : {};
    const problem = switchProblem(template, switches) ?? milestoneProblem(workflows, id, milestone);
 
    if (problem) return problem;
 
    const read = readPages(template, edit.extras);
 
    if ("problem" in read) return read.problem;
 
    const extras = read.pages;
 
    const project = {
        id,
        title,
        template: template.id,
        area: area ?? "",
        milestone,
        summary: summary ?? "",
        switches: switches as Record<string, boolean>,
        extras,
    };
 
    try {
        await writeFile(path, projectYaml({ ...project, ticketSize: ticketSize as TicketSize }), {
            encoding: "utf8",
            flag: "wx",
        });
    } catch (error) {
        if ((error as NodeJS.ErrnoException).code === "EEXIST") return `${id} already exists`;
        throw error;
    }
 
    await startDiary(id, title);
    return null;
};
 
/** Applies a settings edit to the parsed project file, or returns why it can't. */
const editSettings = (
    edit: Record<string, unknown>,
    document: Document,
    view: ProjectView,
    workflows: Workflows,
): string | null => {
    const { id } = view.project;
    const details = Object.fromEntries(DETAILS.map((key) => [key, textOf(edit[key])] as const));
 
    if (!details.title) return "a project needs a title";
    if (!details.milestone) return "a project needs a milestone";
 
    const switches = isRecord(edit.switches) ? edit.switches : {};
    const problem =
        switchProblem(view.template, switches) ??
        milestoneProblem(workflows, id, details.milestone ?? "");
 
    if (problem) return problem;
 
    const size = textOf(edit.ticketSize);
 
    if (!(TICKET_SIZES as readonly string[]).includes(size))
        return `\`${size}\` isn't a ticket size`;
    if (size !== view.project.ticketSize && view.tickets.filed > 0) {
        return "the ticket size is fixed once a ticket is filed";
    }
 
    for (const [key, value] of Object.entries(details)) document.set(key, value);
    if (Object.keys(switches).length > 0 && !isMap(document.get("switches"))) {
        document.set("switches", document.createNode({}));
    }
    for (const [key, on] of Object.entries(switches)) document.setIn(["switches", key], on);
    if (size !== view.project.ticketSize) document.set("ticketSize", size);
 
    return null;
};
 
/** Settles a block that has no ticket, or with no `status` takes its settlement back. */
const editSettle = (
    edit: Record<string, unknown>,
    document: Document,
    view: ProjectView,
): string | null => {
    const block = textOf(edit.block);
    const capability = view.capabilities.find(({ id }) => id === block);
 
    if (!capability?.enabled) return `\`${block}\` isn't a block this project has on`;
    if (capability.issues.some(({ reason }) => reason !== "not_planned")) {
        return `${capability.title} has tickets, so it is finished by closing them on GitHub`;
    }
 
    if (edit.status === null) {
        document.deleteIn(["settled", block]);
        const settled = document.get("settled");
        Eif (isMap(settled) && settled.items.length === 0) document.delete("settled");
        return null;
    }
 
    const status = textOf(edit.status);
    const note = textOf(edit.note);
 
    if (!(SETTLED_STATES as readonly string[]).includes(status)) {
        return `\`${status}\` isn't one of ${SETTLED_STATES.join(", ")}`;
    }
    if (!note) return "a settled block needs a note saying why";
 
    Eif (!isMap(document.get("settled"))) document.set("settled", document.createNode({}));
    const on = new Date().toISOString().slice(0, 10);
    document.setIn(["settled", block], document.createNode({ status, on, note }));
 
    return null;
};
 
/**
 * One edit to a project file through the YAML document model, so the comments and layout a person
 * wrote survive the round trip. Returns a problem, or null once the file is written.
 */
export const applyEdit = async (body: unknown): Promise<string | null> => {
    const edit = body !== null && typeof body === "object" ? (body as Record<string, unknown>) : {};
    const id = textOf(edit.project);
 
    if (!PROJECT_ID.test(id)) return `\`${id}\` isn't a kebab-case project id`;
 
    const path = resolve(workflowsDir(), "projects", `${id}.yaml`);
    const workflows = await loadWorkflows();
 
    if (edit.action === "create") return createProject(edit, id, path, workflows);
    if (!existsSync(path)) return `${id} doesn't exist`;
 
    if (edit.action === "delete") {
        await rm(path);
        await rm(resolve(workflowsDir(), "projects", `${id}.snapshot.json`), { force: true });
        return null;
    }
 
    const view = workflows.projects.find(({ project }) => project.id === id);
 
    Iif (!view) return `${id}.yaml names no template, so it can't be edited here`;
 
    const document = parseDocument(await readFile(path, "utf8"));
 
    Iif (document.errors.length > 0) return `${id}.yaml doesn't parse`;
 
    let problem: string | null;
 
    if (edit.action === "settings") problem = editSettings(edit, document, view, workflows);
    else if (edit.action === "settle") problem = editSettle(edit, document, view);
    else return `\`${String(edit.action)}\` isn't an edit`;
 
    if (problem) return problem;
 
    await writeFile(path, document.toString({ lineWidth: 0 }), "utf8");
    return null;
};