All files / apps/wp-editor/app/composables useChangeset.ts

0% Statements 0/48
0% Branches 0/12
0% Functions 0/15
0% Lines 0/42

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                                                                                                                                                                                                                                 
import type { Changeset } from "#shared/types/Changeset.ts";
import type { Item } from "#shared/types/Item.ts";
import type { ItemKey } from "#shared/types/ItemKey.ts";
import type { Proposal } from "#shared/types/Proposal.ts";
import type { RunReport } from "#shared/types/RunReport.ts";
import type { Settings } from "#shared/types/Settings.ts";
 
interface ChangesetView {
    changeset: Changeset;
    items: Item[];
    settings: Settings;
    runs: RunReport[];
    bulkBlocker: string | null;
    restoreBlocker: string | null;
}
 
export type ItemAction =
    | "seen"
    | "confirm"
    | "unconfirm"
    | "reject"
    | "unreject"
    | "apply"
    | "dry-run"
    | "restore"
    | "repull";
 
/** The refusal text a server rule put in the 409, falling back to the transport error. */
export const messageOf = (error: unknown): string =>
    (error as { data?: { message?: string } }).data?.message ?? (error as Error).message;
 
const PROGRESS_POLL_MS = 1000;
 
export const useChangeset = (id: string) => {
    const toast = useToast();
    const busy = ref<string | null>(null);
    const running = ref<RunReport["kind"] | null>(null);
    const progress = ref<RunReport | null>(null);
    const request = useFetch<ChangesetView>(`/api/changesets/${id}`, { key: `changeset-${id}` });
    const base = `/api/changesets/${id}`;
    // A plain string path: Nitro's typed-route inference over these templates exceeds tsc's depth.
    const call = <T>(path: string, options: { method: "POST" | "PUT"; body?: Proposal }) =>
        $fetch<T>(`${base}${path}`, options);
 
    /** Runs a write, reports a refusal as a toast, and refreshes the view either way. */
    const run = async <T>(
        label: string,
        write: () => Promise<T>,
        quiet = false,
    ): Promise<T | null> => {
        busy.value = label;
 
        try {
            const result = await write();
 
            if (!quiet) toast.add({ title: label, color: "success", icon: "i-lucide-check" });
 
            return result;
        } catch (error) {
            toast.add({ title: `${label} refused`, description: messageOf(error), color: "error" });
 
            return null;
        } finally {
            busy.value = null;
            await request.refresh();
        }
    };
 
    /** Polls the run's own progress saves while `bulk` waits for the whole run to come back. */
    const watchProgress = async <T>(kind: RunReport["kind"], start: () => Promise<T>) => {
        running.value = kind;
 
        const startedAt = new Date().toISOString();
        let finished = false;
        const check = async () => {
            const latest = await $fetch<RunReport | null>(`${base}/progress`).catch(() => null);
 
            if (!finished) progress.value = latest && latest.at >= startedAt ? latest : null;
        };
        const poll = setInterval(() => void check(), PROGRESS_POLL_MS);
 
        try {
            return await start();
        } finally {
            finished = true;
            clearInterval(poll);
            running.value = null;
            progress.value = null;
        }
    };
 
    return Object.assign(request, {
        busy,
        running,
        progress,
        act: (key: ItemKey, action: ItemAction, quiet = false) =>
            run(
                `${action[0]!.toUpperCase()}${action.slice(1)} ${key}`,
                () => call(`/items/${key}/${action}`, { method: "POST" }),
                quiet,
            ),
        save: (key: ItemKey, proposal: Proposal) =>
            run(`Saved ${key}`, () => call(`/items/${key}`, { method: "PUT", body: proposal })),
        /** Resolves once the view is refreshed, so the new report is `runs[0]`. */
        bulk: (kind: RunReport["kind"]) =>
            run(
                RUN_LABELS[kind].name,
                () => watchProgress(kind, () => call<RunReport>(`/${kind}`, { method: "POST" })),
                true,
            ),
    });
};