All files / apps/developer-portal/layers/workflows/shared capability.ts

92.1% Statements 70/76
81.81% Branches 54/66
90% Functions 18/20
92.42% Lines 61/66

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            48x 503x   13x 503x   503x 13x           503x     48x 503x         503x 503x 503x 503x   503x 1x         503x   503x         503x 1x         503x   503x 1x     503x                                                   2x                           48x 424x 4x 15x 7x   986x         214x                   48x 442x 193x 193x   193x 546x   546x 545x   442x 442x 106x 106x   439x 439x   439x     193x 440x 440x     192x       48x       638x   500x   172x 172x 172x     244x 638x             48x 192x 192x    
import { asText, isRecord, type Reader } from "./reader.ts";
import { COMPLEXITY_SCALE, KINDS, REUSE_PLANS, STAGE_NEED_PREFIX } from "./constants.ts";
import type { Capability } from "./types/Capability.ts";
import type { Kind } from "./types/Kind.ts";
import type { ReusePlan } from "./types/ReusePlan.ts";
 
const readReuse = (reader: Reader, raw: unknown, where: string): Capability["reuse"] => {
    if (raw === undefined) return null;
 
    const rawReuse = isRecord(raw) ? raw : {};
    const plan = asText(rawReuse.plan) ?? "";
 
    if ((REUSE_PLANS as readonly string[]).includes(plan)) {
        return { plan: plan as ReusePlan, from: asText(rawReuse.from) };
    }
 
    reader.problems.push(
        `${where}: \`reuse.plan: ${plan || "(missing)"}\` isn't one of ${REUSE_PLANS.join(", ")}`,
    );
    return null;
};
 
export const readCapability = (reader: Reader, raw: unknown, index: number): Capability | null => {
    Iif (!isRecord(raw)) {
        reader.problems.push(`capability #${index + 1} isn't a mapping`);
        return null;
    }
 
    const id = reader.text(raw, "id", `capability #${index + 1}`);
    const where = `capability \`${id || index + 1}\``;
    const onDemand = raw.onDemand === true;
    const optional = raw.optional === true;
 
    if (onDemand && optional) {
        reader.problems.push(
            `${where}: an \`onDemand\` block has no switch, so it can't be \`optional\``,
        );
    }
 
    const reuse = readReuse(reader, raw.reuse, where);
    const complexity =
        typeof raw.complexity === "number" &&
        (COMPLEXITY_SCALE as readonly number[]).includes(raw.complexity)
            ? raw.complexity
            : null;
 
    if (raw.complexity !== undefined && complexity === null) {
        reader.problems.push(
            `${where}: \`complexity: ${JSON.stringify(raw.complexity)}\` isn't one of ${COMPLEXITY_SCALE.join(", ")}`,
        );
    }
 
    const kind = asText(raw.kind) ?? "build";
 
    if (!(KINDS as readonly string[]).includes(kind)) {
        reader.problems.push(`${where}: \`kind: ${kind}\` isn't one of ${KINDS.join(", ")}`);
    }
 
    return {
        id,
        stage: reader.text(raw, "stage", where),
        group: asText(raw.group),
        title: reader.text(raw, "title", where),
        summary: reader.text(raw, "summary", where, ""),
        kind: (KINDS as readonly string[]).includes(kind) ? (kind as Kind) : "build",
        optional,
        default: optional ? raw.default === true : true,
        onDemand,
        dependsOn: reader.texts(raw, "dependsOn", where),
        doneWhen: reader.texts(raw, "doneWhen", where),
        reuse,
        lessons: reader.list(raw, "lessons", where).flatMap((lesson) =>
            isRecord(lesson)
                ? [
                      {
                          text: reader.text(lesson, "text", `${where} lesson`),
                          issues: reader
                              .list(lesson, "issues", `${where} lesson`)
                              .filter((issue): issue is number => typeof issue === "number"),
                      },
                  ]
                : [],
        ),
        tickets: reader.list(raw, "tickets", where).flatMap((ticket) =>
            isRecord(ticket)
                ? [
                      {
                          title: reader.text(ticket, "title", `${where} ticket`),
                          criteria: reader.texts(ticket, "criteria", `${where} ticket`),
                      },
                  ]
                : [],
        ),
        complexity,
    };
};
 
/** The blocks with each `stage:<id>` need swapped for every other block in that stage. */
export const withStageNeeds = (capabilities: Capability[]): Capability[] => {
    const inStage = (stage: string, except: string): string[] =>
        capabilities
            .filter((other) => other.stage === stage && other.id !== except)
            .map(({ id }) => id);
 
    return capabilities.map((capability) => ({
        ...capability,
        dependsOn: [
            ...new Set(
                capability.dependsOn.flatMap((need) =>
                    need.startsWith(STAGE_NEED_PREFIX)
                        ? inStage(need.slice(STAGE_NEED_PREFIX.length), capability.id)
                        : [need],
                ),
            ),
        ],
    }));
};
 
/** The first loop of `dependsOn` links found, as the ids walked round it, or null when there is none. */
export const dependencyCycle = (capabilities: Capability[]): string[] | null => {
    const needs = new Map(capabilities.map(({ id, dependsOn }) => [id, dependsOn]));
    const finished = new Set<string>();
    const path: string[] = [];
 
    const walk = (id: string): string[] | null => {
        const at = path.indexOf(id);
 
        if (at >= 0) return [...path.slice(at), id];
        if (finished.has(id) || !needs.has(id)) return null;
 
        path.push(id);
        for (const need of needs.get(id) ?? []) {
            const cycle = walk(need);
            if (cycle) return cycle;
        }
        path.pop();
        finished.add(id);
 
        return null;
    };
 
    for (const { id } of capabilities) {
        const cycle = walk(id);
        if (cycle) return cycle;
    }
 
    return null;
};
 
/** What each block needs once switched-off blocks are taken out: their own needs take their place. */
export const routedNeeds = (
    all: Capability[],
    isOn: (capability: Capability) => boolean,
): Map<string, string[]> => {
    const byId = new Map(all.map((capability) => [capability.id, capability]));
 
    const needsOf = (id: string, seen: Set<string>): string[] =>
        (byId.get(id)?.dependsOn ?? []).flatMap((need) => {
            const dependency = byId.get(need);
            Iif (!dependency || seen.has(need)) return [];
            return isOn(dependency) ? [need] : needsOf(need, new Set([...seen, need]));
        });
 
    return new Map(
        all.map((capability) => [
            capability.id,
            isOn(capability) ? [...new Set(needsOf(capability.id, new Set([capability.id])))] : [],
        ]),
    );
};
 
export const cycleProblem = (capabilities: Capability[]): string[] => {
    const cycle = dependencyCycle(capabilities);
    return cycle ? [`\`dependsOn\` goes round in a loop: ${cycle.join(" → ")}`] : [];
};