All files / apps/wp-editor/server/services operations.ts

89.87% Statements 222/247
72.22% Branches 78/108
94.44% Functions 51/54
92.72% Lines 204/220

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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541                                                                        1x   12x   1x 121x   121x   121x     88x   1x 133x   133x   133x     1x 128x   128x   128x     1x 57x 57x   57x   19x   19x   19x     1x         35x 35x   35x 1x     34x     43x 43x       35x           42x       35x   42x         33x   3x 1x     33x   33x     1x 29x 34x   29x   29x         29x                 1x                                                   1x           45x   45x   45x     1x 42x   42x   40x     6x   1x 1x   37x   36x     1x   1x   1x     4x   3x   3x   3x     2x   2x   2x 2x 3x     2x   2x 1x         1x   1x   1x     5x   5x 1x     4x   5x 1x     3x             3x 3x     3x   3x         1x 1x 1x   1x             1x 45x 1x       1x           1x 33x 33x   33x   33x 33x 30x   30x 3x 1x     2x 2x     1x 25x         1x 9x   5x                 1x 25x   24x 24x 23x 25x             25x 21x   21x     13x       1x             19x 19x 79x 19x   19x     19x 31x   31x   31x 31x   22x 22x 22x   9x   9x 1x 1x   8x 8x       31x 2x     2x     29x       19x     15x 4x     1x           6x   6x 6x 6x 6x       8x   4x   4x   21x     6x           6x   5x       1x           15x   15x 15x 15x   15x   8x     12x 32x       8x   7x       1x 20x   20x 20x   20x 20x 23x         21x 20x 20x 20x 20x   20x   19x 19x     20x   20x   15x       1x           6x   6x 6x 6x   6x   5x       11x   8x   26x       5x   5x    
import { markersDiffer } from "../utils/blockMarkers.ts";
import {
    afterEdit,
    appliedText,
    bulkApplyBlocker,
    bulkRestoreBlocker,
    confirm,
    derivedStatus,
    driftRefusal,
    expectedModified,
    gateBlocker,
    holdsText,
    isApplied,
    itemFingerprint,
    isPending,
    markSeen,
    nextChangesetId,
    openBlocker,
    reject,
    restoreBlocker,
    unconfirm,
    unreject,
} from "../../shared/rules.ts";
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 { ItemState } from "../../shared/types/ItemState.ts";
import type { Proposal } from "../../shared/types/Proposal.ts";
import type { RunReport } from "../../shared/types/RunReport.ts";
import { POST_TYPES } from "../../shared/constants.ts";
import { parseKey } from "../utils/itemKey.ts";
import { Refusal } from "../../shared/refusal.ts";
import type { Store } from "../adapters/store.ts";
import type { WordPress } from "../adapters/wordpress.ts";
import { toSnapshot } from "../adapters/wordpress.ts";
 
const MAX_FAILURES_IN_A_ROW = 3;
 
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
 
const keyOf = (key: string) => {
    const parsed = parseKey(key);
 
    Iif (!parsed) throw new Refusal(`"${key}" is not a <posts|pages>-<id> key.`);
 
    return parsed;
};
 
const now = () => new Date().toISOString();
 
const requireChangeset = async (store: Store, id: string): Promise<Changeset> => {
    const changeset = await store.readChangeset(id);
 
    Iif (!changeset) throw new Refusal(`No changeset ${id}.`);
 
    return changeset;
};
 
const requireItem = async (store: Store, id: string, key: ItemKey): Promise<Item> => {
    const item = await store.readItem(id, key);
 
    Iif (!item) throw new Refusal(`${key} is not in changeset ${id}.`);
 
    return item;
};
 
const refreshStatus = async (store: Store, id: string): Promise<Changeset> => {
    const changeset = await requireChangeset(store, id);
    const status = derivedStatus(changeset, await store.readItems(id));
 
    if (status === changeset.status) return changeset;
 
    const next = { ...changeset, status };
 
    await store.writeChangeset(next);
 
    return next;
};
 
