iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / src / erase.tsmain at aacbc74

// "Erase and replace": a deployment's whole domain and everything of the earlier iterate are
// erased, and then iterate is deployed as on an empty domain. The list is read from the person's
// own Cloudflare account by the Worker (GET /api/erase, container/takeover.mjs), the person agrees
// to that list on the page (ErasePage.tsx), and the deploy run erases that list and no other.
import { z } from "zod";
import { call, errorOf, queryClient, setState, type DeployState } from "./api.ts";
import { openInWizard, type Deployment } from "./your-deployments.ts";

const ErasedItem = z.object({
  kind: z.string(),
  id: z.string(),
  name: z.string(),
  group: z.enum(["sites", "mail", "dns", "rules", "iterate"]),
  text: z.string(),
  /** "with": it goes with the product that keeps it. "refuse": the run cannot erase it. */
  act: z.enum(["erase", "with", "refuse"]),
});
/** What is on a domain and of its earlier iterate (GET /api/erase). */
const EraseList = z.object({
  zone: z.string(),
  zoneId: z.string().optional(),
  name: z.string(),
  /** The name of this list: the run erases only the list the person saw. */
  digest: z.string().nullable(),
  items: z.array(ErasedItem),
  /** Lists that Cloudflare did not let iterate read. */
  unread: z.array(z.object({ what: z.string(), said: z.string(), must: z.boolean() })),
  /** Why the erase cannot start, in plain words: none when it can. */
  refusals: z.array(z.string()),
});
const Refusal = z.object({ error: z.string() });
export type ErasedItem = z.infer<typeof ErasedItem>;
export type EraseList = z.infer<typeof EraseList>;

export const erasePath = (account: string, domain: string) =>
  `/erase?account=${encodeURIComponent(account)}&domain=${encodeURIComponent(domain)}`;

/** The hand-over from "Your deployments": the page that shows what is erased. */
export const eraseAndReplace: ((deployment: Deployment) => void) | null = (deployment) =>
  location.assign(erasePath(deployment.account.id, deployment.domain));

/** The list, read now. Not a row in the wizard's log: nothing changed. */
export async function readEraseList(
  account: string,
  domain: string,
): Promise<{ ok: boolean; status: number; error?: string; list?: EraseList }> {
  const answer = await fetch(`/api/erase?account=${account}&zone=${domain}`).catch(() => null);
  const said: unknown = await answer?.json().catch(() => null);
  const list = answer?.ok ? EraseList.safeParse(said) : null;
  if (!list?.success)
    return {
      ok: false,
      status: answer?.status || 0,
      error: Refusal.safeParse(said).data?.error,
    };
  return { ok: true, status: answer?.status || 200, list: list.data };
}

/** Starts the run that erases `list` and then deploys iterate with `email` as its owner. Answers
 *  what went wrong, or null: the run goes, and the wizard's Deploy step shows it. */
export async function startErase(
  account: { id: string; name: string },
  list: EraseList,
  email: string,
  typed: string,
): Promise<string | null> {
  if (!list.zoneId || !list.digest) return "Read the list again.";
  const started = await call("POST", "/api/deploy", {
    account: account.id,
    zone: list.zone,
    zoneId: list.zoneId,
    email,
    erase: list.digest,
    typed,
  });
  void queryClient.invalidateQueries({ queryKey: ["quiet"] });
  if (started.status === 401) return "Your access to Cloudflare ended. Connect Cloudflare again.";
  if (!started.ok) return errorOf(started);
  queryClient.setQueryData([`/api/deploy?account=${account.id}&zone=${list.zone}`], started);
  setState((wizard) => ({
    me: wizard.me && { ...wizard.me, connected: !!started.connected },
  }));
  // `owner`: a later "Try again" of the wizard deploys for the same address
  openInWizard({
    account,
    domain: list.zone,
    zone: { id: list.zoneId, name: list.zone, status: "active", nameServers: [] },
    owner: email,
  });
  return null;
}

/** A run that stopped because the iterate on the domain is from before 11 November 2026, which
 *  this version cannot update (container/run.sh `not_older_stack`): the way on is the erase. */
export const olderStack = (state: DeployState) =>
  state.status === "failed" &&
  state.lines.some((line) =>
    line.startsWith("Stopped: This iterate is from before a large change."),
  );

/** A run that stopped before any change because this deployment cannot be updated from iterate
 *  Cloud (container/run.sh `stack_updatable`): its vault key is kept outside Cloudflare, or its
 *  sandbox image is built with Docker. Or it runs an iterate that this Cloud does not have
 *  (`not_unknown_stack`), which only "Update anyway" on its card replaces. Another try from here
 *  stops at the same place. */
export const notFromHere = (state: DeployState) =>
  state.status === "failed" &&
  state.lines.some(
    (line) =>
      line.startsWith("Stopped: This deployment keeps its vault key outside Cloudflare.") ||
      line.startsWith("Stopped: This deployment builds its sandbox image with Docker") ||
      line.startsWith("Stopped: This deployment runs iterate at "),
  );

/** A run that was to erase and stopped before the erase was done: a deploy must not follow it. */
export const eraseUndone = (state: DeployState) =>
  state.status === "failed" && state.erase === true && !state.erased;