export const openChangeset = async (
    store: Store,
    wp: WordPress,
    options: { title: string; instructions?: string; override?: boolean; ids?: string[] },
): Promise<Changeset> => {
    const existing = await store.listChangesets();
    const blocker = openBlocker(existing, !!options.override);
 
    if (blocker) {
        throw new Refusal(`Changeset ${blocker.id} is still open; pass --override to abandon it.`);
    }
 
    const posts = options.ids
        ? await Promise.all(
              [...new Set(options.ids)]
                  .map((key) => keyOf(key))
                  .map(({ type, id }) => wp.get(type, id)),
          )
        : (await Promise.all(POST_TYPES.map((type) => wp.list(type)))).flat();
 
    const changeset: Changeset = {
        id: nextChangesetId(existing, options.title),
        title: options.title,
        instructions: options.instructions ?? "",
        createdAt: now(),
        status: "open",
        keys: posts.map(({ type, id }) => `${type === "page" ? "pages" : "posts"}-${id}` as const),
        scanned: [],
    };
 
    await Promise.all(
        posts.map((post, index) =>
            store.writeBase(changeset.id, changeset.keys[index]!, toSnapshot(post)),
        ),
    );
 
    // Last, so a failed pull leaves the previous changeset open and no half-written one listed.
    await Promise.all(
        existing
            .filter(({ status }) => status === "open")
            .map((open) => store.writeChangeset({ ...open, status: "abandoned" })),
    );
 
    await store.writeChangeset(changeset);
 
    return changeset;
};
 
export const markScanned = async (store: Store, id: string, keys: string[]): Promise<Changeset> => {
    const changeset = await requireChangeset(store, id);
    const unknown = keys.filter((key) => !changeset.keys.includes(key as ItemKey));
 
    Iif (unknown.length > 0) throw new Refusal(`Not in ${id}: ${unknown.join(", ")}.`);
 
    await store.writeChangeset({
        ...changeset,
        scanned: [...new Set([...changeset.scanned, ...(keys as ItemKey[])])],
    });
 
    return refreshStatus(store, id);
};
 
interface ValidateReport {
    removed: ItemKey[];
    markerWarnings: ItemKey[];
}
 
/** Deletes no-op proposals and lists the ones whose block markers drifted from base. */
export const validate = async (store: Store, id: string): Promise<ValidateReport> => {
    const report: ValidateReport = { removed: [], markerWarnings: [] };
 
    for (const item of await store.readItems(id)) {
        const { proposal, base, key } = item;
 
        if (!proposal) continue;
 
        const same =
            proposal.content === base.content &&
            (proposal.title ?? base.title) === base.title &&
            (proposal.excerpt ?? base.excerpt) === base.excerpt;
 
        if (same) {
            report.removed.push(key);
        } else if (markersDiffer(base.content, proposal.content)) {
            report.markerWarnings.push(key);
        }
    }
 
    await Promise.all(report.removed.map((key) => store.writeProposal(id, key, null)));
    await refreshStatus(store, id);
 
    return report;
};
 
const updateState = async (
    store: Store,
    id: string,
    key: ItemKey,
    change: (state: ItemState) => ItemState,
): Promise<ItemState> => {
    const state = change((await requireItem(store, id, key)).state);
 
    await store.writeState(id, key, state);
 
    return state;
};
 
const requirePending = async (store: Store, id: string, key: ItemKey): Promise<Item> => {
    const item = await requireItem(store, id, key);
 
    if (!isPending(item)) throw new Refusal(`${key} has nothing pending to review.`);
 
    return item;
};
 
const isOptionalString = (value: unknown) => value === undefined || typeof value === "string";
 
export const review = {
    seen: (store: Store, id: string, key: ItemKey) => updateState(store, id, key, markSeen),
    confirm: async (store: Store, id: string, key: ItemKey) => {
        await requirePending(store, id, key);
 
        return updateState(store, id, key, confirm);
    },
    unconfirm: async (store: Store, id: string, key: ItemKey) => {
        const { state } = await requirePending(store, id, key);
 
        Iif (state.level !== "confirmed") throw new Refusal(`${key} is not confirmed.`);
 
        return updateState(store, id, key, unconfirm);
    },
    reject: async (store: Store, id: string, key: ItemKey) => {
        await requirePending(store, id, key);
 
        const state = await updateState(store, id, key, reject);
 
        await refreshStatus(store, id);
 
        return state;
    },
    unreject: async (store: Store, id: string, key: ItemKey) => {
        const { state, proposal } = await requireItem(store, id, key);
 
        Iif (!state.rejected || !proposal) throw new Refusal(`${key} is not rejected.`);
 
        const changesets = await store.listChangesets();
        const other = changesets.find(
            (changeset) => changeset.status === "open" && changeset.id !== id,
        );
 
        const reopens = !state.applied && changesets.find((c) => c.id === id)?.status === "closed";
 
        if (other && reopens) {
            throw new Refusal(
                `Undoing this reopens ${id}, but ${other.id} is open; finish it first.`,
            );
        }
 
        const next = await updateState(store, id, key, unreject);
 
        await refreshStatus(store, id);
 
        return next;
    },
    edit: async (store: Store, id: string, key: ItemKey, body: Partial<Proposal> | null) => {
        const item = await requireItem(store, id, key);
 
        if (!item.proposal || isApplied(item)) {
            throw new Refusal(`${key} has no editable proposal.`);
        }
 
        const { content, title, excerpt } = body ?? {};
 
        if (typeof content !== "string" || !isOptionalString(title) || !isOptionalString(excerpt)) {
            throw new Refusal("A proposal is { content, title?, excerpt? }, all strings.");
        }
 
        await store.writeProposal(id, key, {
            content,
            title,
            excerpt,
            reviewRequested: item.proposal.reviewRequested,
        });
 
        const state = await updateState(store, id, key, (current) =>
            afterEdit({ ...current, rejected: undefined }),
        );
 
        await refreshStatus(store, id);
 
        return state;
    },
};
 
/** Refreshes base from live WordPress and sends the item back to unreviewed. */
export const repull = async (store: Store, wp: WordPress, id: string, key: ItemKey) => {
    const { type, id: postId } = keyOf(key);
    const item = await requireItem(store, id, key);
 
    Eif (item.state.applied) throw new Refusal("Applied items can't be re-pulled.");
 
    await store.writeBase(id, key, toSnapshot(await wp.get(type, postId)));
    await store.writeState(id, key, { level: "unreviewed" });
    await refreshStatus(store, id);
};
 
const requireWritable = async (store: Store): Promise<void> => {
    if ((await store.readSettings()).dryRun) {
        throw new Refusal("Dry-run mode is on, so nothing is written to WordPress.");
    }
};
 
const LANDED = "Already live in WordPress, so it was recorded without writing again.";
 
/**
 * Everything an apply checks before it writes, and the item it would write. `landed` is the live
 * timestamp when WordPress already holds the proposal, so the write must not be sent again.
 */
const checkApply = async (store: Store, wp: WordPress, id: string, key: ItemKey) => {
    const { type, id: postId } = keyOf(key);
    const item = await requireItem(store, id, key);
 
    Iif (!isPending(item)) throw new Refusal(`${key} has nothing to apply.`);
 
    const pending = item as Item & { proposal: Proposal };
    const live = await wp.get(type, postId);
    const drift = driftRefusal(expectedModified(item), live.modified_gmt);
 
    if (!drift) return { item: pending, landed: null };
    if (holdsText(toSnapshot(live), appliedText(pending))) {
        return { item: pending, landed: live.modified_gmt };
    }
 
    await store.writeState(id, key, { ...item.state, drift: true });
    throw new Refusal(drift);
};
 
const markerWarning = ({ base, proposal }: Item) =>
    proposal && markersDiffer(base.content, proposal.content)
        ? "Block markers differ from base."
        : null;
 
/** Runs every check an apply would and writes nothing to WordPress. */
export const dryRunItem = async (store: Store, wp: WordPress, id: string, key: ItemKey) => {
    const { item, landed } = await checkApply(store, wp, id, key);
 
    return {
        key,
        warning: landed
            ? "Already live in WordPress; Apply records it without writing again."
            : markerWarning(item),
        fingerprint: itemFingerprint(item),
    };
};
 
const apply = async (store: Store, wp: WordPress, id: string, key: ItemKey) => {
    await requireWritable(store);
 
    const { type, id: postId } = keyOf(key);
    const { item, landed } = await checkApply(store, wp, id, key);
    const modifiedGmt = landed ?? (await wp.update(type, postId, item.proposal)).modified_gmt;
    const state: ItemState = {
        ...item.state,
        drift: undefined,
        restored: undefined,
        applied: { at: now(), modifiedGmt },
    };
 
    await store.writeState(id, key, state);
    await refreshStatus(store, id);
 
    return { state, warning: landed ? LANDED : markerWarning(item) };
};
 
export const applyItem = async (store: Store, wp: WordPress, id: string, key: ItemKey) =>
    (await apply(store, wp, id, key)).state;
 
/** One article at a time, recording each outcome instead of stopping at the first failure. */
const runEach = async (
    kind: RunReport["kind"],
    items: Item[],
    step: (item: Item) => Promise<string | null>,
    save: (report: RunReport) => Promise<void>,
    pauseMs: number,
): Promise<RunReport> => {
    const report: RunReport = { kind, at: now(), ok: [], refused: [], failed: [], warnings: [] };
    const progress = (current?: ItemKey) =>
        save({ ...report, incomplete: true, total: items.length, current });
    let failuresInARow = 0;
 
    await progress();
 
    /* eslint-disable no-await-in-loop -- one article at a time, paced, stopping after a failure run */
    for (const [index, item] of items.entries()) {
        if (index > 0) await sleep(pauseMs);
 
        await progress(item.key);
 
        try {
            const warning = await step(item);
 
            report.ok.push(item.key);
            if (warning) report.warnings.push({ key: item.key, reason: warning });
            failuresInARow = 0;
        } catch (error) {
            const entry = { key: item.key, reason: (error as Error).message };
 
            if (error instanceof Refusal) {
                report.refused.push(entry);
                failuresInARow = 0;
            } else {
                report.failed.push(entry);
                failuresInARow++;
            }
        }
 
        if (failuresInARow === MAX_FAILURES_IN_A_ROW && index < items.length - 1) {
            report.stopped =
                `WordPress failed ${MAX_FAILURES_IN_A_ROW} articles in a row, so the ` +
                `${items.length - index - 1} after them weren't tried.`;
            break;
        }
 
        await progress();
    }
    /* eslint-enable no-await-in-loop */
 
    return report;
};
 
const latestDryRun = async (store: Store, id: string): Promise<RunReport | null> =>
    (await store.listRuns(id)).find(({ kind }) => kind === "dry-run") ?? null;
 
/** Checks every pending article against live WordPress and saves the report bulk apply reads. */
export const bulkDryRun = async (
    store: Store,
    wp: WordPress,
    id: string,
    pauseMs?: number,
): Promise<RunReport> => {
    await requireChangeset(store, id);
 
    const items = await store.readItems(id);
    const settings = await store.readSettings();
    const fingerprints: Partial<Record<ItemKey, string>> = {};
    const report = await runEach(
        "dry-run",
        items.filter(isPending),
        async ({ key }) => {
            const { warning, fingerprint } = await dryRunItem(store, wp, id, key);
 
            fingerprints[key] = fingerprint;
 
            return warning;
        },
        (partial) => store.writeRun(id, { ...partial, fingerprints }),
        pauseMs ?? settings.pauseMs,
    );
    const done: RunReport = {
        ...report,
        fingerprints,
        blocker: gateBlocker(await store.readItems(id), settings),
    };
 
    await store.writeRun(id, done);
 
    return done;
};
 
/** One write at a time with state saved after each, so a stopped run picks up where it left off. */
export const bulkApply = async (
    store: Store,
    wp: WordPress,
    id: string,
    pauseMs?: number,
): Promise<RunReport> => {
    await requireChangeset(store, id);
 
    const items = await store.readItems(id);
    const settings = await store.readSettings();
    const blocker = bulkApplyBlocker(items, settings, await latestDryRun(store, id));
 
    if (blocker) throw new Refusal(blocker);
 
    const report = await runEach(
        "apply",
        items.filter(isPending),
        async ({ key }) => (await apply(store, wp, id, key)).warning,
        (partial) => store.writeRun(id, partial),
        pauseMs ?? settings.pauseMs,
    );
 
    await store.writeRun(id, report);
 
    return report;
};
 
/** Writes this changeset's base back, which is the article as the previous changeset left it. */
export const restoreItem = async (store: Store, wp: WordPress, id: string, key: ItemKey) => {
    const { type, id: postId } = keyOf(key);
 
    await requireChangeset(store, id);
    await requireWritable(store);
 
    const changesets = await store.listChangesets();
    const stack = await Promise.all(
        changesets.map(async (changeset) => ({
            changeset,
            item: await store.readItem(changeset.id, key),
        })),
    );
    const index = stack.findIndex(({ changeset }) => changeset.id === id);
    const own = stack[index]?.item;
    const live = await wp.get(type, postId);
    const landed = !!own && holdsText(toSnapshot(live), own.base);
    const blocker = restoreBlocker(stack, index, live.modified_gmt, landed);
 
    if (blocker) throw new Refusal(blocker);
 
    const { base, state } = own!;
    const modifiedGmt = landed
        ? live.modified_gmt
        : (await wp.update(type, postId, base)).modified_gmt;
    const next: ItemState = { ...state, level: "seen", restored: { at: now(), modifiedGmt } };
 
    await store.writeState(id, key, next);
 
    return next;
};
 
/** Restores every applied article, so a stopped run resumes with only the ones still live. */
export const bulkRestore = async (
    store: Store,
    wp: WordPress,
    id: string,
    pauseMs?: number,
): Promise<RunReport> => {
    await requireChangeset(store, id);
 
    const items = await store.readItems(id);
    const settings = await store.readSettings();
    const blocker = bulkRestoreBlocker(items, settings);
 
    if (blocker) throw new Refusal(blocker);
 
    const report = await runEach(
        "restore",
        items.filter(isApplied),
        async ({ key }) => {
            await restoreItem(store, wp, id, key);
 
            return null;
        },
        (partial) => store.writeRun(id, partial),
        pauseMs ?? settings.pauseMs,
    );
 
    await store.writeRun(id, report);
 
    return report;
};